Overview Package Class Source Class tree Glossary
previous class      next class frames      no frames

U2AI.U2NPCControllerBasic


00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159
00160
00161
00162
00163
00164
00165
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203
00204
00205
00206
00207
00208
00209
00210
00211
00212
00213
00214
00215
00216
00217
00218
00219
00220
00221
00222
00223
00224
00225
00226
00227
00228
00229
00230
00231
00232
00233
00234
00235
00236
00237
00238
00239
00240
00241
00242
00243
00244
00245
00246
00247
00248
00249
00250
00251
00252
00253
00254
00255
00256
00257
00258
00259
00260
00261
00262
00263
00264
00265
00266
00267
00268
00269
00270
00271
00272
00273
00274
00275
00276
00277
00278
00279
00280
00281
00282
00283
00284
00285
00286
00287
00288
00289
00290
00291
00292
00293
00294
00295
00296
00297
00298
00299
00300
00301
00302
00303
00304
00305
00306
00307
00308
00309
00310
00311
00312
00313
00314
00315
00316
00317
00318
00319
00320
00321
00322
00323
00324
00325
00326
00327
00328
00329
00330
00331
00332
00333
00334
00335
00336
00337
00338
00339
00340
00341
00342
00343
00344
00345
00346
00347
00348
00349
00350
00351
00352
00353
00354
00355
00356
00357
00358
00359
00360
00361
00362
00363
00364
00365
00366
00367
00368
00369
00370
00371
00372
00373
00374
00375
00376
00377
00378
00379
00380
00381
00382
00383
00384
00385
00386
00387
00388
00389
00390
00391
00392
00393
00394
00395
00396
00397
00398
00399
00400
00401
00402
00403
00404
00405
00406
00407
00408
00409
00410
00411
00412
00413
00414
00415
00416
00417
00418
00419
00420
00421
00422
00423
00424
00425
00426
00427
00428
00429
00430
00431
00432
00433
00434
00435
00436
00437
00438
00439
00440
00441
00442
00443
00444
00445
00446
00447
00448
00449
00450
00451
00452
00453
00454
00455
00456
00457
00458
00459
00460
00461
00462
00463
00464
00465
00466
00467
00468
00469
00470
00471
00472
00473
00474
00475
00476
00477
00478
00479
00480
00481
00482
00483
00484
00485
00486
00487
00488
00489
00490
00491
00492
00493
00494
00495
00496
00497
00498
00499
00500
00501
00502
00503
00504
00505
00506
00507
00508
00509
00510
00511
00512
00513
00514
00515
00516
00517
00518
00519
00520
00521
00522
00523
00524
00525
00526
00527
00528
00529
00530
00531
00532
00533
00534
00535
00536
00537
00538
00539
00540
00541
00542
00543
00544
00545
00546
00547
00548
00549
00550
00551
00552
00553
00554
00555
00556
00557
00558
00559
00560
00561
00562
00563
00564
00565
00566
00567
00568
00569
00570
00571
00572
00573
00574
00575
00576
00577
00578
00579
00580
00581
00582
00583
00584
00585
00586
00587
00588
00589
00590
00591
00592
00593
00594
00595
00596
00597
00598
00599
00600
00601
00602
00603
00604
00605
00606
00607
00608
00609
00610
00611
00612
00613
00614
00615
00616
00617
00618
00619
00620
00621
00622
00623
00624
00625
00626
00627
00628
00629
00630
00631
00632
00633
00634
00635
00636
00637
00638
00639
00640
00641
00642
00643
00644
00645
00646
00647
00648
00649
00650
00651
00652
00653
00654
00655
00656
00657
00658
00659
00660
00661
00662
00663
00664
00665
00666
00667
00668
00669
00670
00671
00672
00673
00674
00675
00676
00677
00678
00679
00680
00681
00682
00683
00684
00685
00686
00687
00688
00689
00690
00691
00692
00693
00694
00695
00696
00697
00698
00699
00700
00701
00702
00703
00704
00705
00706
00707
00708
00709
00710
00711
00712
00713
00714
00715
00716
00717
00718
00719
00720
00721
00722
00723
00724
00725
00726
00727
00728
00729
00730
00731
00732
00733
00734
00735
00736
00737
00738
00739
00740
00741
00742
00743
00744
00745
00746
00747
00748
00749
00750
00751
00752
00753
00754
00755
00756
00757
00758
00759
00760
00761
00762
00763
00764
00765
00766
00767
00768
00769
00770
00771
00772
00773
00774
00775
00776
00777
00778
00779
00780
00781
00782
00783
00784
00785
00786
00787
00788
00789
00790
00791
00792
00793
00794
00795
00796
00797
00798
00799
00800
00801
00802
00803
00804
00805
00806
00807
00808
00809
00810
00811
00812
00813
00814
00815
00816
00817
00818
00819
00820
00821
00822
00823
00824
00825
00826
00827
00828
00829
00830
00831
00832
00833
00834
00835
00836
00837
00838
00839
00840
00841
00842
00843
00844
00845
00846
00847
00848
00849
00850
00851
00852
00853
00854
00855
00856
00857
00858
00859
00860
00861
00862
00863
00864
00865
00866
00867
00868
00869
00870
00871
00872
00873
00874
00875
00876
00877
00878
00879
00880
00881
00882
00883
00884
00885
00886
00887
00888
00889
00890
00891
00892
00893
00894
00895
00896
00897
00898
00899
00900
00901
00902
00903
00904
00905
00906
00907
00908
00909
00910
00911
00912
00913
00914
00915
00916
00917
00918
00919
00920
00921
00922
00923
00924
00925
00926
00927
00928
00929
00930
00931
00932
00933
00934
00935
00936
00937
00938
00939
00940
00941
00942
00943
00944
00945
00946
00947
00948
00949
00950
00951
00952
00953
00954
00955
00956
00957
00958
00959
00960
00961
00962
00963
00964
00965
00966
00967
00968
00969
00970
00971
00972
00973
00974
00975
00976
00977
00978
00979
00980
00981
00982
00983
00984
00985
00986
00987
00988
00989
00990
00991
00992
00993
00994
00995
00996
00997
00998
00999
01000
01001
01002
01003
01004
01005
01006
01007
01008
01009
01010
01011
01012
01013
01014
01015
01016
01017
01018
01019
01020
01021
01022
01023
01024
01025
01026
01027
01028
01029
01030
01031
01032
01033
01034
01035
01036
01037
01038
01039
01040
01041
01042
01043
01044
01045
01046
01047
01048
01049
01050
01051
01052
01053
01054
01055
01056
01057
01058
01059
01060
01061
01062
01063
01064
01065
01066
01067
01068
01069
01070
01071
01072
01073
01074
01075
01076
01077
01078
01079
01080
01081
01082
01083
01084
01085
01086
01087
01088
01089
01090
01091
01092
01093
01094
01095
01096
01097
01098
01099
01100
01101
01102
01103
01104
01105
01106
01107
01108
01109
01110
01111
01112
01113
01114
01115
01116
01117
01118
01119
01120
01121
01122
01123
01124
01125
01126
01127
01128
01129
01130
01131
01132
01133
01134
01135
01136
01137
01138
01139
01140
01141
01142
01143
01144
01145
01146
01147
01148
01149
01150
01151
01152
01153
01154
01155
01156
01157
01158
01159
01160
01161
01162
01163
01164
01165
01166
01167
01168
01169
01170
01171
01172
01173
01174
01175
01176
01177
01178
01179
01180
01181
01182
01183
01184
01185
01186
01187
01188
01189
01190
01191
01192
01193
01194
01195
01196
01197
01198
01199
01200
01201
01202
01203
01204
01205
01206
01207
01208
01209
01210
01211
01212
01213
01214
01215
01216
01217
01218
01219
01220
01221
01222
01223
01224
01225
01226
01227
01228
01229
01230
01231
01232
01233
01234
01235
01236
01237
01238
01239
01240
01241
01242
01243
01244
01245
01246
01247
01248
01249
01250
01251
01252
01253
01254
01255
01256
01257
01258
01259
01260
01261
01262
01263
01264
01265
01266
01267
01268
01269
01270
01271
01272
01273
01274
01275
01276
01277
01278
01279
01280
01281
01282
01283
01284
01285
01286
01287
01288
01289
01290
01291
01292
01293
01294
01295
01296
01297
01298
01299
01300
01301
01302
01303
01304
01305
01306
01307
01308
01309
01310
01311
01312
01313
01314
01315
01316
01317
01318
01319
01320
01321
01322
01323
01324
01325
01326
01327
01328
01329
01330
01331
01332
01333
01334
01335
01336
01337
01338
01339
01340
01341
01342
01343
01344
01345
01346
01347
01348
01349
01350
01351
01352
01353
01354
01355
01356
01357
01358
01359
01360
01361
01362
01363
01364
01365
01366
01367
01368
01369
01370
01371
01372
01373
01374
01375
01376
01377
01378
01379
01380
01381
01382
01383
01384
01385
01386
01387
01388
01389
01390
01391
01392
01393
01394
01395
01396
01397
01398
01399
01400
01401
01402
01403
01404
01405
01406
01407
01408
01409
01410
01411
01412
01413
01414
01415
01416
01417
01418
01419
01420
01421
01422
01423
01424
01425
01426
01427
01428
01429
01430
01431
01432
01433
01434
01435
01436
01437
01438
01439
01440
01441
01442
01443
01444
01445
01446
01447
01448
01449
01450
01451
01452
01453
01454
01455
01456
01457
01458
01459
01460
01461
01462
01463
01464
01465
01466
01467
01468
01469
01470
01471
01472
01473
01474
01475
01476
01477
01478
01479
01480
01481
01482
01483
01484
01485
01486
01487
01488
01489
01490
01491
01492
01493
01494
01495
01496
01497
01498
01499
01500
01501
01502
01503
01504
01505
01506
01507
01508
01509
01510
01511
01512
01513
01514
01515
01516
01517
01518
01519
01520
01521
01522
01523
01524
01525
01526
01527
01528
01529
01530
01531
01532
01533
01534
01535
01536
01537
01538
01539
01540
01541
01542
01543
01544
01545
01546
01547
01548
01549
01550
01551
01552
01553
01554
01555
01556
01557
01558
01559
01560
01561
01562
01563
01564
01565
01566
01567
01568
01569
01570
01571
01572
01573
01574
01575
01576
01577
01578
01579
01580
01581
01582
01583
01584
01585
01586
01587
01588
01589
01590
01591
01592
01593
01594
01595
01596
01597
01598
01599
01600
01601
01602
01603
01604
01605
01606
01607
01608
01609
01610
01611
01612
01613
01614
01615
01616
01617
01618
01619
01620
01621
01622
01623
01624
01625
01626
01627
01628
01629
01630
01631
01632
01633
01634
01635
01636
01637
01638
01639
01640
01641
01642
01643
01644
01645
01646
01647
01648
01649
01650
01651
01652
01653
01654
01655
01656
01657
01658
01659
01660
01661
01662
01663
01664
01665
01666
01667
01668
01669
01670
01671
01672
01673
01674
01675
01676
01677
01678
01679
01680
01681
01682
01683
01684
01685
01686
01687
01688
01689
01690
01691
01692
01693
01694
01695
01696
01697
01698
01699
01700
01701
01702
01703
01704
01705
01706
01707
01708
01709
01710
01711
01712
01713
01714
01715
01716
01717
01718
01719
01720
01721
01722
01723
01724
01725
01726
01727
01728
01729
01730
01731
01732
01733
01734
01735
01736
01737
01738
01739
01740
01741
01742
01743
01744
01745
01746
01747
01748
01749
01750
01751
01752
01753
01754
01755
01756
01757
01758
01759
01760
01761
01762
01763
01764
01765
01766
01767
01768
01769
01770
01771
01772
01773
01774
01775
01776
01777
01778
01779
01780
01781
01782
01783
01784
01785
01786
01787
01788
01789
01790
01791
01792
01793
01794
01795
01796
01797
01798
01799
01800
01801
01802
01803
01804
01805
01806
01807
01808
01809
01810
01811
01812
01813
01814
01815
01816
01817
01818
01819
01820
01821
01822
01823
01824
01825
01826
01827
01828
01829
01830
01831
01832
01833
01834
01835
01836
01837
01838
01839
01840
01841
01842
01843
01844
01845
01846
01847
01848
01849
01850
01851
01852
01853
01854
01855
01856
01857
01858
01859
01860
01861
01862
01863
01864
01865
01866
01867
01868
01869
01870
01871
01872
01873
01874
01875
01876
01877
01878
01879
01880
01881
01882
01883
01884
01885
01886
01887
01888
01889
01890
01891
01892
01893
01894
01895
01896
01897
01898
01899
01900
01901
01902
01903
01904
01905
01906
01907
01908
01909
01910
01911
01912
01913
01914
01915
01916
01917
01918
01919
01920
01921
01922
01923
01924
01925
01926
01927
01928
01929
01930
01931
01932
01933
01934
01935
01936
01937
01938
01939
01940
01941
01942
01943
01944
01945
01946
01947
01948
01949
01950
01951
01952
01953
01954
01955
01956
01957
01958
01959
01960
01961
01962
01963
01964
01965
01966
01967
01968
01969
01970
01971
01972
01973
01974
01975
01976
01977
01978
01979
01980
01981
01982
01983
01984
01985
01986
01987
01988
01989
01990
01991
01992
01993
01994
01995
01996
01997
01998
01999
02000
02001
02002
02003
02004
02005
02006
02007
02008
02009
02010
02011
02012
02013
02014
02015
02016
02017
02018
02019
02020
02021
02022
02023
02024
02025
02026
02027
02028
02029
02030
02031
02032
02033
02034
02035
02036
02037
02038
02039
02040
02041
02042
02043
02044
02045
02046
02047
02048
02049
02050
02051
02052
02053
02054
02055
02056
02057
02058
02059
02060
02061
02062
02063
02064
02065
02066
02067
02068
02069
02070
02071
02072
02073
02074
02075
02076
02077
02078
02079
02080
02081
02082
02083
02084
02085
02086
02087
02088
02089
02090
02091
02092
02093
02094
02095
02096
02097
02098
02099
02100
02101
02102
02103
02104
02105
02106
02107
02108
02109
02110
02111
02112
02113
02114
02115
02116
02117
02118
02119
02120
02121
02122
02123
02124
02125
02126
02127
02128
02129
02130
02131
02132
02133
02134
02135
02136
02137
02138
02139
02140
02141
02142
02143
02144
02145
02146
02147
02148
02149
02150
02151
02152
02153
02154
02155
02156
02157
02158
02159
02160
02161
02162
02163
02164
02165
02166
02167
02168
02169
02170
02171
02172
02173
02174
02175
02176
02177
02178
02179
02180
02181
02182
02183
02184
02185
02186
02187
02188
02189
02190
02191
02192
02193
02194
02195
02196
02197
02198
02199
02200
02201
02202
02203
02204
02205
02206
02207
02208
02209
02210
02211
02212
02213
02214
02215
02216
02217
02218
02219
02220
02221
02222
02223
02224
02225
02226
02227
02228
02229
02230
02231
02232
02233
02234
02235
02236
02237
02238
02239
02240
02241
02242
02243
02244
02245
02246
02247
02248
02249
02250
02251
02252
02253
02254
02255
02256
02257
02258
02259
02260
02261
02262
02263
02264
02265
02266
02267
02268
02269
02270
02271
02272
02273
02274
02275
02276
02277
02278
02279
02280
02281
02282
02283
02284
02285
02286
02287
02288
02289
02290
02291
02292
02293
02294
02295
02296
02297
02298
02299
02300
02301
02302
02303
02304
02305
02306
02307
02308
02309
02310
02311
02312
02313
02314
02315
02316
02317
02318
02319
02320
02321
02322
02323
02324
02325
02326
02327
02328
02329
02330
02331
02332
02333
02334
02335
02336
02337
02338
02339
02340
02341
02342
02343
02344
02345
02346
02347
02348
02349
02350
02351
02352
02353
02354
02355
02356
02357
02358
02359
02360
02361
02362
02363
02364
02365
02366
02367
02368
02369
02370
02371
02372
02373
02374
02375
02376
02377
02378
02379
02380
02381
02382
02383
02384
02385
02386
02387
02388
02389
02390
02391
02392
02393
02394
02395
02396
02397
02398
02399
02400
02401
02402
02403
02404
02405
02406
02407
02408
02409
02410
02411
02412
02413
02414
02415
02416
02417
02418
02419
02420
02421
02422
02423
02424
02425
02426
02427
02428
02429
02430
02431
02432
02433
02434
02435
02436
02437
02438
02439
02440
02441
02442
02443
02444
02445
02446
02447
02448
02449
02450
02451
02452
02453
02454
02455
02456
02457
02458
02459
02460
02461
02462
02463
02464
02465
02466
02467
02468
02469
02470
02471
02472
02473
02474
02475
02476
02477
02478
02479
02480
02481
02482
02483
02484
02485
02486
02487
02488
02489
02490
02491
02492
02493
02494
02495
02496
02497
02498
02499
02500
02501
02502
02503
02504
02505
02506
02507
02508
02509
02510
02511
02512
02513
02514
02515
02516
02517
02518
02519
02520
02521
02522
02523
02524
02525
02526
02527
02528
02529
02530
02531
02532
02533
02534
02535
02536
02537
02538
02539
02540
02541
02542
02543
02544
02545
02546
02547
02548
02549
02550
02551
02552
02553
02554
02555
02556
02557
02558
02559
02560
02561
02562
02563
02564
02565
02566
02567
02568
02569
02570
02571
02572
02573
02574
02575
02576
02577
02578
02579
02580
02581
02582
02583
02584
02585
02586
02587
02588
02589
02590
02591
02592
02593
02594
02595
02596
02597
02598
02599
02600
02601
02602
02603
02604
02605
02606
02607
02608
02609
02610
02611
02612
02613
02614
02615
02616
02617
02618
02619
02620
02621
02622
02623
02624
02625
02626
02627
02628
02629
02630
02631
02632
02633
02634
02635
02636
02637
02638
02639
02640
02641
02642
02643
02644
02645
02646
02647
02648
02649
02650
02651
02652
02653
02654
02655
02656
02657
02658
02659
02660
02661
02662
02663
02664
02665
02666
02667
02668
02669
02670
02671
02672
02673
02674
02675
02676
02677
02678
02679
02680
02681
02682
02683
02684
02685
02686
02687
02688
02689
02690
02691
02692
02693
02694
02695
02696
02697
02698
02699
02700
02701
02702
02703
02704
02705
02706
02707
02708
02709
02710
02711
02712
02713
02714
02715
02716
02717
02718
02719
02720
02721
02722
02723
02724
02725
02726
02727
02728
02729
02730
02731
02732
02733
02734
02735
02736
02737
02738
02739
02740
02741
02742
02743
02744
02745
02746
02747
02748
02749
02750
02751
02752
02753
02754
02755
02756
02757
02758
02759
02760
02761
02762
02763
02764
02765
02766
02767
02768
02769
02770
02771
02772
02773
02774
02775
02776
02777
02778
02779
02780
02781
02782
02783
02784
02785
02786
02787
02788
02789
02790
02791
02792
02793
02794
02795
02796
02797
02798
02799
02800
02801
02802
02803
02804
02805
02806
02807
02808
02809
02810
02811
02812
02813
02814
02815
02816
02817
02818
02819
02820
02821
02822
02823
02824
02825
02826
02827
02828
02829
02830
02831
02832
02833
02834
02835
02836
02837
02838
02839
02840
02841
02842
02843
02844
02845
02846
02847
02848
02849
02850
02851
02852
02853
02854
02855
02856
02857
02858
02859
02860
02861
02862
02863
02864
02865
02866
02867
02868
02869
02870
02871
02872
02873
02874
02875
02876
02877
02878
02879
02880
02881
02882
02883
02884
02885
02886
02887
02888
02889
02890
02891
02892
02893
02894
02895
02896
02897
02898
02899
02900
02901
02902
02903
02904
02905
02906
02907
02908
02909
02910
02911
02912
02913
02914
02915
02916
02917
02918
02919
02920
02921
02922
02923
02924
02925
02926
02927
02928
02929
02930
02931
02932
02933
02934
02935
02936
02937
02938
02939
02940
02941
02942
02943
02944
02945
02946
02947
02948
02949
02950
02951
02952
02953
02954
02955
02956
02957
02958
02959
02960
02961
02962
02963
02964
02965
02966
02967
02968
02969
02970
02971
02972
02973
02974
02975
02976
02977
02978
02979
02980
02981
02982
02983
02984
02985
02986
02987
02988
02989
02990
02991
02992
02993
02994
02995
02996
02997
02998
02999
03000
03001
03002
03003
03004
03005
03006
03007
03008
03009
03010
03011
03012
03013
03014
03015
03016
03017
03018
03019
03020
03021
03022
03023
03024
03025
03026
03027
03028
03029
03030
03031
03032
03033
03034
03035
03036
03037
03038
03039
03040
03041
03042
03043
03044
03045
03046
03047
03048
03049
03050
03051
03052
03053
03054
03055
03056
03057
03058
03059
03060
03061
03062
03063
03064
03065
03066
03067
03068
03069
03070
03071
03072
03073
03074
03075
03076
03077
03078
03079
03080
03081
03082
03083
03084
03085
03086
03087
03088
03089
03090
03091
03092
03093
03094
03095
03096
03097
03098
03099
03100
03101
03102
03103
03104
03105
03106
03107
03108
03109
03110
03111
03112
03113
03114
03115
03116
03117
03118
03119
03120
03121
03122
03123
03124
03125
03126
03127
03128
03129
03130
03131
03132
03133
03134
03135
03136
03137
03138
03139
03140
03141
03142
03143
03144
03145
03146
03147
03148
03149
03150
03151
03152
03153
03154
03155
03156
03157
03158
03159
03160
03161
03162
03163
03164
03165
03166
03167
03168
03169
03170
03171
03172
03173
03174
03175
03176
03177
03178
03179
03180
03181
03182
03183
03184
03185
03186
03187
03188
03189
03190
03191
03192
03193
03194
03195
03196
03197
03198
03199
03200
03201
03202
03203
03204
03205
03206
03207
03208
03209
03210
03211
03212
03213
03214
03215
03216
03217
03218
03219
03220
03221
03222
03223
03224
03225
03226
03227
03228
03229
03230
03231
03232
03233
03234
03235
03236
03237
03238
03239
03240
03241
03242
03243
03244
03245
03246
03247
03248
03249
03250
03251
03252
03253
03254
03255
03256
03257
03258
03259
03260
03261
03262
03263
03264
03265
03266
03267
03268
03269
03270
03271
03272
03273
03274
03275
03276
03277
03278
03279
03280
03281
03282
03283
03284
03285
03286
03287
03288
03289
03290
03291
03292
03293
03294
03295
03296
03297
03298
03299
03300
03301
03302
03303
03304
03305
03306
03307
03308
03309
03310
03311
03312
03313
03314
03315
03316
03317
03318
03319
03320
03321
03322
03323
03324
03325
03326
03327
03328
03329
03330
03331
03332
03333
03334
03335
03336
03337
03338
03339
03340
03341
03342
03343
03344
03345
03346
03347
03348
03349
03350
03351
03352
03353
03354
03355
03356
03357
03358
03359
03360
03361
03362
03363
03364
03365
03366
03367
03368
03369
03370
03371
03372
03373
03374
03375
03376
03377
03378
03379
03380
03381
03382
03383
03384
03385
03386
03387
03388
03389
03390
03391
03392
03393
03394
03395
03396
03397
03398
03399
03400
03401
03402
03403
03404
03405
03406
03407
03408
03409
03410
03411
03412
03413
03414
03415
03416
03417
03418
03419
03420
03421
03422
03423
03424
03425
03426
03427
03428
03429
03430
03431
03432
03433
03434
03435
03436
03437
03438
03439
03440
03441
03442
03443
03444
03445
03446
03447
03448
03449
03450
03451
03452
03453
03454
03455
03456
03457
03458
03459
03460
03461
03462
03463
03464
03465
03466
03467
03468
03469
03470
03471
03472
03473
03474
03475
03476
03477
03478
03479
03480
03481
03482
03483
03484
03485
03486
03487
03488
03489
03490
03491
03492
03493
03494
03495
03496
03497
03498
03499
03500
03501
03502
03503
03504
03505
03506
03507
03508
03509
03510
03511
03512
03513
03514
03515
03516
03517
03518
03519
03520
03521
03522
03523
03524
03525
03526
03527
03528
03529
03530
03531
03532
03533
03534
03535
03536
03537
03538
03539
03540
03541
03542
03543
03544
03545
03546
03547
03548
03549
03550
03551
03552
03553
03554
03555
03556
03557
03558
03559
03560
03561
03562
03563
03564
03565
03566
03567
03568
03569
03570
03571
03572
03573
03574
03575
03576
03577
03578
03579
03580
03581
03582
03583
03584
03585
03586
03587
03588
03589
03590
03591
03592
03593
03594
03595
03596
03597
03598
03599
03600
03601
03602
03603
03604
03605
03606
03607
03608
03609
03610
03611
03612
03613
03614
03615
03616
03617
03618
03619
03620
03621
03622
03623
03624
03625
03626
03627
03628
03629
03630
03631
03632
03633
03634
03635
03636
03637
03638
03639
03640
03641
03642
03643
03644
03645
03646
03647
03648
03649
03650
03651
03652
03653
03654
03655
03656
03657
03658
03659
03660
03661
03662
03663
03664
03665
03666
03667
03668
03669
03670
03671
03672
03673
03674
03675
03676
03677
03678
03679
03680
03681
03682
03683
03684
03685
03686
03687
03688
03689
03690
03691
03692
03693
03694
03695
03696
03697
03698
03699
03700
03701
03702
03703
03704
03705
03706
03707
03708
03709
03710
03711
03712
03713
03714
03715
03716
03717
03718
03719
03720
03721
03722
03723
03724
03725
03726
03727
03728
03729
03730
03731
03732
03733
03734
03735
03736
03737
03738
03739
03740
03741
03742
03743
03744
03745
03746
03747
03748
03749
03750
03751
03752
03753
03754
03755
03756
03757
03758
03759
03760
03761
03762
03763
03764
03765
03766
03767
03768
03769
03770
03771
03772
03773
03774
03775
03776
03777
03778
03779
03780
03781
03782
03783
03784
03785
03786
03787
03788
03789
03790
03791
03792
03793
03794
03795
03796
03797
03798
03799
03800
03801
03802
03803
03804
03805
03806
03807
03808
03809
03810
03811
03812
03813
03814
03815
03816
03817
03818
03819
03820
03821
03822
03823
03824
03825
03826
03827
03828
03829
03830
03831
03832
03833
03834
03835
03836
03837
03838
03839
03840
03841
03842
03843
03844
03845
03846
03847
03848
03849
03850
03851
03852
03853
03854
03855
03856
03857
03858
03859
03860
03861
03862
03863
03864
03865
03866
03867
03868
03869
03870
03871
03872
03873
03874
03875
03876
03877
03878
03879
03880
03881
03882
03883
03884
03885
03886
03887
03888
03889
03890
03891
03892
03893
03894
03895
03896
03897
03898
03899
03900
03901
03902
03903
03904
03905
03906
03907
03908
03909
03910
03911
03912
03913
03914
03915
03916
03917
03918
03919
03920
03921
03922
03923
03924
03925
03926
03927
03928
03929
03930
03931
03932
03933
03934
03935
03936
03937
03938
03939
03940
03941
03942
03943
03944
03945
03946
03947
03948
03949
03950
03951
03952
03953
03954
03955
03956
03957
03958
03959
03960
03961
03962
03963
03964
03965
03966
03967
03968
03969
03970
03971
03972
03973
03974
03975
03976
03977
03978
03979
03980
03981
03982
03983
03984
03985
03986
03987
03988
03989
03990
03991
03992
03993
03994
03995
03996
03997
03998
03999
04000
04001
04002
04003
04004
04005
04006
04007
04008
04009
04010
04011
04012
04013
04014
04015
04016
04017
04018
04019
04020
04021
04022
04023
04024
04025
04026
04027
04028
04029
04030
04031
04032
04033
04034
04035
04036
04037
04038
04039
04040
04041
04042
04043
04044
04045
04046
04047
04048
04049
04050
04051
04052
04053
04054
04055
04056
04057
04058
04059
04060
04061
04062
04063
04064
04065
04066
04067
04068
04069
04070
04071
04072
04073
04074
04075
04076
04077
04078
04079
04080
04081
04082
04083
04084
04085
04086
04087
04088
04089
04090
04091
04092
04093
04094
04095
04096
04097
04098
04099
04100
04101
04102
04103
04104
04105
04106
04107
04108
04109
04110
04111
04112
04113
04114
04115
04116
04117
04118
04119
04120
04121
04122
04123
04124
04125
04126
04127
04128
04129
04130
04131
04132
04133
04134
04135
04136
04137
04138
04139
04140
04141
04142
04143
04144
04145
04146
04147
04148
04149
04150
04151
04152
04153
04154
04155
04156
04157
04158
04159
04160
04161
04162
04163
04164
04165
04166
04167
04168
04169
04170
04171
04172
04173
04174
04175
04176
04177
04178
04179
04180
04181
04182
04183
04184
04185
04186
04187
04188
04189
04190
04191
04192
04193
04194
04195
04196
04197
04198
04199
04200
04201
04202
04203
04204
04205
04206
04207
04208
04209
04210
04211
04212
04213
04214
04215
04216
04217
04218
04219
04220
04221
04222
04223
04224
04225
04226
04227
04228
04229
04230
04231
04232
04233
04234
04235
04236
04237
04238
04239
04240
04241
04242
04243
04244
04245
04246
04247
04248
04249
04250
04251
04252
04253
04254
04255
04256
04257
04258
04259
04260
04261
04262
04263
04264
04265
04266
04267
04268
04269
04270
04271
04272
04273
04274
04275
04276
04277
04278
04279
04280
04281
04282
04283
04284
04285
04286
04287
04288
04289
04290
04291
04292
04293
04294
04295
04296
04297
04298
04299
04300
04301
04302
04303
04304
04305
04306
04307
04308
04309
04310
04311
04312
04313
04314
04315
04316
04317
04318
04319
04320
04321
04322
04323
04324
04325
04326
04327
04328
04329
04330
04331
04332
04333
04334
04335
04336
04337
04338
04339
04340
04341
04342
04343
04344
04345
04346
04347
04348
04349
04350
04351
04352
04353
04354
04355
04356
04357
04358
04359
04360
04361
04362
04363
04364
04365
04366
04367
04368
04369
04370
04371
04372
04373
04374
04375
04376
04377
04378
04379
04380
04381
04382
04383
04384
04385
04386
04387
04388
04389
04390
04391
04392
04393
04394
04395
04396
04397
04398
04399
04400
04401
04402
04403
04404
04405
04406
04407
04408
04409
04410
04411
04412
04413
04414
04415
04416
04417
04418
04419
04420
04421
04422
04423
04424
04425
04426
04427
04428
04429
04430
04431
04432
04433
04434
04435
04436
04437
04438
04439
04440
04441
04442
04443
04444
04445
04446
04447
04448
04449
04450
04451
04452
04453
04454
04455
04456
04457
04458
04459
04460
04461
04462
04463
04464
04465
04466
04467
04468
04469
04470
04471
04472
04473
04474
04475
04476
04477
04478
04479
04480
04481
04482
04483
04484
04485
04486
04487
04488
04489
04490
04491
04492
04493
04494
04495
04496
04497
04498
04499
04500
04501
04502
04503
04504
04505
04506
04507
04508
04509
04510
04511
04512
04513
04514
04515
04516
04517
04518
04519
04520
04521
04522
04523
04524
04525
04526
04527
04528
04529
04530
04531
04532
04533
04534
04535
04536
04537
04538
04539
04540
04541
04542
04543
04544
04545
04546
04547
04548
04549
04550
04551
04552
04553
04554
04555
04556
04557
04558
04559
04560
04561
04562
04563
04564
04565
04566
04567
04568
04569
04570
04571
04572
04573
04574
04575
04576
04577
04578
04579
04580
04581
04582
04583
04584
04585
04586
04587
04588
04589
04590
04591
04592
04593
04594
04595
04596
04597
04598
04599
04600
04601
04602
04603
04604
04605
04606
04607
04608
04609
04610
04611
04612
04613
04614
04615
04616
04617
04618
04619
04620
04621
04622
04623
04624
04625
04626
04627
04628
04629
04630
04631
04632
04633
04634
04635
04636
04637
04638
04639
04640
04641
04642
04643
04644
04645
04646
04647
04648
04649
04650
04651
04652
04653
04654
04655
04656
04657
04658
04659
04660
04661
04662
04663
04664
04665
04666
04667
04668
04669
04670
04671
04672
04673
04674
04675
04676
04677
04678
04679
04680
04681
04682
04683
04684
04685
04686
04687
04688
04689
04690
04691
04692
04693
04694
04695
04696
04697
04698
04699
04700
04701
04702
04703
04704
04705
04706
04707
04708
04709
04710
04711
04712
04713
04714
04715
04716
04717
04718
04719
04720
04721
04722
04723
04724
04725
04726
04727
04728
04729
04730
04731
04732
04733
04734
04735
04736
04737
04738
04739
04740
04741
04742
04743
04744
04745
04746
04747
04748
04749
04750
04751
04752
04753
04754
04755
04756
04757
04758
04759
04760
04761
04762
04763
04764
04765
04766
04767
04768
04769
04770
04771
04772
04773
04774
04775
04776
04777
04778
04779
04780
04781
04782
04783
04784
04785
04786
04787
04788
04789
04790
04791
04792
04793
04794
04795
04796
04797
04798
04799
04800
04801
04802
04803
04804
04805
04806
04807
04808
04809
04810
04811
04812
04813
04814
04815
04816
04817
04818
04819
04820
04821
04822
04823
04824
04825
04826
04827
04828
04829
04830
04831
04832
04833
04834
04835
04836
04837
04838
04839
04840
04841
04842
04843
04844
04845
04846
04847
04848
04849
04850
04851
04852
04853
04854
04855
04856
04857
04858
04859
04860
04861
04862
04863
04864
04865
04866
04867
04868
04869
04870
04871
04872
04873
04874
04875
04876
04877
04878
04879
04880
04881
04882
04883
04884
04885
04886
04887
04888
04889
04890
04891
04892
04893
04894
04895
04896
04897
04898
04899
04900
04901
04902
04903
04904
04905
04906
04907
04908
04909
04910
04911
04912
04913
04914
04915
04916
04917
04918
04919
04920
04921
04922
04923
04924
04925
04926
04927
04928
04929
04930
04931
04932
04933
04934
04935
04936
04937
04938
04939
04940
04941
04942
04943
04944
04945
04946
04947
04948
04949
04950
04951
04952
04953
04954
04955
04956
04957
04958
04959
04960
04961
04962
04963
04964
04965
04966
04967
04968
04969
04970
04971
04972
04973
04974
04975
04976
04977
04978
04979
04980
04981
04982
04983
04984
04985
04986
04987
04988
04989
04990
04991
04992
04993
04994
04995
04996
04997
04998
04999
05000
05001
05002
05003
05004
05005
05006
05007
05008
05009
05010
05011
05012
05013
05014
05015
05016
05017
05018
05019
05020
05021
05022
05023
05024
05025
05026
05027
05028
05029
05030
05031
05032
05033
05034
05035
05036
05037
05038
05039
05040
05041
05042
05043
05044
05045
05046
05047
05048
05049
05050
05051
05052
05053
05054
05055
05056
05057
05058
05059
05060
05061
05062
05063
05064
05065
05066
05067
05068
05069
05070
05071
05072
05073
05074
05075
05076
05077
05078
05079
05080
05081
05082
05083
05084
05085
05086
05087
05088
05089
05090
05091
05092
05093
05094
05095
05096
05097
05098
05099
05100
05101
05102
05103
05104
05105
05106
05107
05108
05109
05110
05111
05112
05113
05114
05115
05116
05117
05118
05119
05120
05121
05122
05123
05124
05125
05126
05127
05128
05129
05130
05131
05132
05133
05134
05135
05136
05137
05138
05139
05140
05141
05142
05143
05144
05145
05146
05147
05148
05149
05150
05151
05152
05153
05154
05155
05156
05157
05158
05159
05160
05161
05162
05163
05164
05165
05166
05167
05168
05169
05170
05171
05172
05173
05174
05175
05176
05177
05178
05179
05180
05181
05182
05183
05184
05185
05186
05187
05188
05189
05190
05191
05192
05193
05194
05195
05196
05197
05198
05199
05200
05201
05202
05203
05204
05205
05206
05207
05208
05209
05210
05211
05212
05213
05214
05215
05216
05217
05218
05219
05220
05221
05222
05223
05224
05225
05226
05227
05228
05229
05230
05231
05232
05233
05234
05235
05236
05237
05238
05239
05240
05241
05242
05243
05244
05245
05246
05247
05248
05249
05250
05251
05252
05253
05254
05255
05256
05257
05258
05259
05260
05261
05262
05263
05264
05265
05266
05267
05268
05269
05270
05271
05272
05273
05274
05275
05276
05277
05278
05279
05280
05281
05282
05283
05284
05285
05286
05287
05288
05289
05290
05291
05292
05293
05294
05295
05296
05297
05298
05299
05300
05301
05302
05303
05304
05305
05306
05307
05308
05309
05310
05311
05312
05313
05314
05315
05316
05317
05318
05319
05320
05321
05322
05323
05324
05325
05326
05327
05328
05329
05330
05331
05332
05333
05334
05335
05336
05337
05338
05339
05340
05341
05342
05343
05344
05345
05346
05347
05348
05349
05350
05351
05352
05353
05354
05355
05356
05357
05358
05359
05360
05361
05362
05363
05364
05365
05366
05367
05368
05369
05370
05371
05372
05373
05374
05375
05376
05377
05378
05379
05380
05381
05382
05383
05384
05385
05386
05387
05388
05389
05390
05391
05392
05393
05394
05395
05396
05397
05398
05399
05400
05401
05402
05403
05404
05405
05406
05407
05408
05409
05410
05411
05412
05413
05414
05415
05416
05417
05418
05419
05420
05421
05422
05423
05424
05425
05426
05427
05428
05429
05430
05431
05432
05433
05434
05435
05436
05437
05438
05439
05440
05441
05442
05443
05444
05445
05446
05447
05448
05449
05450
05451
05452
05453
05454
05455
05456
05457
05458
05459
05460
05461
05462
05463
05464
05465
05466
05467
05468
05469
05470
05471
05472
05473
05474
05475
05476
05477
05478
05479
05480
05481
05482
05483
05484
05485
05486
05487
05488
05489
05490
05491
05492
05493
05494
05495
05496
05497
05498
05499
05500
05501
05502
05503
05504
05505
05506
05507
05508
05509
05510
05511
05512
05513
05514
05515
05516
05517
05518
05519
05520
05521
05522
05523
05524
05525
05526
05527
05528
05529
05530
05531
05532
05533
05534
05535
05536
05537
05538
05539
05540
05541
05542
05543
05544
05545
05546
05547
05548
05549
05550
05551
05552
05553
05554
05555
05556
05557
05558
05559
05560
05561
05562
05563
05564
05565
05566
05567
05568
05569
05570
05571
05572
05573
05574
05575
05576
05577
05578
05579
05580
05581
05582
05583
05584
05585
05586
05587
05588
05589
05590
05591
05592
05593
05594
05595
05596
05597
05598
05599
05600
05601
05602
05603
05604
05605
05606
05607
05608
05609
05610
05611
05612
05613
05614
05615
05616
05617
05618
05619
05620
05621
05622
05623
05624
05625
05626
05627
05628
05629
05630
05631
05632
05633
05634
05635
05636
05637
05638
05639
05640
05641
05642
05643
05644
05645
05646
05647
05648
05649
05650
05651
05652
05653
05654
05655
05656
05657
05658
05659
05660
05661
05662
05663
05664
05665
05666
05667
05668
05669
05670
05671
05672
05673
05674
05675
05676
05677
05678
05679
05680
05681
05682
05683
05684
05685
05686
05687
05688
05689
05690
05691
05692
05693
05694
05695
05696
05697
05698
05699
05700
05701
05702
05703
05704
05705
05706
05707
05708
05709
05710
05711
05712
05713
05714
05715
05716
05717
05718
05719
05720
05721
05722
05723
05724
05725
05726
05727
05728
05729
05730
05731
05732
05733
05734
05735
05736
05737
05738
05739
05740
05741
05742
05743
05744
05745
05746
05747
05748
05749
05750
05751
05752
05753
05754
05755
05756
05757
05758
05759
05760
05761
05762
05763
05764
05765
05766
05767
05768
05769
05770
05771
05772
05773
05774
05775
05776
05777
05778
05779
05780
05781
05782
05783
05784
05785
05786
05787
05788
05789
05790
05791
05792
05793
05794
05795
05796
05797
05798
05799
05800
05801
05802
05803
05804
05805
05806
05807
05808
05809
05810
05811
05812
05813
05814
05815
05816
05817
05818
05819
05820
05821
05822
05823
05824
05825
05826
05827
05828
05829
05830
05831
05832
05833
05834
05835
05836
05837
05838
05839
05840
05841
05842
05843
05844
05845
05846
05847
05848
05849
05850
05851
05852
05853
05854
05855
05856
05857
05858
05859
05860
05861
05862
05863
05864
05865
05866
05867
05868
05869
05870
05871
05872
05873
05874
05875
05876
05877
05878
05879
05880
05881
05882
05883
05884
05885
05886
05887
05888
05889
05890
05891
05892
05893
05894
05895
05896
05897
05898
05899
05900
05901
05902
05903
05904
05905
05906
05907
05908
05909
05910
05911
05912
05913
05914
05915
05916
05917
05918
05919
05920
05921
05922
05923
05924
05925
05926
05927
05928
05929
05930
05931
05932
05933
05934
05935
05936
05937
05938
05939
05940
05941
05942
05943
05944
05945
05946
05947
05948
05949
05950
05951
05952
05953
05954
05955
05956
05957
05958
05959
05960
05961
05962
05963
05964
05965
05966
05967
05968
05969
05970
05971
05972
05973
05974
05975
05976
05977
05978
05979
05980
05981
05982
05983
05984
05985
05986
05987
05988
05989
05990
05991
05992
05993
05994
05995
05996
05997
05998
05999
06000
06001
06002
06003
06004
06005
06006
06007
06008
06009
06010
06011
06012
06013
06014
06015
06016
06017
06018
06019
06020
06021
06022
06023
06024
06025
06026
06027
06028
06029
06030
06031
06032
06033
06034
06035
06036
06037
06038
06039
06040
06041
06042
06043
06044
06045
06046
06047
06048
06049
06050
06051
06052
06053
06054
06055
06056
06057
06058
06059
06060
06061
06062
06063
06064
06065
06066
06067
06068
06069
06070
06071
06072
06073
06074
06075
06076
06077
06078
06079
06080
06081
06082
06083
06084
06085
06086
06087
06088
06089
06090
06091
06092
06093
06094
06095
06096
06097
06098
06099
06100
06101
06102
06103
06104
06105
06106
06107
06108
06109
06110
06111
06112
06113
06114
06115
06116
06117
06118
06119
06120
06121
06122
06123
06124
06125
06126
06127
06128
06129
06130
06131
06132
06133
06134
06135
06136
06137
06138
06139
06140
06141
06142
06143
06144
06145
06146
06147
06148
06149
06150
06151
06152
06153
06154
06155
06156
06157
06158
06159
06160
06161
06162
06163
06164
06165
06166
06167
06168
06169
06170
06171
06172
06173
06174
06175
06176
06177
06178
06179
06180
06181
06182
06183
06184
06185
06186
06187
06188
06189
06190
06191
06192
06193
06194
06195
06196
06197
06198
06199
06200
06201
06202
06203
06204
06205
06206
06207
06208
06209
06210
06211
06212
06213
06214
06215
06216
06217
06218
06219
06220
06221
06222
06223
06224
06225
06226
06227
06228
06229
06230
06231
06232
06233
06234
06235
06236
06237
06238
06239
06240
06241
06242
06243
06244
06245
06246
06247
06248
06249
06250
06251
06252
06253
06254
06255
06256
06257
06258
06259
06260
06261
06262
06263
06264
06265
06266
06267
06268
06269
06270
06271
06272
06273
06274
06275
06276
06277
06278
06279
06280
06281
06282
06283
06284
06285
06286
06287
06288
06289
06290
06291
06292
06293
06294
06295
06296
06297
06298
06299
06300
06301
06302
06303
06304
06305
06306
06307
06308
06309
06310
06311
06312
06313
06314
06315
06316
06317
06318
06319
06320
06321
06322
06323
06324
06325
06326
06327
06328
06329
06330
06331
06332
06333
06334
06335
06336
06337
06338
06339
06340
06341
06342
06343
06344
06345
06346
06347
06348
06349
06350
06351
06352
06353
06354
06355
06356
06357
06358
06359
06360
06361
06362
06363
06364
06365
06366
06367
06368
06369
06370
06371
06372
06373
06374
06375
06376
06377
06378
06379
06380
06381
06382
06383
06384
06385
06386
06387
06388
06389
06390
06391
06392
06393
06394
06395
06396
06397
06398
06399
06400
06401
06402
06403
06404
06405
06406
06407
06408
06409
06410
06411
06412
06413
06414
06415
06416
06417
06418
06419
06420
06421
06422
06423
06424
06425
06426
06427
06428
06429
06430
06431
06432
06433
06434
06435
06436
06437
06438
06439
06440
06441
06442
06443
06444
06445
06446
06447
06448
06449
06450
06451
06452
06453
06454
06455
06456
06457
06458
06459
06460
06461
06462
06463
06464
06465
06466
06467
06468
06469
06470
06471
06472
06473
06474
06475
06476
06477
06478
06479
06480
06481
06482
06483
06484
06485
06486
06487
06488
06489
06490
06491
06492
06493
06494
06495
06496
06497
06498
06499
06500
06501
06502
06503
06504
06505
06506
06507
06508
06509
06510
06511
06512
06513
06514
06515
06516
06517
06518
06519
06520
06521
06522
06523
06524
06525
06526
06527
06528
06529
06530
06531
06532
06533
06534
06535
06536
06537
06538
06539
06540
06541
06542
06543
06544
06545
06546
06547
06548
06549
06550
06551
06552
06553
06554
06555
06556
06557
06558
06559
06560
06561
06562
06563
06564
06565
06566
06567
06568
06569
06570
06571
06572
06573
06574
06575
06576
06577
06578
06579
06580
06581
06582
06583
06584
06585
06586
06587
06588
06589
06590
06591
06592
06593
06594
06595
06596
06597
06598
06599
06600
06601
06602
06603
06604
06605
06606
06607
06608
06609
06610
06611
06612
06613
06614
06615
06616
06617
06618
06619
06620
06621
06622
06623
06624
06625
06626
06627
06628
06629
06630
06631
06632
06633
06634
06635
06636
06637
06638
06639
06640
06641
06642
06643
06644
06645
06646
06647
06648
06649
06650
06651
06652
06653
06654
06655
06656
06657
06658
06659
06660
06661
06662
06663
06664
06665
06666
06667
06668
06669
06670
06671
06672
06673
06674
06675
06676
06677
06678
06679
06680
06681
06682
06683
06684
06685
06686
06687
06688
06689
06690
06691
06692
06693
06694
06695
06696
06697
06698
06699
06700
06701
06702
06703
06704
06705
06706
06707
06708
06709
06710
06711
06712
06713
06714
06715
06716
06717
06718
06719
06720
06721
06722
06723
06724
06725
06726
06727
06728
06729
06730
06731
06732
06733
06734
06735
06736
06737
06738
06739
06740
06741
06742
06743
06744
06745
06746
06747
06748
06749
06750
06751
06752
06753
06754
06755
06756
06757
06758
06759
06760
06761
06762
06763
06764
06765
06766
06767
06768
06769
06770
06771
06772
06773
06774
06775
06776
06777
06778
06779
06780
06781
06782
06783
06784
06785
06786
06787
06788
06789
06790
06791
06792
06793
06794
06795
06796
06797
06798
06799
06800
06801
06802
06803
06804
06805
06806
06807
06808
06809
06810
06811
06812
06813
06814
06815
06816
06817
06818
06819
06820
06821
06822
06823
06824
06825
06826
06827
06828
06829
06830
06831
06832
06833
06834
06835
06836
06837
06838
06839
06840
06841
06842
06843
06844
06845
06846
06847
06848
06849
06850
06851
06852
06853
06854
06855
06856
06857
06858
06859
06860
06861
06862
06863
06864
06865
06866
06867
06868
06869
06870
06871
06872
06873
06874
06875
06876
06877
06878
06879
06880
06881
06882
06883
06884
06885
06886
06887
06888
06889
06890
06891
06892
06893
06894
06895
06896
06897
06898
06899
06900
06901
06902
06903
06904
06905
06906
06907
06908
06909
06910
06911
06912
06913
06914
06915
06916
06917
06918
06919
06920
06921
06922
06923
06924
06925
06926
06927
06928
06929
06930
06931
06932
06933
06934
06935
06936
06937
06938
06939
06940
06941
06942
06943
06944
06945
06946
06947
06948
06949
06950
06951
06952
06953
06954
06955
06956
06957
06958
06959
06960
06961
06962
06963
06964
06965
06966
06967
06968
06969
06970
06971
06972
06973
06974
06975
06976
06977
06978
06979
06980
06981
06982
06983
06984
06985
06986
06987
06988
06989
06990
06991
06992
06993
06994
06995
06996
06997
06998
06999
07000
07001
07002
07003
07004
07005
07006
07007
07008
07009
07010
07011
07012
07013
07014
07015
07016
07017
07018
07019
07020
07021
07022
07023
07024
07025
07026
07027
07028
07029
07030
07031
07032
07033
07034
07035
07036
07037
07038
07039
07040
07041
07042
07043
07044
07045
07046
07047
07048
07049
07050
07051
07052
07053
07054
07055
07056
07057
07058
07059
07060
07061
07062
07063
07064
07065
07066
07067
07068
07069
07070
07071
07072
07073
07074
07075
07076
07077
07078
07079
07080
07081
07082
07083
07084
07085
07086
07087
07088
07089
07090
07091
07092
07093
07094
07095
07096
07097
07098
07099
07100
07101
07102
07103
07104
07105
07106
07107
07108
07109
07110
07111
07112
07113
07114
07115
07116
07117
07118
07119
07120
07121
07122
07123
07124
07125
07126
07127
07128
07129
07130
07131
07132
07133
07134
07135
07136
07137
07138
07139
07140
07141
07142
07143
07144
07145
07146
07147
07148
07149
07150
07151
07152
07153
07154
07155
07156
07157
07158
07159
07160
07161
07162
07163
07164
07165
07166
07167
07168
07169
07170
07171
07172
07173
07174
07175
07176
07177
07178
07179
07180
07181
07182
07183
07184
07185
07186
07187
07188
07189
07190
07191
07192
07193
07194
07195
07196
07197
07198
07199
07200
07201
07202
07203
07204
07205
07206
07207
07208
07209
07210
07211
07212
07213
07214
07215
07216
07217
07218
07219
07220
07221
07222
07223
07224
07225
07226
07227
07228
07229
07230
07231
07232
07233
07234
07235
07236
07237
07238
07239
07240
07241
07242
07243
07244
07245
07246
07247
07248
07249
07250
07251
07252
07253
07254
07255
07256
07257
07258
07259
07260
07261
07262
07263
07264
07265
07266
07267
07268
07269
07270
07271
07272
07273
07274
07275
07276
07277
07278
07279
07280
07281
07282
07283
07284
07285
07286
07287
07288
07289
07290
07291
07292
07293
07294
07295
07296
07297
07298
07299
07300
07301
07302
07303
07304
07305
07306
07307
07308
07309
07310
07311
07312
07313
07314
07315
07316
07317
07318
07319
07320
07321
07322
07323
07324
07325
07326
07327
07328
07329
//=============================================================================
// U2NPCControllerBasic.uc
// Created By: Mike Fox
// Created On: 8/01/00
// $Author: Mfox $
// $Date: 1/07/03 10:31a $
// $Revision: 156 $
//=============================================================================

class U2NPCControllerBasic extends U2NPCControllerBase;

/*-----------------------------------------------------------------------------
OVERVIEW:

This is the AI Controller class for most NPCs which can react to and attack 
enemies but don't use actual inventory weapons (animation-based ranged and
melee attacks).
*/

//-----------------------------------------------------------------------------

const FakeNotifyLeapBeginTimerName	= 'FakeNotifyLeapBeginTimer';
const FreezeNPCHackTimerName		= 'FreezeNPCHackTimer';

const LeapBeginNotify				= 'LeapBeginNotify';
const StayNotify					= 'Stay';

const MinImpaleCos					= -0.93;	// impalee/impaler facing each other to within 20 degrees

//!!mdf-tbi: go off actual animation durations / update when animations changed
const CrouchStanceChangeDuration	= 0.50;
const ProneStanceChangeDuration		= 0.75;

// AI properties
var float	Aggressiveness;				// 0.0 to 1.0 (typically)
var Pawn	OldControllerEnemy;
var	vector	HidingSpot;
var float	VerifyCoverRate;

// AI flags
var bool bChangeDir;					// tactical move boolean
var bool bDeviousHunting;				// if true, try to sneak up behind enemy when hunting
var bool bFrustrated;				
var bool bInitiatingAttack;
var bool bKamikaze;					
var bool bSmartAboutTurrets;			// if true, knows to avoid attacking turrets (StationaryPawns for now)
var bool bSniping;						// mdf-tbd: approach changed in 777?
var bool bStationary;					// if set NPC can only rotate/aim
var bool bTriedLastDetectedLocation;	// used with hunting state
//tbd: just call LOS if not too slow? var protected bool bLOSToTarget;			// true when NPC has LOS to enemy (false means don't fire)

// orders
var name	Orders;						// orders a bot is carrying out 
var Object  OrderGiver;					// source of orders (e.g. player, GameAIController)
var	Actor	OrdersObject;				// order object (if applicable)
var float	OrdersThreshold;			// threshold used with some orders
var bool	bExecuteOrders;				// NPC will favor orders over attacking enemy (controlled, e.g., on a squad-basis)
var float	ExecuteOrdersThreshold;		// threshold used by NPC to decide whether to set/clear bExecuteOrders

var Actor	StationarySpot;				// holdspot used with stationary NPCs

// debug
var(Controller) globalconfig private bool bShowOrdersObjects;

// attacks
var class<BehaviorControllerInterf>	BehaviorControllerClass;
var BehaviorControllerInterf			BehaviorController;

var name DefaultAcquisitionState;		// state used when NPC acquires an enemy when relaxed
var name DefaultDeadLockedState;		// state used to wait a few ticks when behavior is deadlocked
var name DefaultImmobileState;			// state used to keep NPCs from moving
var name DefaultImmobileAttackState;	// state used to carry out ranged attack for immobile (stationary) NPCs

// internal
//!!mdf -- eliminate with external firing controller?
var bool bFireFalling;
var bool bStrafeDir;						
//mdf-tbd: var float LastFireTime;				
var float MaxFallbackNoDetectTime;
var float MaxHuntTime;	
var float LastInvFind;					// move to bot
var float RefireDelay;
var float LastSpecialDestinationCheck;
var NavigationPoint BlockedPath;		// tbd
var vector RealLastDetectedLocation;	// tbd
var EDestinationResult DestinationResult;	// result of last call to SetChargeDestination
var float LastBumpDamageTime;
var float StartTurnTime;
var float OldCheckBehaviorDelay, OldCheckMetaStateDelay;

var float AlertTime;

var float NextLeapTime;
var rotator PendingLeapRotation;
var float PendingLeapSpeed;
var bool bLeapNotifyTimeSet;
var bool bLeaping;
var vector LeapLastHitWallNormal;		// normal of last hit with wall (to prevent multiple hit wall notifications for the same hit)
var float LeapLastHitWallTime;			// last time a wall was hit
var float LeapMinHitWallDelay;			// minimum amount of time before acknowledging hit wall notifications

var Pawn ImpaleVictim;					// pawn we're impaling
var float MeleeEndTime;
var bool bMeleeDamagedTarget;			// set during successful melee attack

var vector StateStartLocation;			// used to save location at start of some states
var bool bAcceptedState;

// move to advanced+?
var Ambushpoint AmbushSpot;				// current AmbushSpot if applicable

var float StartDodgeTime;
var bool bDodgeFinished;				// true when dodge animation has finished playing

//-----------------------------------------------------------------------------
//@ DEBUG
//-----------------------------------------------------------------------------

function string GetExtendedStateInformation() 
{ 
	return BehaviorController.GetExtendedStateInformation();
}

//-----------------------------------------------------------------------------

function string GetMetaStateName()
{
	if( BehaviorController != None )
		return BehaviorController.GetCurrentMetaStateName();
	else
		return "NA";
}

//-----------------------------------------------------------------------------

function string GetMetaStateNameShort()
{
	if( BehaviorController != None )
		return BehaviorController.GetCurrentMetaStateNameShort();
	else
		return "NA";
}

//-----------------------------------------------------------------------------

//!!mdf-tbr:
#debugbegin
function VerifyStateChange( name OldState, name NewState, name Label, bool bGoto, string ContextStr, int ContextLineNum )
{
	local string ErrorStr;

	ErrorStr = "";

	// ignore transitions within the same state for now?
	if( NewState != OldState )
	{
		if( !IsMobile() )
		{
			switch( NewState )
			{
			case AttackCloseState:
			case AttackCloseChargeState:
			case AttackFallbackState:
			case AttackHideState: 
			case AttackHuntState:
			case AttackLeapState:
			case AttackMoveToCoverBaseState:
			case AttackMoveToCoverCombatState:
			case AttackMoveToCoverFleeState:
			case AttackRecoverEnemyState:
			//nope: let immobile NPCs use this for attacking:
			// case AttackStationaryState:
			case AttackRetreatState:
			case AttackStakeOutState:
			case AttackStakeOutCoverState:
			//!!mdf-tbd: can't think of a good way to handle these
			/*
			case AttackTacticalMoveState:
			case AttackTacticalMoveMeleeState:
			case AttackTacticalRetreatState:
			case AttackTacticalRetreatMeleeState:
			*/
			case FindAirState:
			case RoamingState:
			case WanderingState:
				ErrorStr = "Immobile NPC transitioning to state which requires movement (" $ NewState $ ")!";
			}
		}
	}

	if( ErrorStr != "" )
		DMAssert( false, "VerifyStateChange -- " $ ErrorStr $ "  CONTEXT=" $ ContextStr $ " Line=" $ ContextLineNum );
}
#debugend

//-----------------------------------------------------------------------------
//@ _INIT/RESTART
//-----------------------------------------------------------------------------

function ClearReferencesTo( Pawn P )
{
	local Pawn PreviousControllerEnemy;
	
	PreviousControllerEnemy = ControllerEnemy;
	
	Super.ClearReferencesTo( P );

	if( OldControllerEnemy == P )
		OldControllerEnemy = None;

	// only called UpdateEnemy if previous enemy was the given Pawn
	if( PreviousControllerEnemy == P )
	{
		#debug   StopFiring( 0.0, SFI_Behavior, GetContext() );
		#release StopFiring( 0.0, SFI_Behavior );
		UpdateEnemy();
	}
}

//-----------------------------------------------------------------------------

function Restart()
{
	#debug   SetControllerEnemy( None, GetContext() );
	#release SetControllerEnemy( None );

	#debug DMAI( "Restart" );
	GotoState( DefaultState ); //GS-OK
}

//-----------------------------------------------------------------------------

function PossessStartup()
{
	Super.PossessStartup();
	
	if( U2PBase.bStationary )
		SetStationary( true );
}

//-----------------------------------------------------------------------------

function Possess( Pawn P )
{
	Super.Possess( P );

	P.PreSetMovement();
	
	BehaviorController = new BehaviorControllerClass;
	#debug DMAssert( BehaviorController != None, GetContext() );

	if( U2PBasic.bMonitorStanceRanges )
	{
		// for getting EnemyRangeTransition events (NPC stands up if enemy too close etc.)
		Ranges.Length = 2;
		Ranges[ 0 ] = U2PBasic.MinCrouchDistance;
		Ranges[ 1 ] = U2PBasic.MinProneDistance;
	}
}

//-----------------------------------------------------------------------------

event Destroyed()
{
	//DMTNS( "Destroyed  BehaviorController: " $ BehaviorController );

	RemoveAllTimers();

	if( BehaviorController != None )
	{
		BehaviorController.CleanupBC();
		BehaviorController.Delete();
		BehaviorController = None;
	}
	
	ClearCoverSpot();
	
	Super.Destroyed();
}

//-----------------------------------------------------------------------------

function ResetGlobalAISettings();

//-----------------------------------------------------------------------------
// NOTE: I'd like to eliminate this if possible and fold this behavior into the
// behavior controller. For now this should only be called when the NPC no longer
// has a valid enemy (or old enemy) and we want to know "what to do next" (all
// situations when the NPC does have an enemy should be captured / handled by
// the BC. All that WTDN should really do is put the NPC back into the scripted
// state if it has a script (and isn't in the scripted state currently) or let
// the NPC go back to its default state (tbd: go roaming to handle a priority
// objective?).

#debug   function WhatToDoNext( string ContextStr )
#release function WhatToDoNext()
{
	local name DestinationState, DestinationLabel;
	local bool bMaintainCurrentState;

	#debug DMAI( "U2NPCControllerBasic.WhatToDoNext (" $ ContextStr $ ") ScriptController=" $ ScriptController $ " Enemy=" $ ControllerEnemy $ " OldControllerEnemy=" $ OldControllerEnemy );

	ResetGlobalAISettings();

	//!!mdf-tbd: this is still happening:
	//DMAssert( ControllerEnemy == None && OldControllerEnemy == None, ContextStr $ "-->" $ GetContext() ); // all calls to WTDN should go through BC which will handle valid enemies through behavior lists
	// e.g. DM:  165.255 U2NPCControllerAdvanced1 AttackStationary WARNING (ASSERT!): assertion is invalid: WhatToDoNext (line 296) (Pawn=m08a1.U2Izarian4)
	
	//hack: we shouldn't be here if there is an enemy...
	if( ControllerEnemy != None )
	{
		//!!mdf-tbd: fix
		//DMAssert( false, ContextStr $ "-->" $ GetContext() ); // all calls to WTDN should go through BC which will handle valid enemies through behavior lists
		#debug   BehaviorController.Update( BC_AttackUpdate, ContextStr $ "-->" $ GetContext() );
		#release BehaviorController.Update( BC_AttackUpdate );
		return;		
	}

	#debug DMAssert( OldControllerEnemy == None, "OldControllerEnemy: " $ OldControllerEnemy $ " " $ ContextStr $ "-->" $ GetContext() ); // all calls to WTDN should go through BC which will handle valid enemies through behavior lists
	#release DMAssert( OldControllerEnemy == None, "OldControllerEnemy: " $ OldControllerEnemy $ " " $ GetContext() ); // all calls to WTDN should go through BC which will handle valid enemies through behavior lists

	if( HasScript() )
	{
		if( GetStateName() == ScriptedState )
		{
			bMaintainCurrentState = true;
		}
		else
		{
			DestinationState = ScriptedState;

			#debug DMAI( "WTDN (Basic) selecting " $ ScriptedState $ " (default label)" );
			if( IsInState( ScriptedDialogState ) )
				DestinationLabel = BeginLabel;
			else
				DestinationLabel = AutoEndLabel;
		}
	}
	else if( bStationary )
	{
		DestinationState = DefaultImmobileState;
	}
	else if( Orders == OrdersNone || !ReadyForOrders() || !DetermineOrdersTransition( DestinationState, DestinationLabel ) )
	{
		DestinationState = DefaultState;
	}

	if( bMaintainCurrentState )
	{
		#debug DMAI( "WTDN maintaining current state: " $ GetStateName() );
	}
	else
	{
		#debug DMAI( "WTDN (Basic) selecting " $ DestinationState $ "," $ DestinationLabel );
		GotoState( DestinationState, DestinationLabel ); //GS-OK
	}
}

//-----------------------------------------------------------------------------
//@ EVENTS
//-----------------------------------------------------------------------------

function bool FriendlyBumpSpecial()
{
	local bool bResult;

	if( ControllerEnemy != None )
	{
		if( LineOfSightTo( ControllerEnemy ) )
		{
			if( !IsInState( AttackTacticalMoveState ) )
			{
				if( AllowFriendlyBumpStateChanges() )
					GotoState( AttackTacticalMoveState, DontCloseLabel ); //GS-tbd
			}
		}
		else if( !IsInState( AttackStakeOutState ) && FRand() < 0.5 )
		{
			if( AllowFriendlyBumpStateChanges() )
				GotoState( AttackStakeOutState ); //GS-tbd
			ClearLastSeenTimes();
		}

		bResult = true;
	}

	return bResult;
}

//-----------------------------------------------------------------------------

function bool WanderAfterFriendlyBumpExtra()
{
	return (
		AllowFriendlyBumpStateChanges() &&
		Pawn.Health > 0 && 
		ControllerEnemy == None && 
		Orders == OrdersFollow && 
		MoveTarget == Controller(OrdersObject).Pawn && 
		MoveTarget.Acceleration == vect(0,0,0) );
}

//-----------------------------------------------------------------------------
// At this point, enemy should already be set to the Pawn that bumped us.

function HandleBumpedByEnemy()
{
	GotoState( AttackStationaryState ); //GS-tbd
}

//-----------------------------------------------------------------------------

#debug   function SetControllerEnemy( Pawn Enemy, coerce string ContextString )
#release function SetControllerEnemy( Pawn Enemy )
{
	#debug   Super.SetControllerEnemy( Enemy, ContextString );
	#release Super.SetControllerEnemy( Enemy );
	if( OldControllerEnemy == ControllerEnemy )
		OldControllerEnemy = None;
}

//-----------------------------------------------------------------------------

function eventSeeOther( Actor Seen )
{
	local EAttitude AttitudeToOther;
	// placeholder hack -- if no enemy react to seeing a carcass
	//    eventually friendly/neutral --> go alert (seek cover, search area?
	//               enemy --> "check out carcass"?

	if( ControllerEnemy == None )
	{
		if( Pawn(Seen) != None && Pawn(Seen).Health <= 0 )
		{
			AttitudeToOther = GetAttitudeTo( Pawn(Seen) );
			if( AttitudeToOther == ATTITUDE_Enemy )
			{
				// tbi: make alert and approach carcass?
			}
			else
			{
				// tbi: make alert and search/hide?
			}
		}
	}
}

//-----------------------------------------------------------------------------

#debug   function UpdateBehavior( bool bEnableBC, string ContextStr )
#release function UpdateBehavior( bool bEnableBC )
{
	if( bEnableBC )
		BehaviorController.SetBCEnabled( true );
		
	if( ValidEnemy( ControllerEnemy ) )
	{
		#debug   BehaviorController.Update( BC_AttackUpdate, ContextStr );
		#release BehaviorController.Update( BC_AttackUpdate );
	}
	else
	{
		#debug   BehaviorController.Update( BC_UpdateInactive, ContextStr );
		#release BehaviorController.Update( BC_UpdateInactive );
	}
}

//-----------------------------------------------------------------------------
// States which disable the behavior controller (via SetBCEnabled() in order to
// prevent the state from changing). Should call this if there is any chance
// the state can end with the behavior controller still disabled (e.g. because
// UpdateBehavior() was never called). Checks the behavior controller and if 
// its not enabled, calls UpdateBehavior( true ).

function CheckBehaviorEnabled()
{
	// Assume that the code which changed the state knows what it is doing so
	// don't call UpdateBehavior here?
	if( ValidPawn( Pawn ) && BehaviorController != None && !BehaviorController.GetBCEnabled() )
	{
		//DMTNS( "CheckBehaviorEnabled re-enabling behavior controller (leaving state with behavior controller still disabled?)" );
		BehaviorController.SetBCEnabled( true );
	}
}

//-----------------------------------------------------------------------------
//@ EVENTS -- DAMAGE
//-----------------------------------------------------------------------------

function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
{
	if( Pawn != None && Pawn.Health > 0 )
	{
		Super.DamageAttitudeTo( Other, Damage, DamageType );
		#debug   BehaviorController.Update( BC_TookDamage, GetContext() );
		#release BehaviorController.Update( BC_TookDamage );
	}
}

//-----------------------------------------------------------------------------

function SpecialDeathHandling( Pawn KilledPawn )
{
	class'UtilSquad'.static.CheckSquadOrdersOnMemberLost( Self, KilledPawn );
}

//-----------------------------------------------------------------------------

function eventTakeDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
{
	local Pawn OldPawn;
	
	OldPawn = Pawn;
	
	Super.eventTakeDamage( Damage, Instigator, HitLocation, Momentum, DamageType );

	if( Pawn == None || Pawn.Health <= 0 || Pawn.bDeleteMe )
		SpecialDeathHandling( OldPawn );
}

//-----------------------------------------------------------------------------

function HandleKnockDown()
{
	GotoState( KnockDownState ); //mdf-tbd: go through BC
}

//-----------------------------------------------------------------------------

function EndPanic()
{
	Super.EndPanic();
	
	if( Pawn != None )
	{
		// pretty bad accuracy for next sec or so?
		// !!mdf-tbd: alternatively, stay in the panic state at a "recover" label for a bit?
		LastAcquireTime = Level.TimeSeconds + 0.5;
		Pawn.LastPainAnimTime = Level.TimeSeconds + 0.5;
	}
}

//-----------------------------------------------------------------------------
//@ COMBAT
//-----------------------------------------------------------------------------

/*-----------------------------------------------------------------------------
Try moving at right angles to enemy on the side that the NPC is currently 
headed towards (i.e. if an NPC, moving at least somewhat to its left acquires 
an enemy, continue moving to the left (but now at right angles to the enemy) to
maximize chances of exposing the firing offset.
*/

function bool GetPossibleFiringLocation( out vector FiringLocation )
{
	local vector RightAngleDirection;
	
	RightAngleDirection = Normal( (ControllerEnemy.Location - Pawn.Location) cross vect(0,0,1) );

	//AddArrow( Pawn.Location, Pawn.Location + 128.0*Normal(Pawn.Velocity), ColorWhite() );

	if( Pawn.Velocity dot RightAngleDirection > 0 )
		FiringLocation  = Pawn.Location + Pawn.CollisionRadius *  RightAngleDirection;
	else
		FiringLocation  = Pawn.Location + Pawn.CollisionRadius * -RightAngleDirection;

	//AddArrow( Pawn.Location, FiringLocation, ColorOrange() );
	
	return true;
}
		
/*tbd
//-----------------------------------------------------------------------------
// Return true if enemy can be attacked (e.g. shot) from the current location.
// This could be tricky -- some weapons have different fire offsets depending
// on whether they are alt fired or fired and whether they are instant hit or
// projectile based (including particle based projectiles).

function bool CanAttackEnemy()
{
	if( !CanSee( ControllerEnemy ) )
		return false;
			
	if( 
}
*/

//-----------------------------------------------------------------------------

function ClearCoverSpot()
{
	if( CurrentCoverSpot != None )
	{
		CurrentCoverSpot.Destroy();
		CurrentCoverSpot = None;
	}
}

//-----------------------------------------------------------------------------

function AssignCoverSpot( CoverSpot NewCoverSpot )
{
	ClearCoverSpot();
	CurrentCoverSpot = NewCoverSpot;
	//CurrentCoverSpot.bHidden = false;
	//CurrentCoverSpot.SetDrawScale( 5.0 );
}

//-----------------------------------------------------------------------------

function NotifyMetaStateChange()
{
	//why? even if changed metastate, shouldn't we keep the old coverspot as long as its valid?
	// ClearCoverSpot();
}

//-----------------------------------------------------------------------------

function SetExecuteOrders( bool bVal )
{
	local bool bExecuteOrdersOld;
	
	bExecuteOrdersOld = bExecuteOrders;
	//DMTNS( "(" $ Pawn $ ") SetExecuteOrders: " $ bExecuteOrders $ " --> " $ bVal );
	
	bExecuteOrders = bVal;
	
	if( bExecuteOrdersOld != bExecuteOrders && BehaviorController != None )
	{
		#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
		#release BehaviorController.Update( BC_AttackUpdate );
	}
		
	if( U2PBasic != None && U2PBasic.bCanStrafeDuringOrders )
	{
		if( bVal )
			U2PBasic.bCanStrafe = true;
		else
			U2PBasic.bCanStrafe = U2PBasic.default.bCanStrafe;
	}
}

//-----------------------------------------------------------------------------

function RestoreCanStrafe()
{
	if( !bExecuteOrders )
	{
		// not carrying out orders -- restore as usual
		Super.RestoreCanStrafe();
	}
	else 
	{
		// carrying out orders
		if( U2PBasic == None || !U2PBasic.bCanStrafeDuringOrders )
		{
			// not a "special" NPC -- restore as usual
			Super.RestoreCanStrafe();
		}
		else
		{
			// special NPC -- make sure bCanStrafe is true
			Pawn.bCanStrafe = true;
		}
	}
}
	
//-----------------------------------------------------------------------------
// Called when current enemy becomes invalid or NPC is abandoning it. Checks if 
// there is another enemy to attack and updates the BC accordingly.

function UpdateEnemy( optional bool bTryRadiusCheck )
{
	//2002.12.08 mdf-tbd: clear old enemy if this was a stationary pawn (XMP item)
	//so that NPC will only attack it if necessary (blocked by it).
	if( !ValidEnemy( OldControllerEnemy ) || StationaryPawn( OldControllerEnemy ) != None )
		OldControllerEnemy = None;

	// !!mdf-tbd: this is potentially bad if the old enemy is still valid but went
	// out of sight etc. and wasn't cleared. Either code which handles loss
	// of LOS, will clear ControllerEnemy or go hunting etc. or alternatively, we could 
	// make this function smarter and swap ControllerEnemy and OldControllerEnemy if both are 
	// valid but ControllerEnemy is no longer visible. My feeling at this point is that
	// this is a decision which is best handled in the attacking controller.
	#debug   SetControllerEnemy( OldControllerEnemy, GetContext() );
	#release SetControllerEnemy( OldControllerEnemy );

	if( ControllerEnemy == None && bTryRadiusCheck )
	{
		#debug   SetControllerEnemy( FindLocalEnemy( MaxRadiusEnemiesDistance ), GetContext() );
		#release SetControllerEnemy( FindLocalEnemy( MaxRadiusEnemiesDistance ) );
	}
	
	if( ControllerEnemy != None )
	{
		if( BehaviorController != None )
		{
			#debug   BehaviorController.Update( BC_EnemyChanged, GetContext() ); //!!mdf-tbd: do additional checks -- is the enemy visible, reachable etc.? (or do in UpdateEnemy?)
			#release BehaviorController.Update( BC_EnemyChanged ); //!!mdf-tbd: do additional checks -- is the enemy visible, reachable etc.? (or do in UpdateEnemy?)
		}
	}
	else
	{
		// 2002.12.14 (mdf) I don't think we should set the bExecuteOrders here 
		// if there is no enemy (set orders when enemy acquired based on squad
		// situation)?
		//if( HasSquadOrders() )
		//	SetExecuteOrders( true ); // no enemy so enable orders? //!!mdf-tbd: not sure
		if( BehaviorController != None )
		{
			#debug   BehaviorController.Update( BC_EnemyInvalid, GetContext() );
			#release BehaviorController.Update( BC_EnemyInvalid );
		}
	}
	
	//DMTNS( "UpdateEnemy  ControllerEnemy: " $ ControllerEnemy );
}

//-----------------------------------------------------------------------------

function HandleEnemyInvalid()
{
	// Pretty much the default desired behavior for any attack state?
	//DMTNS( "HandleEnemyInvalid" );
	if( IsFiring() )
		UnlockAnimationController();
	UpdateEnemy();
}

//-----------------------------------------------------------------------------
// mdf-tbd: shouldn't add significant overhead to do this since this will now
// only be called if Enemy is set but has become invalid.

event EnemyInvalid() 
{ 
	HandleEnemyInvalid(); 
}

//-----------------------------------------------------------------------------

function bool OKToHit( Actor HitActor, vector HitLocation, vector HitNormal )
{
	#debug DMAI( "OKToHit: " $ HitActor );

	return( HitActor == OldControllerEnemy || Super.OKToHit( HitActor, HitLocation, HitNormal ) );
}

//-----------------------------------------------------------------------------

function float GetAttackStyle( Actor TargetActor )
{
	local float ReturnedStyle;
	local float DistanceToEnemy;

	DistanceToEnemy = VSize( Pawn.Location - TargetActor.Location );

	if( DistanceToEnemy > 2*U2PBasic.RangeIdealAttack )
		ReturnedStyle = StyleCharge;
	else if( DistanceToEnemy > U2PBasic.RangeIdealAttack )
		ReturnedStyle =  StyleClose;
	else if( DistanceToEnemy < 0.5*U2PBasic.RangeIdealAttack )
		ReturnedStyle =  StyleRetreat;
	else if( DistanceToEnemy < U2PBasic.RangeIdealAttack )
		ReturnedStyle =  StyleBackoff;
	else
		ReturnedStyle =  StyleNeutral;
		
	//DMTNS( "Basic.GetAttackStyle returning " $ ReturnedStyle );
	return ReturnedStyle;
}

//-----------------------------------------------------------------------------

function float GetDefenseStyle( Actor TargetActor )
{
	//DMTNS( "Basic.GetDefenseStyle returning " $ StyleNeutral );
	return StyleNeutral; // mdf-tbd: add properties for this for tweaking various basic NPCs?
}

//-----------------------------------------------------------------------------

function byte PriorityObjective() { return 0; } //mdf-tbd: move to advanced/bot?
function bool FindSpecialAttraction() { return false; } //mdf-tbd: move to advanced/bot?

//-----------------------------------------------------------------------------

function bool SplashJump()
{
	return false;
}

//-----------------------------------------------------------------------------

function bool SplashDamageAttack()
{
	return ( IsFiring() && U2PBasic.bSplashDamageAttack );
}	

//-----------------------------------------------------------------------------

function bool HasInstantHitAttack()
{
	return U2PBasic.bInstantHitAttack;
}

//-----------------------------------------------------------------------------

function bool TrySplashDamageAttack() 
{
	return false; // mdf-tbd whether we want/need basic NPCs to try for splash damage
}

//-----------------------------------------------------------------------------

function bool IsMeleeAttacking()
{
	return( Pawn != None &&
			Pawn.MeleeOdds > 0.0 && 
			(bInitiatingAttack ||
			 (Level.TimeSeconds < MeleeEndTime) || 
			 (U2PBasic.MeleeNotifyTime > 0.0 && TimeRemaining( 'MeleeDamageTimer' ) > 0.0)) );
}

/*-----------------------------------------------------------------------------
Returns true if NPC is firing or is trying to fire.

This is used for example when taking damage to determine whether its ok to play 
a hit animation (without causing a ranged attack to be aborted).
*/

function bool IsFiring()
{
	//!!mdf tbd: is there a better way to do this, e.g. by looking at LastFireTime?
	//return Level.TimeSeconds - LastFireTime < 2.0;
	return ( bFire!=0 || bAltFire!=0 || IsMeleeAttacking() );
}

//-----------------------------------------------------------------------------
// Used to stop NPC from firing without aborting the current attack (won't
// clear animation-based attacks).

//-----------------------------------------------------------------------------

function StopFiringBase()
{
	bFire = 0;
	bAltFire = 0;
	
	//mdf-tbd: LastFireTime = -1.0;
	if( U2P.AnimationController != None )
		U2P.AnimationController.SpecialAnimationClear();

	RangedAttackAbort();
}

//-----------------------------------------------------------------------------

function StopFiringUpdate( float SuggestedFireAgainDelay )
{
	// reset the fire check timer	
	if( BehaviorController != None )
	{
		//DMTNS( "StopFiringUpdate: " $ SuggestedFireAgainDelay );
		BehaviorController.SetNextCheckFireShotDelay( SuggestedFireAgainDelay );
	}
}

//-----------------------------------------------------------------------------

#debug   function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo, string ContextStr )
#release function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo )
{
	#debug DMAIA( "  StopFiring Basic (" $ SuggestedFireAgainDelay $ "): " $ EnumStr( enum'EStopFiringInfo', SFInfo ) $ " (" $ ContextStr $ ")" );
	//DMTNS( "  StopFiring Basic (" $ SuggestedFireAgainDelay $ "): " $ EnumStr( enum'EStopFiringInfo', SFInfo ) $ " (" $ ContextStr $ ")" );
	StopFiringBase();
	StopFiringUpdate( SuggestedFireAgainDelay );
}

//-----------------------------------------------------------------------------

function BCStartFiring()
{
	// try to fire immediately
	if( BehaviorController != None )
		BehaviorController.StartFiring();
}

//-----------------------------------------------------------------------------

function BCBlockFiring( float SuggestedFireAgainDelay, bool bStopFiring )
{
	if( bStopFiring )
	{
		#debug   StopFiring( SuggestedFireAgainDelay, SFI_Behavior, GetContext() );
		#release StopFiring( SuggestedFireAgainDelay, SFI_Behavior );
	}
	if( BehaviorController != None )
		BehaviorController.BlockFiring( SuggestedFireAgainDelay );
}

//-----------------------------------------------------------------------------

function float GetSpecifiedFireRate( bool bPrimary )
{
	return U2PBasic.RefireRate; // return animation-based rate
}

//-----------------------------------------------------------------------------

function float GetCurrentFireRate()
{
	return U2PBasic.RefireRate; // return animation-based rate
}

//-----------------------------------------------------------------------------
// NOTE: although this is only ever applicable in the TacticalMove state, we
// need a global version because the state can sometimes change "as the call is 
// made" and this would otherwise result in a "failed to find function" error.

function bool StrafeFromDamage( float Damage, class<DamageType> DamageType, bool bFindDest );

//-----------------------------------------------------------------------------

function bool ShouldGiveUpHunting()
{
	return ( GetSkill() < 0.5 );
}

//-----------------------------------------------------------------------------

function bool GetShouldUseDeviousTactics( float BaseSkill, float BaseOdds )
{
	return ( GetSkill() >= BaseSkill && FRand() < BaseOdds );
}

//-----------------------------------------------------------------------------

function bool TestCanJump()
{
	return ( MoveTarget != None );
}

//-----------------------------------------------------------------------------
// NPC's enemy was killed but NPC currently has another enemy to deal with.

function HandleEnemyKilledUnSafe( Controller Killer, Pawn KilledEnemy )
{
	if( Killer == Self )
		U2P.AssetsHelperClass.static.HandleKilledEnemy( U2P );
}

//-----------------------------------------------------------------------------
// Called when an NPC's enemy is killed and the NPC currently has no enemy. Can
// be used to do simple things like taunting the enemy (e.g. bots might do this)
// or for more complex behavior (e.g. if bunch of araknids kill an enemy, the
// araknid who struck the fatal blow might get "first dibs" on the carcass, and
// other araknids will swarm the carcass once the killer is in place)..

function HandleEnemyKilledSafe( Controller Killer, Pawn KilledEnemy )
{
	if( Killer == Self )
		U2P.AssetsHelperClass.static.HandleKilledEnemySafe( U2P );
}

//-----------------------------------------------------------------------------

function HandleFriendDead( Pawn KilledFriend )
{
	if( !KilledFriend.ShouldGib( class'DamageTypePhysical' ) &&
		class'UtilGame'.static.ActorCanSeeActor( U2P, KilledFriend, -1.0 ) )
	{
		AddTimer( 'PlayFriendDeadSound', class'Util'.static.PerturbFloatPercent( U2P.FriendDeadSoundDelay, 30.0 ) );
	}
}

//-----------------------------------------------------------------------------

function PlayFriendDeadSound()
{
	U2P.AssetsHelperClass.static.HandleFriendDead( U2P );
}

//-----------------------------------------------------------------------------

function NotifyKilled( Controller Killer, Controller Killed, Pawn KilledPawn, class<DamageType> DamageType )
{
	//NOTE: don't call super -- this would clear enemy which is used below

	if( KilledPawn == Pawn && Killer != None )
	{
		#debug DMAI( "NotifyKilled -- I died Killer.Pawn: " $ Killer.Pawn $ "(" $ ValidEnemy( Killer.Pawn ) $ ")" );

		// I'm dead so I won't actually acquire the Instigator but nearby NPCs on my team might acquire him
		if( ValidEnemy( Killer.Pawn ) )
			MaybeAlertOthers( Killer.Pawn );
	}

	if( Pawn == None || Pawn.Health <= 0 )
		return;

	if( OldControllerEnemy == KilledPawn )
		OldControllerEnemy = None;

	if( ControllerEnemy == KilledPawn )
	{
		#debug   StopFiring( 0.5, SFI_TargetInvalid, GetContext() );
		#release StopFiring( 0.5, SFI_TargetInvalid );

		UpdateEnemy( true );

		if( ControllerEnemy == None )
			HandleEnemyKilledSafe( Killer, KilledPawn );
		else
			HandleEnemyKilledUnSafe( Killer, KilledPawn );
	}
	else if( Pawn.SameTeam( KilledPawn ) )
		HandleFriendDead( KilledPawn );
}	

//-----------------------------------------------------------------------------
// Check if I can see my current Destination point, and so can enemy.

function bool CanStakeOut()
{
	local vector LastEnemySeenLocation;
	
	LastEnemySeenLocation = GetLastEnemyDetectedLocation();
	
	return ( VSize( ControllerEnemy.Location - LastEnemySeenLocation ) <= 800 &&
			 Pawn.FastTrace( LastEnemySeenLocation, Pawn.Location + Pawn.EyeHeight * vect(0,0,1) ) && 
			 Pawn.FastTrace( LastEnemySeenLocation, ControllerEnemy.Location + ControllerEnemy.BaseEyeHeight * vect(0,0,1) ) );
}

//-----------------------------------------------------------------------------

function SetPeripheralVision()
{
	Super.SetPeripheralVision();

	if( Pawn != None && bSniping && AmbushSpot != None )
		Pawn.SetSightRadius( AmbushSpot.SightRadius );
}

//-----------------------------------------------------------------------------

function SpawnShotTimer()
{
	#debug DMAIA( "SpawnShotTimer" );
	//class'U2GameInfo'.static.BSM( Self, "WTF?" );
	if( Pawn.Health > 0 && IsFiring() )
		U2PBasic.SpawnShot();
}

//-----------------------------------------------------------------------------

function bool CanUseStillAnimations() { return false; }

//-----------------------------------------------------------------------------

function FireShot( byte bUseAltMode )
{
	local float AnimationDuration;
	
	#debug DMAIA( "FireShot (basic)" );

	//mib-tbd hack to restore weapon state
	if( U2PBasic != None )
	{
		if( !bUseAltMode )
			bFire = 1;
		else
			bAltFire = 1;
		
		if( U2PBasic.AnimationController != None )
			AnimationDuration = U2PBasic.AnimationController.SpecialAnimationRangedAttack( CanUseStillAnimations() );
		//DMTNS( "FireShot calling SetNextCheckFireShotDelay: " $ AnimationDuration );
		if( BehaviorController != None )
		{
			BehaviorController.SetNextCheckFireShotDelay( AnimationDuration );
			BehaviorController.SetMinTimeOutDelay( AnimationDuration );
		}
		
		if( U2PBasic.RangedNotifyTime > 0.0 )
		{
			// these should be replaced with actual notifies
			DMAssert( false, GetContext() );
			AddTimer( 'SpawnShotTimer', U2PBasic.RangedNotifyTime, false );
		}
	}
}

//-----------------------------------------------------------------------------

function FireAt( Actor A )
{
	FireShot( 0 );
}

//-----------------------------------------------------------------------------

function MeleeDamageTimer()
{
	if( Pawn.Health > 0 && IsMeleeAttacking() )
		U2PBasic.NotifyMelee01();
}

//-----------------------------------------------------------------------------

function MeleeAttack( byte bUseAltMode )
{
	local float MeleeAnimationDuration;
	
	//	#debug DMAIA( "MeleeAttack" );

	bInitiatingAttack = true;
	MeleeAnimationDuration = U2P.AnimationController.SpecialAnimationMeleeAttack();
	
	bInitiatingAttack = false;
	if( U2PBasic.MeleeNotifyTime > 0.0 )
	{
		// these should be replaced with actual notifies
		DMAssert( false, "dependencies on MeleeNotifyTime need to be removed " $ GetContext() );
		AddTimer( 'MeleeDamageTimer', U2PBasic.MeleeNotifyTime, false );
	}
	
	if( MeleeAnimationDuration > 0.0 )
	{
		//!!CDH (mdf): in some cases the returned animation duration is off and 
		// playing the animation again b4 it finishes causes it to "lock up" so
		// adding 0.05 seconds in here. This fixes the seagoat for example.
		MeleeAnimationDuration += 0.05;
		BehaviorController.SetMinTimeOutDelay( MeleeAnimationDuration );
		U2PBasic.NotifyMeleeBegin();
		MeleeEndTime = Level.TimeSeconds + MeleeAnimationDuration;
	}
}

//-----------------------------------------------------------------------------

function float SetSpecialAnim( name AnimAction, bool bOverrideBehavior )
{
	local float AnimationDuration;
	
	AnimationDuration = U2P.AnimationController.SpecialAnimation( AnimAction );
	if( AnimationDuration == 0.0 )
		DMTNS( "WARNING - no acquisition animation for " $ Pawn $ " AnimSequence: " $ Pawn.AnimSequence );
	
	if( bOverrideBehavior )
		BehaviorController.SetMinTimeOutDelay( AnimationDuration );
	
	//DMTNS( "playing special animation (" $ AnimAction $ "), sleeping for " $ AnimationDuration $ " seconds " );
	return AnimationDuration;
}

//-----------------------------------------------------------------------------

function MeleeAttackAbort()
{
	if( U2P != None && U2P.AnimationController != None )
		U2P.AnimationController.SpecialAnimationMeleeAttackAbort();
}

//-----------------------------------------------------------------------------

function RangedAttackAbort()
{
	if( U2P != None && U2P.AnimationController != None )
		U2P.AnimationController.SpecialAnimationRangedAttackAbort();
}

//-----------------------------------------------------------------------------
// Impaling attack behavior

function bool IsImpaling() { return false; }

//-----------------------------------------------------------------------------

function bool CanImpale( Pawn Victim )
{
	return( CheckMeleeAttackRange( Victim ) &&
			vector(Pawn.Rotation) dot vector(Victim.Rotation) < MinImpaleCos );
}

//-----------------------------------------------------------------------------

function ImpaleAttack()
{
	GotoState( ImpalingState );
}

//-----------------------------------------------------------------------------

function ImpaleAttackAnimationAbort()
{
	//#debug DMAIA( "ImpaleAttackAnimationAbort" );
	if( U2PBase != None )
		U2P.AnimationController.SpecialAnimationImpaleAttackAbort()	;
}

//-----------------------------------------------------------------------------

// Animation notifications
function ImpalePawn();
function UnImpalePawn();

/* mdf-tbd: nothing uses this currently
//-----------------------------------------------------------------------------
// combo move

function SpecialFire()
{
	bFiringPaused = true;
	StopMovement( true, false );
	GS( AttackStationaryState ); //GS-tbd
}
*/

//-----------------------------------------------------------------------------

function bool IsPreparedToFire( bool bOwner, optional bool bCheckWeaponRating, optional int MinWeaponRating )
{
	return ( U2PBasic != None && U2PBasic.bHasRangedAttack );
}

//-----------------------------------------------------------------------------

function bool IsPreparedToMelee( bool bOwner, optional bool bCheckWeaponRating, optional int MinWeaponRating )
{
	return ( Pawn != None && Pawn.MeleeOdds > 0.0 );
}

//-----------------------------------------------------------------------------

function bool CanFire( bool bTest ) { return ( CheckTargetInAttackRange( bTest ) && IsFacingTarget( GetTarget(), CosMinFacingTargetAngle ) ); }

//-----------------------------------------------------------------------------

function bool HasSquadOrders()
{
	return ( Orders == OrdersSquad || (Orders == OrdersGoto && OrdersObject != None) );
}

//-----------------------------------------------------------------------------

function EnemyAcquired()
{
	#debug   BehaviorController.Update( BC_EnemyAcquired, GetContext() );
	#release BehaviorController.Update( BC_EnemyAcquired );
}
	
//-----------------------------------------------------------------------------
// Note, my enemy might not actually be set (e.g. if I was killed with 1 shot).

function MaybeAlertOthers( Pawn PotentialEnemy )
{
	local Controller C;

	//DMTNS( "MaybeAlertOthers" );

	if( U2PBase.AlertOthersRadius > 0.0 )
	{
		for( C=Level.ControllerList; C!=None; C=C.NextController )
		{
			if( C != Self && 
				U2NPCController(C) != None && 
				ValidPawn( C.Pawn ) && 
				U2PBase.SameTeam( C.Pawn ) )
			{
				U2NPCController(C).MaybeInheritEnemy( U2PBase, PotentialEnemy );
			}
		}
	}
}

//-----------------------------------------------------------------------------
// Return true if NPC should jump during tactical moves.

function bool UseTacticalJumps()
{
	return( FRand() < U2PBasic.TacticalJumpOdds );
}

//-----------------------------------------------------------------------------

/*!!mdf 
function NotTakingHit()
{
	if( Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z && 
		(Momentum.Z/Pawn.PhysicsVolume.Gravity.Z < -0.5) )
		bFireFalling = true;
	else
		Super.NotTakingHit();
}
*/

//-----------------------------------------------------------------------------

function NotifyTakeHit( Pawn Instigator, vector HitLocation, int Damage, class<DamageType> DamageType, vector Momentum )
{
	bFireFalling = false;
	Super.NotifyTakeHit( Instigator, HitLocation, Damage, DamageType, Momentum );
}

//-----------------------------------------------------------------------------

function ExecuteDodge( bool bLeft, vector DodgeDestination )
{
	Super.ExecuteDodge( bLeft, DodgeDestination );
	GotoState( DodgingState );
}

//-----------------------------------------------------------------------------

function UtilGame.ELeapResult GetLeapHighParameters( float TargetDistance, vector Extents, out vector LeapDestination, out float Theta, out float LeapSpeed )
{
	local vector PredictedLocation;
	local int FitActorAtResult;
	
	//DMTNS( "try to LEAP high" );
	LeapSpeed = U2PBasic.LeapHighSpeed;
	
	PredictedLocation = ControllerEnemy.Location;
	if( FDecision( U2PBasic.LeapHighPredictOdds ) )
	{
		// predict necessary target location
		class'UtilGame'.static.GetBestPredictedProjectileLocation( 
			Pawn, 
			ControllerEnemy, 
			class'Pawn', 
			LeapSpeed, 
			U2PBasic.LeapDelayPreJump + U2PBasic.LeapNotifyTime, 
			Pawn.Location, 
			TargetDistance, 
			true, 
			PredictedLocation );
	}
	
	//AddCylinder( PredictedLocation, Pawn.CollisionRadius, Pawn.CollisionHeight, ColorCyan() );
			
	LeapDestination = PredictedLocation;
			
	// align NPC "feet" with bottom of target location
	LeapDestination.Z += (Pawn.CollisionHeight - ControllerEnemy.CollisionHeight);
	
	FitActorAtResult = Pawn.FitActorAt( LeapDestination, Pawn.CollisionRadius + class'UtilGame'.default.VerifyTrajectoryHorizontalExtentPadding, Pawn.CollisionHeight + class'UtilGame'.default.VerifyTrajectoryVerticalExtentPadding );
	//DMTNS( "FitActorAtResult  #2: " $ FitActorAtResult );			
	if( FitActorAtResult == 0 )
	{
		// try aiming directly at enemy
		LeapDestination = ControllerEnemy.Location - (Pawn.CollisionRadius - ControllerEnemy.CollisionRadius) * Normal( Pawn.Location - ControllerEnemy.Location );
		// align NPC "feet" with bottom of target location
		LeapDestination.Z += (Pawn.CollisionHeight - ControllerEnemy.CollisionHeight);
	}
	
	//AddCylinder( LeapDestination, Pawn.CollisionRadius, Pawn.CollisionHeight, ColorOrange() );
	//AddArrow( Pawn.Location, LeapDestination, ColorOrange() );

	return class'UtilGame'.static.VerifyLeapParameters( 
				Pawn,
				class'Pawn',
				LeapSpeed,
				LeapDestination,
				Pawn.Location,
				ControllerEnemy,
				TRAJ_High, 
				Theta,
				Extents );
}		

//-----------------------------------------------------------------------------

function UtilGame.ELeapResult GetLeapLowParameters( float TargetDistance, vector Extents, out vector LeapDestination, out float Theta, out float LeapSpeed )
{
	local vector PredictedLocation;
	local int FitActorAtResult;

	//DMTNS( "try to LEAP low" );
	LeapSpeed = U2PBasic.LeapLowSpeed;

	PredictedLocation = ControllerEnemy.Location;
	if( FDecision( U2PBasic.LeapLowPredictOdds ) )
	{
		// predict necessary target location
		class'UtilGame'.static.GetBestPredictedProjectileLocation( 
			Pawn, 
			ControllerEnemy, 
			class'Pawn', 
			LeapSpeed, 
			U2PBasic.LeapDelayPreJump + U2PBasic.LeapNotifyTime, 
			Pawn.Location, 
			TargetDistance, 
			false, 
			PredictedLocation );
	}
	
	// aim to leap through enemy somewhat
	LeapDestination = PredictedLocation + vect(0,0,1) * ControllerEnemy.CollisionHeight;
	
	// align NPC "feet" with bottom of target location
	LeapDestination.Z += (Pawn.CollisionHeight - ControllerEnemy.CollisionHeight);

	//AddCylinder( LeapDestination, Pawn.CollisionRadius, Pawn.CollisionHeight, ColorGreen() );
	FitActorAtResult = Pawn.FitActorAt( LeapDestination, Pawn.CollisionRadius + class'UtilGame'.default.VerifyTrajectoryHorizontalExtentPadding, Pawn.CollisionHeight + class'UtilGame'.default.VerifyTrajectoryVerticalExtentPadding );
	//AddCylinder( LeapDestination, Pawn.CollisionRadius, Pawn.CollisionHeight, ColorBlue() );
	
	//DMTNS( "FitActorAtResult #1: " $ FitActorAtResult );			
	if( FitActorAtResult == 0 )
	{
		// doesn't fit at overshoot location -- back up to predicted location
		LeapDestination = PredictedLocation - (Pawn.CollisionRadius - ControllerEnemy.CollisionRadius) * Normal( Pawn.Location - PredictedLocation );
		
		// align NPC "feet" with bottom of target location
		LeapDestination.Z += (Pawn.CollisionHeight - ControllerEnemy.CollisionHeight);
		FitActorAtResult = Pawn.FitActorAt( LeapDestination, Pawn.CollisionRadius + class'UtilGame'.default.VerifyTrajectoryHorizontalExtentPadding, Pawn.CollisionHeight + class'UtilGame'.default.VerifyTrajectoryVerticalExtentPadding );
		
		//DMTNS( "FitActorAtResult  #2: " $ FitActorAtResult );			
		if( FitActorAtResult == 0 )
		{
			// doesn't fit at overshoot location -- aim directly at enemy
			LeapDestination = ControllerEnemy.Location - (Pawn.CollisionRadius - ControllerEnemy.CollisionRadius) * Normal( Pawn.Location - ControllerEnemy.Location );
			// align NPC "feet" with bottom of target location
			LeapDestination.Z += (Pawn.CollisionHeight - ControllerEnemy.CollisionHeight);
		}
	}
	
	//AddCylinder( PredictedLocation, 4, 4, ColorMagenta() );	
	//AddCylinder( LeapDestination, 16, 16, ColorGreen() );
	//AddArrow( Pawn.Location, LeapDestination, ColorGreen() );
	
	return class'UtilGame'.static.VerifyLeapParameters( 
				Pawn,
				class'Pawn',
				LeapSpeed,
				LeapDestination,
				Pawn.Location,
				ControllerEnemy,
				TRAJ_Low, 
				Theta,
				Extents );
}

//-----------------------------------------------------------------------------

function bool GetLeapMaxParameters( out vector LeapDestination, vector Extents, out float Theta, out float LeapSpeed )
{
	//DMTNS( "LEAP at 45 degrees?" );
			
	LeapDestination = ControllerEnemy.Location;
	if( Normal( LeapDestination - Pawn.Location ) dot vector(Pawn.Rotation) < 0.707 )
		return false;
		
	LeapSpeed = U2PBasic.LeapLowSpeed;
	Theta = -45 * DegreesToRadians;
			
	//AddCylinder( PredictedLocation, 16, 16, ColorRed() );
	//AddArrow( Pawn.Location, PredictedLocation, ColorRed() );

	return class'UtilGame'.static.VerifyTrajectory( Pawn, class'Pawn', LeapSpeed, Pawn.Location, LeapDestination, ControllerEnemy, Theta, /*InterceptTime*/, Extents );
}
	
//-----------------------------------------------------------------------------
// !!mdf-tbd: maybe try different leap speeds depending on the circumstances?

function bool GetLeapParameters( out rotator LeapRotation, out float LeapSpeed )
{
	local vector LeapDestination;
	local float Theta;
	local float TargetDistance;
	local vector Extents;
	local UtilGame.ELeapResult LeapResult;
	local bool bTriedHigh, bSuccess;
	
	if( Pawn == None || ControllerEnemy == None )
		return false;
		
	//AddActor( Pawn, ColorRed() );
	//AddActor( ControllerEnemy, ColorGreen() );
	
	Extents.X = Pawn.CollisionRadius;
	Extents.Y = Pawn.CollisionRadius;
	Extents.Z = Pawn.CollisionHeight;

	TargetDistance = VSize( ControllerEnemy.Location - Pawn.Location );
	//DMTNS( "TargetDistance: " $ TargetDistance );
	if( TargetDistance > U2PBasic.OnlyLeapLowRange && FDecision( U2PBasic.LeapHighOdds ) )
	{
		// try a high leap
		bTriedHigh = true;
		LeapResult = GetLeapHighParameters( TargetDistance, Extents, LeapDestination, Theta, LeapSpeed );
		bSuccess = (LeapResult == LR_Success );
		
		//if( bSuccess )
		//	DMTNS( "  LEAP HIGH!" );
	}

	if( !bSuccess )
	{
		// try a low leap, then maybe a high leap, then maybe a max leap
		LeapResult = GetLeapLowParameters( TargetDistance, Extents, LeapDestination, Theta, LeapSpeed );
		bSuccess = ( LeapResult == LR_Success );

		//if( bSuccess )
		//	DMTNS( "LEAP LOW!" );
		
		if( !bSuccess && LeapResult != LR_OutOfRange && !bTriedHigh && TargetDistance > U2PBasic.OnlyLeapLowRange && U2PBasic.LeapHighOdds > 0.0 )
		{
			LeapResult = GetLeapHighParameters( TargetDistance, Extents, LeapDestination, Theta, LeapSpeed );
			bSuccess = ( LeapResult == LR_Success );
			//if( bSuccess )
			//	DMTNS( "LEAP HIGH (low failed)!" );
		}
				
		if( LeapResult == LR_OutOfRange && FDecision( U2PBasic.LeapMaxOdds ) )
		{
			bSuccess = GetLeapMaxParameters( LeapDestination, Extents, Theta, LeapSpeed );
			//if( bSuccess )
			//	DMTNS( "  LEAP MAX!" );
		}
	}

	//if( !bSuccess )
	//	DMTNS( "  LEAP FAILED!" );
	
	if( bSuccess )
	{
		// set leap parameters
		LeapRotation = rotator(LeapDestination - Pawn.Location); // rotation to aim directly at target
	
		// modify the leap pitch
		if( Theta < 0 )
			LeapRotation.Pitch = RadiansToDegrees * -Theta * DegreesToRotationUnits;
		else
			LeapRotation.Pitch = 65535 - RadiansToDegrees * Theta * DegreesToRotationUnits;
	}
	
	return bSuccess;
}

//-----------------------------------------------------------------------------

function bool CanAttemptLeapAttack()
{
	return( Level.TimeSeconds >= NextLeapTime &&
			Pawn.Physics == PHYS_Walking && 
			(ControllerEnemy.Physics == PHYS_Walking || ControllerEnemy.Physics == PHYS_Falling) && 
			(!U2PBasic.bLeapRequiresLOS || GetTimeSinceEnemyLastDetected() < 0.2) &&
			ValidEnemy( ControllerEnemy ) );
}

//-----------------------------------------------------------------------------

event EnemyInLeapRange( float Distance )
{
	if( FDecision( Pawn.LeapOdds ) && CanAttemptLeapAttack() )
		GotoState( AttackLeapState );
}

//-----------------------------------------------------------------------------

event EnemyInMeleeRange()
{
	if( FDecision( Pawn.MeleeOdds ) || !IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) )
	{
		#debug   BehaviorController.Update( BC_MeleeRange, GetContext() );
		#release BehaviorController.Update( BC_MeleeRange );
	}
}

//-----------------------------------------------------------------------------
//@ INTERACTIONS
//-----------------------------------------------------------------------------

function bool ShouldDeferTo( Controller Other )
{
	return ( Orders == OrdersFollow && Other == OrdersObject );
}

//-----------------------------------------------------------------------------

function bool DeferTo( Controller Other )
{
	if( ShouldDeferTo( Other ) )
	{
		if( ControllerEnemy != None && LineOfSightTo( ControllerEnemy ) )
		{
			GotoState( AttackTacticalMoveState, DontCloseLabel ); //GS-tbd
		}
		else
		{
			#debug   SetControllerEnemy( None, GetContext() );
			#release SetControllerEnemy( None );
			OldControllerEnemy = None;

			//!!mdf--this might need to be in base?
			if( Pawn.Health > 0 && Pawn.Acceleration == vect(0,0,0) )
			{
				WanderDirectionExternal = Other.Pawn.CollisionRadius*2.0*Normal( Pawn.Location - Other.Pawn.Location );
				GotoState( WanderingState, BeginLabel ); //GS-tbd
			}
		}
		return true;
	}

	return Super.DeferTo( Other );
}

//-----------------------------------------------------------------------------
// Only called for Pawn's which are already known to be an enemy. Returns fear
// or attack.

function EReaction GetReactionToEnemy( Pawn EnemyPawn )
{
	local EReaction ReturnedReaction;
	local float CurrentRelativeStrength;
	
	// mdf-tbd: in U2 turrets might be destroyable so NPCs might need to attack
	// these (while moving around, taking cover, doding projectiles?)
	if( StationaryPawn(EnemyPawn) != None )
	{
		// fear turrets but not force fields (if smart about turrets)	
		if( bSmartAboutTurrets && StationaryPawn(EnemyPawn).bHasAttack )
			ReturnedReaction = REACTION_Fear;
		else
			ReturnedReaction = REACTION_Attack;
	}
	else
	{
		CurrentRelativeStrength = RelativeStrength( EnemyPawn );
		
		if( CurrentRelativeStrength > 0.0 )
		{
			// stronger than enemy -- more likely to attack with increasing skill and Aggressiveness
			if( (CurrentRelativeStrength + Aggressiveness) > (1.0 - GetSkill()) )
				ReturnedReaction = REACTION_Attack;
			else
				ReturnedReaction = REACTION_Fear;
		}
		else
		{
			// weaker than enemy -- more likely to run away with increasing skill and decreasing Aggressiveness
			if( (CurrentRelativeStrength + Aggressiveness) > (1.0 - GetSkill()) )
				ReturnedReaction = REACTION_Fear;
			else
				ReturnedReaction = REACTION_Attack;
		}
	}
	
	return ReturnedReaction;
}

//-----------------------------------------------------------------------------
// mdf-tbi: implement bAlwaysSetAnnoyingNewEnemy -- NPCs which use this (with
// bAlwaysSetEnemy=false) will generally focus on one enemy at a time but if
// a 2nd enemy bumps or damages them then they'll attack it. Not implemented
// yet (just need to add hooks for communicating way in which enemy was 
// detected (see/hear vs bump/damage) via AnnoyedAt or as a parameter to 
// SeeEnemy (leaning towards AnnoyedAt currently -- maintain fixed-sized list
// of recently acquired NPCs & whether annoyed at them).

function bool MaybeAcquireEnemy( Pawn NewEnemy )
{
	#debug DMAIA( "MaybeAcquireEnemy - Enemy: " $ ControllerEnemy $ " OldControllerEnemy: " $ OldControllerEnemy );
	//DMTNS( "MaybeAcquireEnemy - ControllerEnemy: " $ ControllerEnemy $ " OldControllerEnemy: " $ OldControllerEnemy $ " NewEnemy: " $ NewEnemy );

	//2002.12.18 (mdf) this only affects NPCs with the primary script in obolus
	if( bXMPHandlingEnabled )
	{
		// don't allow the fact that we are autonomous to deal with XMP items
		// let us acquire a non-stationary pawn enemy or another XMP item if
		// we already have one as an enemy
		if( StationaryPawn(NewEnemy) == None || StationaryPawn(ControllerEnemy) != None )
			return false;
	}
	
	if( ControllerEnemy == None || U2PBasic.bAlwaysAttackNewEnemy /*|| (U2PBasic.bAlwaysAttackAnnoyingNewEnemy && AnnoyedAt(NewEnemy)) */ )
	{
		#debug DMAIA( "  acquiring new enemy" );
		//DMTNS( "  acquiring new enemy" );
	   
		if( ControllerEnemy == None	&& HasSquadOrders() )
			class'UtilSquad'.static.CheckSquadOrdersOnEnemyAcquired( Pawn );
		
		#debug   SetControllerEnemy( NewEnemy, GetContext() );
		#release SetControllerEnemy( NewEnemy );
	}
	else if( CompareThreat( NewEnemy, ControllerEnemy ) > 0.0 )
	{
		// new enemy bigger threat than current enemy
		#debug DMAIA( "  switching from current enemy to new enemy, maybe replace old enemy with current enemy" );
		//DMTNS( "  switching from current enemy to new enemy, maybe replace old enemy with current enemy" );

		// replace old enemy with current enemy if bigger threat
		if( OldControllerEnemy == None || CompareThreat( ControllerEnemy, OldControllerEnemy ) > 0.0 )
			OldControllerEnemy = ControllerEnemy;

		#debug   SetControllerEnemy( NewEnemy, GetContext() );
		#release SetControllerEnemy( NewEnemy );
	}
	else
	{
		// current enemy bigger threat than new enemy
		#debug DMAIA( "  keeping current enemy, maybe replace old enemy with new enemy" );
		//DMTNS( "  keeping current enemy, maybe replace old enemy with new enemy" );

		// replace old enemy with new enemy if bigger threat
		if( OldControllerEnemy == None || CompareThreat( NewEnemy, OldControllerEnemy ) > 0.0 )
			OldControllerEnemy = NewEnemy;
	}

	return( ControllerEnemy == NewEnemy );
}

//-----------------------------------------------------------------------------
//@ MISC
//-----------------------------------------------------------------------------

function CoverSpot FindCoverActor( float MaxDistance, float	CosMinAngle, float CosMaxAngle, bool bIncludePathable )
{
	//!!mdf-tbd: this should fix the crash but I'd like to find out how this is happening
	DMTNS( "Warning: FindCoverActor called in " $ GetStateName() $ " state" );
	return None;
}

//-----------------------------------------------------------------------------

function HandleBump( Pawn Other, bool bEnemy );

//-----------------------------------------------------------------------------
//@ ORDERS
//-----------------------------------------------------------------------------

function name		GetOrders()						{ return Orders; }
function Actor		GetOrdersObject()				{ return OrdersObject; }
function float		GetOrdersThreshold()			{ return OrdersThreshold; }
function Object		GetOrderGiver()					{ return OrderGiver; }

//-----------------------------------------------------------------------------

function Actor GetHoldActor()
{
	local Actor ReturnedActor;
	
	if( bStationary )
	{
		if( StationarySpot != None )
			ReturnedActor = StationarySpot;
		else
			ReturnedActor = GetHoldSpot( Pawn );
	}
	else
	{
		ReturnedActor = OrdersObject;
	}
	
	return ReturnedActor;
}		

//-----------------------------------------------------------------------------

function ClearHoldSpots()
{
	Super.ClearHoldSpots();
	ClearHoldSpot( OrdersObject );
	ClearHoldSpot( StationarySpot );
}

//-----------------------------------------------------------------------------

function bool UpdateStance( byte TargetStance, optional float EnemyDistance )
{
	local bool bResult;
	local byte OldStance;
	
	OldStance = Pawn.GetStance();
	bResult = Super.UpdateStance( TargetStance, EnemyDistance );
	if( bResult && (TargetStance == ST_Prone || OldStance == ST_Prone) )
	{
		//DMTNS( "going to/from prone -- stop firing for " $ ProneStanceChangeDuration );
		BCBlockFiring( ProneStanceChangeDuration, true ); // don't fire during prone stance change
	}
			
	return bResult;
}

//-----------------------------------------------------------------------------
// Prevents NPC from moving but NPC can still shoot and rotate towards target.
// Unlike hold orders -- these keep an NPC in a general area but the NPC can
// still wander/roam (if applicable) and will revert to moving around when an
// enemy appears. If NPC is no longer dealing with an enemy and goes back to
// the hold state, NPC will try to get back to his original location and
// and rotation and will set his stance to the stance active when the NPC was
// made stationary.
//
// mdf-tbd: support NPC being able to optionally chase no longer visible enemy 
// somewhat?

function SetStationary( bool bVal, optional bool bStayStationaryVal )
{
	bStationary = bVal;
	bStayStationary = bStayStationaryVal;
	
	ClearHoldSpot( StationarySpot );
		
	if( bStationary )
	{
		StationarySpot = GetHoldSpot( Pawn );
		if( StationarySpot != None )
		{
			// not ordered but uses OrdersObject anyway
			
			StationaryStance = LPawn.GetStance();
			//DMTN( "Saved stance is :" $ StationaryStance );
		}

		StopMovement( true, true );
	}

	#debug   WhatToDoNext( GetContext() );
	#release WhatToDoNext();
}

//-----------------------------------------------------------------------------

function bool IsStationary()	{ return  bStationary; }
function bool IsMobile()		{ return !bStationary; }

//-----------------------------------------------------------------------------

function bool ProcessOrdersFollow( out Actor NewOrdersObject, Object NewOrderGiver )
{
	local bool bResult;
	
	if( NewOrdersObject == None && Controller(NewOrderGiver) != None )
		NewOrdersObject = Controller(NewOrderGiver).Pawn;
		
	if( NewOrdersObject != None )
	{
		Aggressiveness += 1;
		bResult = true;
	}
		
	return bResult;
}

//-----------------------------------------------------------------------------

function bool ProcessOrdersGoto( out Actor NewOrdersObject )
{
	local bool bResult;

	if( NewOrdersObject != None )
	{
		Aggressiveness += 1;
		bResult = true;
	}
	
	return bResult;
}

//-----------------------------------------------------------------------------

function bool ProcessOrdersHold( out Actor NewOrdersObject, Object NewOrderGiver )
{
	local bool bResult;

	if( NewOrdersObject == None && Controller(NewOrderGiver) != None )
		NewOrdersObject = Controller(NewOrderGiver).Pawn;

	if( Pawn(NewOrdersObject) != None )
		NewOrdersObject = GetHoldSpot( Pawn(NewOrdersObject) ); // need to use a holdspot
		
	if( NewOrdersObject != None )
	{
		Aggressiveness += 1;
		bResult = true;
	}

	return bResult;
}

//-----------------------------------------------------------------------------

function bool ProcessOrdersNone()
{
	return true;
}

//-----------------------------------------------------------------------------

function bool ProcessOrdersSquad()
{
	return true;
}

//-----------------------------------------------------------------------------

function bool DetermineOrdersTransition( out name DestinationState, out name DestinationLabel )
{
	DestinationState = NoState;
	DestinationLabel = NoLabel;

	if( Orders == OrdersHold )
		DestinationState = HoldState;

	return ( DestinationState != NoState );
}

//-----------------------------------------------------------------------------

function bool ProcessOrders( name NewOrders, out Actor NewOrdersObject, out float NewOrdersThreshold, out Object NewOrderGiver )
{
	local bool bResult;

	switch( NewOrders )
	{
		case OrdersNone:
			bResult = ProcessOrdersNone();
			break;

    	case OrdersFollow:
			bResult = ProcessOrdersFollow( NewOrdersObject, NewOrderGiver );
			break;

    	case OrdersGoto:
			bResult = ProcessOrdersGoto( NewOrdersObject );
			break;

		case OrdersHold:
			bResult = ProcessOrdersHold( NewOrdersObject, NewOrderGiver );
			break;

		case OrdersSquad:
			NewOrderGiver = Self;
			bResult = ProcessOrdersSquad();
			break;

		default:
			bResult = false;
			DMAssert( false, GetContext() ); // mdf-tbr
			break;
	}
	
	return bResult;
}

//-----------------------------------------------------------------------------
// Sets the current OrdersObject and, if debug mode is enabled, hides the 
// previous OrdersObject and shows the new one, e.g. so an NPC's destination can
// be seen in-game.

function SetOrdersObject( Actor NewOrdersObject )
{
	if( bShowOrdersObjects && OrdersObject != None && OrdersObject.default.bHidden )
		HideActor( OrdersObject );

	OrdersObject = NewOrdersObject;

	if( bShowOrdersObjects && OrdersObject != None && OrdersObject.default.bHidden )
		ShowActor( OrdersObject, 5.0, STY_Translucent );
}

//-----------------------------------------------------------------------------

function ClearOrders()
{
	Aggressiveness = U2PBasic.BaseAggressiveness;

	// destroy old holdspot
	if( HoldSpot(OrdersObject) != None )
	{
		OrdersObject.Destroy();
		SetOrdersObject( None );
	}
}

//-----------------------------------------------------------------------------

function UpdateOrders( name NewOrders, Actor NewOrdersObject, float NewOrdersThreshold, Object NewOrderGiver )
{
	ClearOrders();
	
	Orders = NewOrders;
	SetOrdersObject( NewOrdersObject );
	OrdersThreshold = FMax( MinGoalDistance, NewOrdersThreshold );
	OrderGiver = NewOrderGiver;
}
	
/*-----------------------------------------------------------------------------
Handles incoming orders.

In most cases it should be unnecessary to override the handling of special 
orders but, if this happens, the "right" way to do this is to override the 
HandleXXXOrders function used to actually deal with specific orders (set the
destination state etc.).

To illustrate: the 'here' orders are used to immediately order an NPC to the
OrderGiver's location (used to test pathing and reachability). These can be
handled here (in one place). If SetOrders was used for this, it might be
necessary to modify code in several places.

Returns true if the given orders were successfully processed (valid).
*/

function bool SetOrders( optional name NewOrders, optional Actor NewOrdersObject, optional float NewOrdersThreshold, optional Object NewOrderGiver, optional bool bAcknowledge )
{
	local bool bResult;
	local name DestinationState, DestinationLabel;

	#debug DMAI( "SetOrders (begin) -- NewOrders: " $ NewOrders $ " NewOrderGiver: " $ NewOrderGiver $ " NewOrdersObject: " $ NewOrdersObject );
	//DMTNS( "SetOrders (begin) -- NewOrders: " $ NewOrders $ " NewOrderGiver: " $ NewOrderGiver $ " NewOrdersObject: " $ NewOrdersObject );

	//-------------------------------------------------------------------------
	// process new orders -- keep old orders until new ones are validated
	//-------------------------------------------------------------------------
	
	bResult = ProcessOrders( NewOrders, NewOrdersObject, NewOrdersThreshold, NewOrderGiver );
	
	//DMTNS( "Basic.SetOrders -- called ProcessOrders for " $ NewOrders $ " bResult: " $ bResult );
	if( bResult )
	{
		// cleanup, reset, re-initialization
		UpdateOrders( NewOrders, NewOrdersObject, NewOrdersThreshold, NewOrderGiver );

		// respond to orders asap (old code used to wait for WTDN, Roaming etc.. to notice orders change)
		if( ReadyForOrders() )
		{
			if( DetermineOrdersTransition( DestinationState, DestinationLabel ) )
				GotoState( DestinationState, DestinationLabel ); //GS-tbd
		}
	}

	if( HasSquadOrders() )
	{
		class'UtilSquad'.static.CheckSquadOrdersOnMemberAdded( Self );
	}
	else if( Orders == OrdersNone || OrdersObject == None )
	{
		class'UtilSquad'.static.CheckSquadOrdersOnMemberLost( Self, Pawn );
	}
	
	#debug DMAI( "SetOrders (end) -- Orders: " $ Orders $ " OrderGiver: " $ OrderGiver $ " OrdersObject: " $ OrdersObject );
	//DMTNS( "Basic.SetOrders returning " $ bResult );
	return bResult;
}

//-----------------------------------------------------------------------------

function Actor GetSpecialGoal()
{
	local Actor ReturnedGoal;

	if( Orders == OrdersFollow )
	{
		if( Controller(OrdersObject) != None )
			ReturnedGoal = Controller(OrdersObject).Pawn;
		else
			ReturnedGoal = OrdersObject;

		if( ReturnedGoal == None || ReturnedGoal.bDeleteMe )
		{
			#debug DMAI( "SetOrders " $ GetContext() );
			SetOrders( OrdersNone );
			ReturnedGoal = None;
		}			
	}
	else
	{
		ReturnedGoal = Super.GetSpecialGoal();
	}

	return ReturnedGoal;
}

//-----------------------------------------------------------------------------
//@ STATES -- BASE
//-----------------------------------------------------------------------------

state @ MoveToGoalWithEnemyState extends @ MoveToGoalBaseState
{
	function EnemyAcquired();
} // MoveToGoalWithEnemyState

//-----------------------------------------------------------------------------
//@ STATES -- MAIN
//-----------------------------------------------------------------------------

/*-----------------------------------------------------------------------------
NPC just acquired an enemy -- take some time to react, turning towards enemy, 
possibly playing a special animation and even staring at the enemy for a brief 
period so that NPCs don't instantly react to enemies.
*/

state @ AcquisitionState
{
	ignores BeginFalling, EnemyInLeapRange, NotifyLanded; 

	function PlayRandomSound();

	//-------------------------------------------------------------------------

	function ShotFiredNotification( Pawn Shooter, vector FireDir, class<Projectile> ProjectileClass, float ProjSpeed );
	
	//-------------------------------------------------------------------------

	singular function eventHearNoiseThreat( float Loudness, Actor NoiseMaker )
	{
		#debug DMAI( "eventHearNoiseThreat -- calling MaybeSetEnemy  NoiseMaker: " $ NoiseMaker );
		if( MaybeSetEnemy( NoiseMaker.Instigator ) )
			HandleEnemyNoise( NoiseMaker );
	}
	
	//-------------------------------------------------------------------------

	function eventSeeEnemy( Pawn Seen )
	{
		if( MaybeSetEnemy( Seen ) )
			Pawn.MakeNoise( 1.0 );
	} 

	//-------------------------------------------------------------------------
	
	function bool CanFire( bool bTest ) { return false; }
	
	//-------------------------------------------------------------------------

	function eventTookDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		Global.eventTookDamage( Damage, Instigator, HitLocation, Momentum, DamageType );
		#debug   UpdateBehavior( false, GetContext() );
		#release UpdateBehavior( false );
	}
	
	/*!!mdf-tbd:
	//-------------------------------------------------------------------------
	
	event BeginState()
	{
		//DMTNS( "BeginState" );
		// turn more slowly during acquisition?
		Pawn.RotationRate.Yaw = Min( 32000, Pawn.default.RotationRate.Yaw );
	}
	*/
		
	//-------------------------------------------------------------------------
	
	event EndState()
	{
		//DMTNS( "EndState" );
		UnlockAnimationController( true );
		BCStartFiring();
		if( Pawn != None )
			Pawn.RotationRate.Yaw = Pawn.default.RotationRate.Yaw;
	}
	
	//-------------------------------------------------------------------------

@ BeginLabel:
	WaitForLanding();
	StopMovement( true, false );
	Focus = ControllerEnemy;
	FocalPoint = Focus.Location;
	if( NeedToTurn( FocalPoint, NeedToTurnAngleCos ) )
		FinishRotation( DefaultRotationThreshold );
	FocalPoint = Focus.Location;

@ PostBeginLabel:
	//DMTNS( "Finished rotating, sleeping for " $ U2PBasic.MinAcquisitionDelay - (Level.TimeSeconds - LastAcquireTime) $ " secs" );
	Sleep( U2PBasic.MinAcquisitionDelay - (Level.TimeSeconds - LastAcquireTime) );
	
	// Play acquisition animation for less intelligent NPCs? Mercs, 
	// marines etc. have alert animations which should have kicked in by now.
	if( StationaryPawn(ControllerEnemy) == None )
		U2PBasic.HandleAcquireEnemySound();
		
	if( FDecision( U2PBasic.AcquisitionAnimationOdds ) )
	{
		StopMovement( true, true );
		//DMTNS( "ACQUIRE!" );
		Sleep( SetSpecialAnim( 'U2_Acquire', true ) );
		Sleep( U2PBasic.PostAcquisitionAnimationDelay );
	}
	#debug   UpdateBehavior( false, GetContext() );
	#release UpdateBehavior( false );
} // AcquisitionState

/*-----------------------------------------------------------------------------
Close in on an enemy.
*/

state @ AttackCloseState extends @ MoveToGoalWithEnemyState
{
	// can't ignore NotifyBump -- borks moving around friendly NPCs
	// 2002.11.11 added SeeEnemy -- we have an enemy, we can assume its in sight, no?
    ignores SeeFriend, SeeOther, SeeAlertFriend, HearNoise;

	//-------------------------------------------------------------------------

	event MayFall()
	{
		#debug DMAI( "MayFall" );

		if( MoveTarget == ControllerEnemy )
		{
			// if enemy is still reachable go ahead with the jump, otherwise abort it
			Pawn.bCanJump = ActorReachable( ControllerEnemy );
			if( !Pawn.bCanJump )
			{
				//DMTNS( "MayFall: BC_EnemyCantReach" );
				//GS( AttackTacticalMoveState, DontCloseLabel );
				#debug   BehaviorController.Update( BC_EnemyCantReach, GetContext() );
				#release BehaviorController.Update( BC_EnemyCantReach );
			}
		}
	}

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest ) { return ( U2PBasic.bHasMovingRangedAttack && FDecision( U2PBasic.AttackClosingCanFireOdds ) && Global.CanFire( bTest ) ); }

	//-------------------------------------------------------------------------

	function FearThisSpot( Actor aSpot )
	{
		#debug DMAI( "FearThisSpot" );
		Destination = Pawn.Location + 120 * Normal( Normal( Destination - Pawn.Location ) + Normal( Pawn.Location - aSpot.Location ) ); 
		GotoLabel( MoveActiveStrafeLabel );
	}

	//-------------------------------------------------------------------------

	function bool TryStrafe( vector SideDir )
	{ 
		local vector Extent, HitLocation, HitNormal;
		local Actor HitActor;

		#debug DMAI( "TryToStrafe" );

		Extent = Pawn.CollisionRadius * vect(1,1,0);
		Extent.Z = Pawn.CollisionHeight;
		HitActor = Pawn.Trace( HitLocation, HitNormal, Pawn.Location + 100 * SideDir, Pawn.Location, false, Extent );
		if( HitActor != None )
		{
			SideDir *= -1;
			HitActor = Pawn.Trace( HitLocation, HitNormal, Pawn.Location + 100 * SideDir, Pawn.Location, false, Extent );
		}
		if( HitActor != None )
			return false;
		
		if( Pawn.Physics == PHYS_Walking )
		{
			HitActor = Pawn.Trace( HitLocation, HitNormal, Pawn.Location + 100 * SideDir - Pawn.MaxStepHeight * vect(0,0,1), Pawn.Location + 100 * SideDir, false, Extent);
			if( HitActor == None )
				return false;
		}

		// do the strafe
		Destination = Pawn.Location + 250 * SideDir;
		GotoLabel( MoveActiveStrafeLabel );
		return true;
	}
			
	//-------------------------------------------------------------------------

	function TryToDodge( vector DuckDir, bool bDuckLeft )
	{
		#debug DMAI( "TryToDodge" );
		if( !U2PBase.bCanStrafe || FDecision( U2PBasic.DodgeInsteadofStrafeOdds ) )
			Global.TryToDodge( DuckDir, bDuckLeft );
		else if( U2PBase.bCanStrafe && MoveTarget == ControllerEnemy ) 
			TryStrafe( DuckDir );
	}

	//-------------------------------------------------------------------------

	function bool StrafeFromDamage( float Damage, class<DamageType> DamageType, bool bFindDest )
	{
		local vector SideDir;

		#debug DMAI( "StrafeFromDamage" );

		if( !Pawn.bCanStrafe )
			return false;

		if( FRand() * Damage < 0.15 * U2PBasic.CombatStyle * Pawn.Health ) 
			return false;

		if( !bFindDest )
			return true;

		if( ControllerEnemy == None )
			return false;

		SideDir = Normal( (ControllerEnemy.Location - Pawn.Location) cross vect(0,0,1) );
		if( ( Pawn.Velocity dot sidedir ) > 0 )
			sidedir *= -1;

		return TryStrafe( SideDir );
	}

	//-------------------------------------------------------------------------

	function eventTookDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		local float Pick;
		local vector SideDir;
		local bool bWasOnGround;

		#debug DMAI( "eventTookDamage" );

		// !!mdf-tbd: refactor with global
		if( Pawn.Health > 0 )
		{
			#debug DMAI( "eventTookDamage" );

			bWasOnGround = ( Pawn.Physics == PHYS_Walking );
	
			Global.eventTookDamage( Damage, Instigator, HitLocation, Momentum, DamageType );

			if( !StrafeFromDamage( Damage, DamageType, true ) )
			{
				if( bWasOnGround && MoveTarget == ControllerEnemy && Pawn.Physics == PHYS_Falling ) 
				{
					// weave
					Pick = 1.0;
					if( bStrafeDir )
						Pick = -1.0;
					SideDir = Normal( (ControllerEnemy.Location - Pawn.Location) cross vect(0,0,1) );
					SideDir.Z = 0;
					Pawn.Velocity += Pick * Pawn.GroundSpeed * 0.7 * SideDir;   
					if( FRand() < 0.2 )
						bStrafeDir = !bStrafeDir;
				}
			}
		}
	}

	//-------------------------------------------------------------------------

	function eventEnemyNotVisible()
	{
		#debug DMAI( "EnemyNotVisible -- going to attack hunt" );
		//GS( AttackHuntState ); 
		#debug   BehaviorController.Update( BC_EnemyNotVisible, GetContext() );
		#release BehaviorController.Update( BC_EnemyNotVisible );
	}

	/*-------------------------------------------------------------------------
	NOTE: Actor/PointReachable return false if target is more than MAXPATHDIST
	units away (assumes that pathing will be used).
	
	I added bKamikazeClose to override this but we'll probably eventually want
	to be able to pass the max distance to use to Actor/PointReachable so that
	we can have "smart" charging from far away without needing to use paths

	Also note that when smart closing (use paths if > 1200 units away) is used
	then this has 2 side effects:

	1) If there are no paths then the NPC can't move (will turn into a turret 
	   if he has a ranged attack until the enemy becomes reachable).

	2) If there are paths, the NPC may appear to "weave" as he closes in 
	   as he moves towards pathnodes while looking at his enemy.
	*/

	function bool CloseRequiresPathing()
	{
		//DMTNS( "CloseRequiresPathing ActorReachable (" $ U2PBasic.AttackClosingReachableDistSquared $ "): " $ ActorReachable( ControllerEnemy, U2PBasic.AttackClosingReachableDistSquared ) );
		return ( !U2PBasic.bKamikazeClosing && !ActorReachable( ControllerEnemy, U2PBasic.AttackClosingReachableDistSquared ) );
	}

	//-------------------------------------------------------------------------

	function bool GetPredictedCloseLocation( out vector PredictedLocation )
	{
		//DMTNS( "calling GetBestPredictedLocation" );
		class'UtilGame'.static.GetBestPredictedLocation( Pawn, ControllerEnemy, Pawn.GroundSpeed, 0.0, PredictedLocation );
		
		//DMTNS( "called GetBestPredictedLocation" );
			
		// use a location that is a small distance along the vector to the 
		// predicted location so call to MoveToPoint won't take long (this would
		// reduce the frequency with which the destination is updated).
		
		//AddCylinder( PredictedLocation, 4, 4, ColorCyan() );
		
		PredictedLocation = Pawn.Location + Pawn.CollisionRadius * 8.0 * Normal( PredictedLocation - Pawn.Location );
		
		//AddCylinder( PredictedLocation, 4, 4, ColorOrange() );
		//Level.bPlayersOnly = !Level.bPlayersOnly;
		
		return true;
	}

	//-------------------------------------------------------------------------

	function EDestinationResult SetChargeDestination()
	{
		local Actor CurrentEnemy;
		local float DeltaZ;
		local vector PredictedLocation;
		
		CurrentEnemy = ControllerEnemy;

		// check for enemy directly above us (without this check its possible for an
		// NPC/player to "surf" on top of the other one since the lower one will 
		// always try to move in the same direction instantly
		if( VSize2D(CurrentEnemy.Location - Pawn.Location) <= (CurrentEnemy.CollisionRadius + Pawn.CollisionRadius) )
		{
			DeltaZ = CurrentEnemy.Location.Z - Pawn.Location.Z;
			if( DeltaZ > 0 && DeltaZ < 256.0 )
				return DR_Wait;
		}			
		
		if( !U2PBasic.bPredictChargeLocation )
			return DR_Raw;

		if( VSize(CurrentEnemy.Location - Pawn.Location) <= 3*Pawn.MeleeRange )
			return DR_Raw;

		if( !GetPredictedCloseLocation( PredictedLocation ) )
			return DR_Raw;

		if( !U2PBasic.bKamikazeClosing && !PointReachable( PredictedLocation ) )
			return DR_Raw;

		Destination = PredictedLocation;
		
		return DR_Predicted;
	}

	//-------------------------------------------------------------------------
	//2002.12.17 (mdf) hack to fix izarians not closing.

	function bool FindAlternativeClosePath( Actor Focus )
	{
		local float TargetDistance, NPDistance;
		local TDistanceInfo NPList[ MaxDistanceActors ];
		local int ii;
		
		//DMTNS( "FindAlternativeClosePath  Focus: " $ Focus );
	
		// only applies to levels with XMP items:
		if( Level.HasSpecialColliders() )
		{
			TargetDistance = VSize( Focus.Location - Pawn.Location );
			
			// only applies to NPCs with modified attack ranges
			if( !CheckMaxAttackRanges( TargetDistance, Focus ) ||
				(TargetDistance > 512.0 && (Pawn.IsA( 'U2SkaarjLight' ) || Pawn.IsA( 'U2SkaarjMedium' ) || Pawn.IsA( 'U2SkaarjHeavy' ))) )
			{
				//DMTNS( "looking for alternative paths" );
				// look for a pathnode which is at most 1200 units away
				// and closer to the enemy than the NPC's current location
				GetNearbyPathNodesRelativeTo( Pawn, Focus, NPList, 50.0, 2400.0, false );
				
				for( ii=0; ii<ArrayCount(NPList); ii++ )
				{
					if( NPList[ ii ].TargetActor == None )
						break;
				
					NPDistance = VSize( Focus.Location - NPList[ ii ].TargetActor.Location );
					
					if( NPDistance < TargetDistance )
					{	
						//DMTNS( "checking: " $ NPList[ ii ].TargetActor );
						//AddCylinder( NPList[ ii ].TargetActor.Location, 16, 16, ColorYellow() );
						if( FindBestPathToward( NPList[ ii ].TargetActor, true ) )
						{
							MoveTarget = NPList[ ii ].TargetActor;
							Destination = MoveTarget.Location;
							//AddActor( MoveTarget, ColorPink() );
							//DMTNS( "found alternate path: " $ MoveTarget );
							return true;
						}
					}
				}
			}
		}
		
		return false;
	}

	//-------------------------------------------------------------------------

	function bool FaceTarget( float F )
	{
		if( !Pawn.bCanStrafe )
			return false;
			
		if( U2PBasic.CloseFaceTarget == 1 )
			return true;

		if( U2PBasic.CloseFaceTarget == -1 )
			return false;
			
		if( (VSize( MoveTarget.Location - Pawn.Location ) < 2.5 * Pawn.CollisionRadius) )
			return true;
			
		return Global.FaceTarget( F );
	}
	
	//-------------------------------------------------------------------------

	function ETacticalMoveType GetTacticalMoveType()
	{
		//!!mdf-tbd:
		//if( GetSkill() >= 0.5 && IsPreparedToFire( true ) && FRand() < 0.75 )
		//if( IsPreparedToFire( true ) && FRand() < 0.75 )
		//!!mdf-tbd: why do we care whether the NPC can fire or not? If there really are cases, add a 
		// new bool to control this?
		if( FDecision( U2PBasic.TacticalMoveCloseOdds ) )
		//if( (!U2PBasic.bHasRangedAttack || IsPreparedToFire( true )) && FDecision( U2PBasic.TacticalMoveCloseOdds ) )
			return Pawn.TacticalMoveType;
		else
			return TMT_None;
	}

	//-------------------------------------------------------------------------

	function TryToCloseDodge( bool bLeft )
	{
		local vector DodgeDir;

		//DMTNS( "TryToCloseDodge" );
		DodgeDir = Normal( (ControllerEnemy.Location - Pawn.Location) cross vect(0,0,1) );

		if( bLeft )
			TryToDodge( -DodgeDir, true );
		else
			TryToDodge( DodgeDir, false );
	}

	//-------------------------------------------------------------------------
	
	event BeginState()
	{
		Super.BeginState();
		
		if( U2PBasic.AttackClosingCanFireOdds <= 0.0 )
		{
			#debug   StopFiring( 9999999.9, SFI_Behavior, GetContext() ); // kill off firing timer for the duration of the state
			#release StopFiring( 9999999.9, SFI_Behavior ); // kill off firing timer for the duration of the state
		}
		if( StationaryPawn(ControllerEnemy) != None )
			Enable( Event_SeeEnemy );
		else
			Disable( Event_SeeEnemy );
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		if( Pawn != None )
			Pawn.bCanJump = (Pawn.JumpZ > 0);
			
		if( U2PBasic != None && U2PBasic.AttackClosingCanFireOdds <= 0.0 )
		{
			#debug   StopFiring( 0.2, SFI_Behavior, GetContext() ); // restore firing timer
			#release StopFiring( 0.2, SFI_Behavior ); // restore firing timer
		}
	}

	//-------------------------------------------------------------------------

@ BeginLabel:
	#debug DMAIL( BeginLabel );

@ MovePickDestLabel:
@ CloseLabel:
	if( !ValidEnemy( ControllerEnemy ) )
	{
		#debug   BehaviorController.Update( BC_EnemyInvalid, GetContext() );
		#release BehaviorController.Update( BC_EnemyInvalid );
	}
	
	#debug DMAI( "CloseLabel Enemy = " $ ControllerEnemy );

	if( ControllerEnemy.PhysicsVolume.bWaterVolume )
	{
		if( !Pawn.bCanSwim )
		{
			//DMTNS( "enemy in a water volume and I can't swim: BC_EnemyCantReach" );
			//GS( AttackTacticalMoveState, DontCloseLabel );
			#debug   BehaviorController.Update( BC_EnemyCantReach, GetContext() );
			#release BehaviorController.Update( BC_EnemyCantReach );
		}
	}
	else if( !Pawn.bCanFly && !Pawn.bCanWalk )
	{
		//DMTNS( "enemy not in a water volume and I can't fly or walk: BC_EnemyCantReach" );
		//GS( AttackTacticalMoveState, DontCloseLabel );
		#debug   BehaviorController.Update( BC_EnemyCantReach, GetContext() );
		#release BehaviorController.Update( BC_EnemyCantReach );
	}

	Focus = ControllerEnemy;
	Destination = Focus.Location;
	WaitForLanding();

	if( CloseRequiresPathing() )
	{
		//DMTNS( "closing using path to enemy at: " $ VSize( Focus.Location - Pawn.Location ) );
		
@ CantReachLabel:
		#debug DMAIL( CantReachLabel );
		//!!mdf-tbd: shouldn't do this -- might still be facing enemy? 
		//if( !FindBestPathToward( Focus, true ) )
		if( !FindBestPathToward( Focus, true ) && !FindAlternativeClosePath( Focus ) )
		{
			#debug DMAIM( "can't close (no path or not mobile): BC_EnemyCantReach" );
			Sleep( 0.0 ); // prevents state recursion in some cases
			#debug   BehaviorController.Update( BC_EnemyCantReach, GetContext() );
			#release BehaviorController.Update( BC_EnemyCantReach );
		}
		else
		{
			#debug DMAIM( "moving toward " $ MoveTarget );

			if( FaceTarget( 1.5 ) )
			{
				//DMTNS( "  while facing enemy" );
				MoveToActor( MoveTarget, GetTacticalMoveType(), , , Focus, GetMoveSpeed() );
			}
			else
			{
				//DMTNS( "  while facing navigation point" );
				MoveToActor( MoveTarget, GetTacticalMoveType(), , , , GetMoveSpeed() );
			}
		}
	}
	else
	{
		//DMTNS( "closing using destination=enemy or predicted location" );
		
		DestinationResult = SetChargeDestination();
		if( DestinationResult == DR_Wait )
		{
			Goto( PauseLabel );
		}
		else 
		{
			// only use predicted location (MoveToPoint) if it isn't near the enemy
			if( DestinationResult == DR_Predicted )
			{
				//DMTNS( "  using target's predicted location  face location: " $ U2PBasic.bFacePredictedLocation );
				//AddArrow( Pawn.Location, Destination, ColorOrange() );
				//!!mdf-tbd: can't currently use tactical moves while moving to a point destination
				if( U2PBasic.bFacePredictedLocation )
					MoveToPoint( Destination, , , GetMoveSpeed() );
				else
					MoveToPoint( Destination, , Focus, GetMoveSpeed() );
			}
			else
			{
				//DMTNS( "  using target's current location" );
				//NOTE: will use TMT_Basic instead of TMT_Serpentine if Pawn.bResortToBasicTacticalMoves=true
				MoveToActor( Focus, GetTacticalMoveType(), , , , GetMoveSpeed() );
			}
				
			if( FDecision( U2PBasic.RandomCloseDodgeOdds ) )
				TryToCloseDodge( bTacticalDir );
		}
	}

	// stay in this state until BC decides otherwise (or something changes) 
	Goto( CloseLabel );

@ TurnLabel:
	#debug DMAIM( TurnLabel );
	StopMovement( true, true );
	Focus = ControllerEnemy;
	FinishRotation( DefaultRotationThreshold );
	Goto( CloseLabel );
	Stop;

// collapse with DelayLabel in charging?
@ PauseLabel:
	#debug DMAIM( PauseLabel );
	//StopMovement( true, false );
	Focus = ControllerEnemy;
	FinishRotation( DefaultRotationThreshold );
	Sleep( 0.5 );
	Goto( CloseLabel );

// mdf: handle strafe move here rather than jumping to attacktactical state for this as was done before
@ MoveActiveStrafeLabel:
	//DMTNS( "StrafeMove!" );
	MoveToPoint( Destination, , ControllerEnemy );
	Goto( CloseLabel );
} // AttackCloseState

/*-----------------------------------------------------------------------------
Used by creatures like the mukhogg and rammer to charge directly at their enemy
and damage them if they are bumped by the "head" of the creature. If the target
is missed, creature will overshoot somewhat (due to momentum) before turning
around to charge at their enemy again. Also, while charging, the creature's
ability to correct its direction is somewhat limited.

NOTE: 
*/

state @ AttackCloseChargeState extends @ AttackCloseState
{
    ignores SeeFriend, SeeOther, SeeAlertFriend, HearNoise;

	//-------------------------------------------------------------------------

	function ETacticalMoveType GetTacticalMoveType()
	{
		return TMT_None;
	}
	
	//-------------------------------------------------------------------------

	function HandleBump( Pawn Other, bool bEnemy )
	{
		local float EnemyToHeadDistance, Threshold;
		local float SpeedRatio;
		local float Damage;
		local vector MomentumVector;

		// no damage unless Other is within range of head?
		EnemyToHeadDistance = VSize( Other.Location - (Pawn.Location + Pawn.CollisionRadius*vector(Pawn.Rotation)) );
		Threshold = (Other.CollisionRadius + U2PBasic.ChargeHeadSize);
		//DMTNS( "HandleBump: " $ Other $ " bEnemy: " $ bEnemy $ " Distance: " $ EnemyToHeadDistance $ " Threshold: " $ Threshold );
		
		if( EnemyToHeadDistance < Threshold )
		{
			// launch other, momentum transfer based on speed?
			SpeedRatio = VSize( Pawn.Velocity ) / Pawn.GroundSpeed;

			if( !bEnemy )
				SpeedRatio *= 0.25;

			MomentumVector = Normal( Other.Location - Pawn.Location );
			MomentumVector.Z = 1;
			MomentumVector *= U2PBasic.ChargeMaxMomentumTransfer * SpeedRatio * 100.0/Other.Mass;

			Damage = FMax( U2PBasic.ChargeMinDamage, U2PBasic.ChargeMaxDamage * SpeedRatio);
			//DMTNS( "Damage: " $ Damage );

			Other.TakeDamage( Damage, Pawn, Other.Location, MomentumVector, class'DamageTypePhysical' );
			//AddArrow( Other.Location, Other.Location + MomentumVector, ColorRed() );
	
			// tbd: special animation and/or state?
			if( bEnemy && ValidEnemy( ControllerEnemy ) )
			{
				Disable( Event_NotifyBump );
				#debug   UpdateBehavior( true, GetContext() );
				#release UpdateBehavior( true );
				//GotoLabel( DelayLabel ); // enemy still alive, pause a bit
			}
		}
	}

	//-------------------------------------------------------------------------

	function eventBumpEnemy( Pawn Other )
	{
		// launch enemy, momentum transfer based on speed
		Super.eventBumpEnemy( Other );

		HandleBump( Other, true );
	}

	//-------------------------------------------------------------------------

	// !!mdf-tbd:
	function eventBumpFriend( Pawn Other )
	{
		//DMTNS( "BUMP friend: " $ Other );

		Super.eventBumpFriend( Other );

		// tbd: don't bump same class?
		if( !ClassIsChildOf( Pawn.Class, Other.Class ) )
			HandleBump( Other, false );
	}

	//-------------------------------------------------------------------------
		
	function bool GetPredictedCloseLocation( out vector PredictedLocation )
	{
		local vector PredictedDirection, RotationDirection;
		local vector PredictedNormal, RotationNormal;
		local vector PredictedOffset, RotationOffset;
		local vector TargetLocation;
		local float TargetDistance, CosTargetAngle;
		local float ChangeSize;
		local bool bResult;
		
		TargetDistance = class'Util'.static.GetDistanceBetweenActors( Pawn, ControllerEnemy );
		if( TargetDistance < 2*Pawn.CollisionRadius )
		{
			PredictedLocation = ControllerEnemy.Location;
		}
		else
		{ 
			if( !Super.GetPredictedCloseLocation( PredictedLocation ) )
				return false;
		}

		// constrain result based on speed (limit change)

		// must be a better way? but for now just select a destination somewhere
		// on the vector between endpoint of unit vector alingned with Pawn's 
		// rotation and endpoint of unit vector corresponding to predicted
		// location then extrapolate that out.

		//!!mdf-tbd: better way is to use RotateAngleAxis?
		
		// mdf-tbd: eliminate Z component?
		PredictedDirection = PredictedLocation - Pawn.Location;
		PredictedDirection.Z = 0;
		RotationDirection = vector( Pawn.Rotation );
		RotationDirection.Z = 0;
		
		// mdf-tbd: handle pathological cases (are there any?)
		PredictedNormal = Normal( PredictedDirection );
		RotationNormal  = Normal( RotationDirection );
		CosTargetAngle = PredictedNormal dot RotationNormal;

		//AddArrow( Pawn.Location, PredictedLocation, ColorCyan() );
		//if( (CosTargetAngle < 0.707) && TargetDistance > 512.0 ) -- stops all the time
		if( (CosTargetAngle < 0.0) && (TargetDistance > 512.0 || VSize( Pawn.Velocity) < 0.1*Pawn.GroundSpeed) )
		{
			#debug DMAIM( "angle too great -- turning!" );
			GotoLabel( TurnLabel );
		}
		else if( TargetDistance < Pawn.CollisionRadius && CosTargetAngle > 0.866 )
		{
			bResult = true;
		}
		else
		{
			//PredictedOffset = Pawn.Location + PredictedNormal;
			//RotationOffset = Pawn.Location + RotationNormal;
	
			// tbr: extend out so more visible for debugging -- shouldn't be needed though
			PredictedOffset = Pawn.Location + 512.0*PredictedNormal;
			RotationOffset = Pawn.Location + 512.0*RotationNormal;
	
			//AddArrow( Pawn.Location, Pawn.Location + 2048.0*PredictedNormal, ColorRed() );
			//AddArrow( Pawn.Location, Pawn.Location + 2048.0*RotationNormal,  ColorGreen() );
	
			//DMTNS( "Location: "		   $ Pawn.Location );
			//DMTNS( "PredictedOffset: " $ PredictedOffset );
			//DMTNS( "RotationOffset:  " $ RotationOffset );
			//DMTNS( "PredictedNormal: " $ PredictedNormal );
			//DMTNS( "RotationNormal:  " $ RotationNormal );
	
			//#debug AddLine( PredictedOffset, RotationOffset, ColorBlue() );
	
			// note: again, I'm sure there is a better way to do this but at this point
			// we have a "line" with endpoints 2048.0 units away from the Pawn which
			// represents the desired change in direction. If this is more than some
			// amount (should really be an angle) then scale it back based on the
			// Pawn's Velocity / GroundSpeed ratio allowing a 256 "unit" change even
			// if at max Velocity.
			ChangeSize = VSize(PredictedOffset - RotationOffset);
			if( ChangeSize > U2PBasic.ChargeMaxChangeSize )
			{
				// scale distance from ChangeSize down to MaxChangeSize depending on velocity
				ChangeSize = U2PBasic.ChargeMaxChangeSize + (1.0 - (VSize( Pawn.Velocity ) / Pawn.GroundSpeed)) * (ChangeSize-U2PBasic.ChargeMaxChangeSize);
				TargetLocation = RotationOffset + U2PBasic.ChargeMaxChangeSize*Normal( PredictedOffset - RotationOffset);
			}
			else
			{
				TargetLocation = PredictedOffset;
			}
	
			//DMTNS( "TargetLocation: " $ TargetLocation );
	
			// keep distances short so MoveToPoint doesn't get tied up for too long
			PredictedLocation = Pawn.Location + 128.0*Normal( TargetLocation - Pawn.Location);
	
			//AddArrow( Pawn.Location, PredictedLocation, ColorMagenta() );
	
			//PredictedLocation.Z = 0; should be Pawn Location.Z by now?
	
			//DMTNS( "PredictedLocation: " $ PredictedLocation );
			bResult	= true;
		}

		return bResult;
	}

	//-------------------------------------------------------------------------

@ DelayLabel:
	StopMovement( true, true );
	Focus = ControllerEnemy;
	FinishRotation( DefaultRotationThreshold );
	Sleep( 1.0 );
	Enable( Event_NotifyBump );
	Goto( CloseLabel );
} // AttackCloseChargeState

//-----------------------------------------------------------------------------
// Head towards a special goal or orders destination while dealing with an
// enemy.
//
// NOTE (mdf) UT bot code has ignore EnemyNotVisible here even though there
// was an EnemyNotVisible handler (so it was never getting called). This was
// either an oversight or maybe it was done intentionally because of either
// performance issues or maybe the NPC was cycling between 2 enemies in an
// undesirable way?

state @ AttackFallbackState extends @ MoveToGoalWithEnemyState
{
	//-------------------------------------------------------------------------

	event MayFall()
	{
		Pawn.bCanJump = TestCanJump();
	}

	//-------------------------------------------------------------------------

	function eventEnemyNotVisible()
	{
		local Pawn TempPawn;

		// current enemy no longer visible
		if( OldControllerEnemy != None && LineOfSightTo( OldControllerEnemy ) )
		{
			// old enemy visible - swap with current enemy
			TempPawn = OldControllerEnemy;
			OldControllerEnemy = ControllerEnemy;
			#debug   SetControllerEnemy( TempPawn, GetContext() );
			#release SetControllerEnemy( TempPawn );
		}
		else 
		{
			// no visible enemy
			if( !ControllerEnemy.IsMobile() )
			{
				// enemy can't move -- clear enemy and maybe pick up OldControllerEnemy (although not visible
				// current enemy (no longer visible) and can't move so worry about OldControllerEnemy (if set) instead
				#debug   SetControllerEnemy( None, GetContext() );
				#release SetControllerEnemy( None );
				UpdateEnemy();
			}
		}
	}

	//-------------------------------------------------------------------------

	function eventSeeEnemy( Pawn Seen )
	{
		if( Seen != ControllerEnemy && MaybeSetEnemy( Seen ) )
			Pawn.MakeNoise( 1.0 );
	}

	//-------------------------------------------------------------------------

	singular function eventHearNoiseThreat( float Loudness, Actor NoiseMaker )
	{
		if( NoiseMaker.Instigator != ControllerEnemy && !LineOfSightTo( ControllerEnemy ) )
		{
			#debug DMAI( "eventHearNoiseThreat -- calling MaybeSetEnemy" );
			if( MaybeSetEnemy( NoiseMaker.Instigator ) )
			{
				HandleEnemyNoise( NoiseMaker );
				Pawn.MakeNoise( 1.0 );
			}
		}
	}

	//-------------------------------------------------------------------------

	function bool FaceTarget( float F )
	{
		return Pawn.bCanStrafe; // always face target when using fallback?
	}

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest ) { return ( U2PBasic.bHasMovingRangedAttack && Global.CanFire( bTest ) ); }

	//-------------------------------------------------------------------------

	function ETacticalMoveType GetTacticalMoveType()
	{
		if( FDecision( U2PBasic.TacticalMoveFallbackOdds ) && GetTimeSinceEnemyLastSeen() < 1.0 )
			return Pawn.TacticalMoveType;
		else
			return TMT_None;
	}

	//-------------------------------------------------------------------------

	function bool OverrideSpecialAttraction()
	{
		return false;
	}

	//-------------------------------------------------------------------------

	function bool ShouldClearSpecialColliders()
	{
		return true; // so can fall back to special destination
	}

	//-------------------------------------------------------------------------

	function bool HasReachedOrdersObject()
	{
		return AtDestinationActor( OrdersObject, OrdersThreshold );

		/* old
		local float Distance;
		
		if( Pawn.Physics == PHYS_Walking )
			Distance = VSize2D( Pawn.Location - OrdersObject.Location );
		else	
			Distance = VSize( Pawn.Location - OrdersObject.Location );
		
		return ( Distance <= OrdersThreshold );
		*/
				
		/*!!mdf-tbd: used to be -- we don't currently have any cases afaik where we want an
		  NPC to stop short of the order object if its within sight if we do add cases like
		  this then we should have a way of determining when to use it.
		return( VSize( Pawn.Location - OrdersObject.Location ) < 20 || 
		       (VSize( Pawn.Location - OrdersObject.Location ) < 600 && LineOfSightTo( OrdersObject )) );
		*/
	}

	//-------------------------------------------------------------------------

	function HandleReachedOrdersObject()
	{
		//DMTNS( "got to OrdersObject: " $ OrdersObject );
		if( StationaryPawn(ControllerEnemy) != None || (GetTimeSinceEnemyLastSeen() > 5 && Orders == OrdersHold) )
		{
			#debug   SetControllerEnemy( OldControllerEnemy, GetContext() );
			#release SetControllerEnemy( OldControllerEnemy );
			OldControllerEnemy = None;
		}
		#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
		#release BehaviorController.Update( BC_AttackUpdate );
	}

	//-------------------------------------------------------------------------

	function PickDestination()
	{
		local Actor PreviousMoveTarget;

		if( GetTimeSinceEnemyLastDetected() > MaxFallbackNoDetectTime )
		{
			#debug   SetControllerEnemy( None, GetContext() );
			#release SetControllerEnemy( None );
		}
		
		if( !ValidEnemy( ControllerEnemy ) )
		{
			UpdateEnemy();
		}
		else
		{
			PreviousMoveTarget = MoveTarget;
		
			LastSpecialDestinationCheck = Level.TimeSeconds - 0.1;
	
			if( FindSpecialAttraction() )
			{
				if( !OverrideSpecialAttraction() )
				{
		   			if( MoveTarget == None )
		   			{
		   				#debug DMAI( " no destination in fallback!" );
		   				Orders = OrdersNone;
						#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
						#release BehaviorController.Update( BC_AttackUpdate );
					}
				}
			}
			else if( Orders == OrdersAttack || OrdersObject == None )
			{
				#debug DMAI( " attack fallback turned to freelance" );
				Orders = OrdersNone;
				#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
				#release BehaviorController.Update( BC_AttackUpdate );
			}
			else if( HasReachedOrdersObject() )
			{
				HandleReachedOrdersObject();
			}
			else
			{
				GetPathToActor( OrdersObject, MoveTarget, true );
				if( MoveTarget == None )
				{
					#debug DMAI( "fallback turned to freelance (no Path to " $ OrdersObject $ " )" );
					Orders = OrdersNone;
					#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
					#release BehaviorController.Update( BC_AttackUpdate );
				}
			}
		}
		
		if( MoveTarget != PreviousMoveTarget )
			NumMoveAttempts = 0;
	}

	//-------------------------------------------------------------------------

	function eventBumpEnemy( Pawn Other )
	{
		#debug DMAI( "eventBumpEnemy -- calling MaybeSetEnemy" );
		MaybeSetEnemy( Other );
	}

	//-------------------------------------------------------------------------

	function Actor GetFinalDestinationActor()
	{
		return None;
	}

	//-------------------------------------------------------------------------

	function float GetReachedDestinationDistance()
	{
		if( Orders != OrdersNone )
			return OrdersThreshold;
		else
			return -1.0; // use usual distance reached tests
	}

	//-------------------------------------------------------------------------

@ BeginLabel:
@ MovePickDestLabel:
	WaitForLanding();
	
	PickDestination();

@ MoveActiveLabel:
	if( MoveTarget == None )
		Goto( MoveNoDestLabel );

	//DMTNS( "MoveToActor  BEGIN  MoveTarget: " $ MoveTarget $ " TMT: " $ GetTacticalMoveType() $ " (final dest:" $ GetFinalDestinationActor() $ " Distance: " $ GetReachedDestinationDistance() $ " MoveSpeed:" $ GetMoveSpeed() $ ")" );
	if( FaceTarget( 1 ) )
	{
		//DMTNS( "  facing target" );
		MoveToActor( MoveTarget, GetTacticalMoveType(), GetFinalDestinationActor(), GetReachedDestinationDistance(), ControllerEnemy, GetMoveSpeed() );
	}
	else
	{
		//DMTNS( "  not facing target" );
		MoveToActor( MoveTarget, GetTacticalMoveType(), GetFinalDestinationActor(), GetReachedDestinationDistance(), , GetMoveSpeed() );
	}
	
	//DMTNS( "MoveToActor END returned MoveResult: " $ EnumStr( enum'EMoveResult', MoveResult ) );
	
	if( ++NumMoveAttempts > 8 )
	{
		//DMTNS( "ran out of move attempts" );
		#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() ); // try something else?
		#release BehaviorController.Update( BC_AttackUpdate ); // try something else?
	}	
	Goto( MovePickDestLabel );

@ MoveSpecialLabel:
	if( MoveTarget == None )
		MoveToPoint( Destination );
	else
		MoveToActor( MoveTarget, GetTacticalMoveType() ); 
	Goto( MovePickDestLabel ); // what if didn't get to special destination?

@ MoveNoDestLabel:
	#debug DMAIA( "AttackFallback.MoveNoDestLabel" );
	Focus = GetTarget();
	FinishRotation( DefaultRotationThreshold ); // try again in a bit
	Goto( MovePickDestLabel );
} // AttackFallbackState

//-----------------------------------------------------------------------------
// Similar to fallback basically except the destination will be a location from
// which the enemy won't have LOS to the NPC.

//2003.01.07 fix for "function not found problem" TTP #4616
function HandleRecoveredEnemy();

state @ AttackHuntState
{
	ignores EnemyNotVisible; 

	//-------------------------------------------------------------------------

	event MayFall()
	{
		Pawn.bCanJump = ( TestCanJump() || PointReachable( Destination ) );
	}

	//-------------------------------------------------------------------------

	function bool FaceTarget( float F )
	{
		// in general, never face face target when hunting -- shouldn't know where
		// it is, although PickDestination does "cheat" by using ControllerEnemy.Location.
		return false;
	}

	//-------------------------------------------------------------------------

	function bool IsFacingTarget( Actor Target, float CosMinFacingAngle )
	{
		return ( (Level.TimeSeconds - TimeSinceBeginState) < U2PBasic.MaxHuntFireAtLastSeenTime ); // so NPC can fire at last seen pos if facing it (AdjustAim will check this)?
	}

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest ) { return ( U2PBasic.bHasMovingRangedAttack && Global.CanFire( bTest ) ); }

	//-------------------------------------------------------------------------
	
	function HandleRecoveredEnemy()
	{
		// We're jumping to state code to shift and rotate the NPC and we
		// don't want to be spammed with SeeEnemy calls & keep ending up 
		// here. Senses will be re-enabled when we exit the state.
		DisableSenses();

		// And make sure shift + rotate isn't interrupted (or NPC won't be 
		// in a position to fire, possibly causing next state to bail).
		BehaviorController.SetMinTimeOutDelay( 1.0 );

		// !!mdf-tbd: actually getting cool behavior without this -- NPC runs 
		// across gap while firing at target and seemingly heading for cover.
		// This wouldn't be too hard to re-enable this "properly" -- just have 
		// some odds here of
		//  a) checking whether there is cover close by in the direction
		//     that the NPC is headed in
		//	b) if so, invalidate previous cover location (if any)
		//	c) put NPC into MoveToCover state with this destination
		StopMovement( true, false );
				
		if( LineOfSightTo( ControllerEnemy ) )
		{
			NumMoveAttempts	= 0;
			GotoLabel( AdjustPositionLabel );
		}
		else
		{
			GotoLabel( AdjustRotationLabel );
		}
	}
	
	//-------------------------------------------------------------------------
	
	function eventBumpEnemy( Pawn Other )
	{
		// NOTE: bump --> reevaluate attack situation
		#debug DMAI( "eventBumpEnemy -- calling MaybeSetEnemy" );
		MaybeSetEnemy( Other );
	}

	//-------------------------------------------------------------------------

	function bool ReduceThreat()
	{
		return true;
	}

	//-------------------------------------------------------------------------

	function FearThisSpot( Actor aSpot )
	{
		Destination = Pawn.Location + 120 * Normal( Normal( Destination - Pawn.Location ) + Normal( Pawn.Location - aSpot.Location ) ); 
		MoveTarget = None;
		GotoLabel( MoveSpecialLabel );
	}

	//-------------------------------------------------------------------------

	function eventTookDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		if( Pawn.Health > 0 )
		{
			bFrustrated = true;
			Global.eventTookDamage( Damage, Instigator, HitLocation, Momentum, DamageType );
		}
	}

	//-------------------------------------------------------------------------

	singular function eventHearNoiseThreat( float Loudness, Actor NoiseMaker )
	{
		#debug DMAI( "eventHearNoiseThreat -- calling MaybeSetEnemy" );
		MaybeSetEnemy( NoiseMaker.Instigator );
	}

	//-------------------------------------------------------------------------

	function EnemyAcquired(); // go through HandleRecoveredEnemy (via MaybeSetEnemy)
	
	//-------------------------------------------------------------------------

	function bool MaybeSetEnemy( Pawn NewEnemy, optional bool bAlertingOthers )
	{
		local bool bResult;

		bResult = Global.MaybeSetEnemy( NewEnemy, bAlertingOthers );

		if( bResult )
		{
			BlockedPath = None;
			Focus = ControllerEnemy;
			HandleRecoveredEnemy();
		}

		return bResult;
	} 

	//-------------------------------------------------------------------------

	function bool FindViewSpot()
	{
		local vector X, Y, Z;
		local bool bAlwaysTry, bResult;

		GetAxes( Rotation, X, Y, Z );

		// try left and right
		// if frustrated, always move if possible
		bAlwaysTry = bFrustrated;
		bFrustrated = false;

		if( Pawn.FastTrace( ControllerEnemy.Location, Pawn.Location + 2 * Y * Pawn.CollisionRadius ) )
		{
			Destination = Pawn.Location + 2.5 * Y * Pawn.CollisionRadius;
			bResult = true;
		}
		else if( Pawn.FastTrace( ControllerEnemy.Location, Pawn.Location - 2 * Y * Pawn.CollisionRadius ) )
		{
			Destination = Pawn.Location - 2.5 * Y * Pawn.CollisionRadius;
			bResult = true;
		}
		else if( bAlwaysTry )
		{
			if( FRand() < 0.5 )
				Destination = Pawn.Location - 2.5 * Y * Pawn.CollisionRadius;
			else
				Destination = Pawn.Location - 2.5 * Y * Pawn.CollisionRadius;
			bResult = true;
		}

		return bResult;
	}

	//-------------------------------------------------------------------------

	function MaybeClearHuntingEnemy()
	{
		// If no enemy, or I should see him but don't, then give up		
		if( GetTimeSinceEnemyLastDetected() > MaxHuntTime )
		{
			if( ControllerEnemy != None )
				U2P.AssetsHelperClass.static.HandleLostEnemy( U2P );

			#debug DMAI( "MaybeClearHuntingEnemy clearing enemy" );
			#debug   SetControllerEnemy( None, GetContext() );
			#release SetControllerEnemy( None );
		}
	}

	//-------------------------------------------------------------------------

	function bool SpecialHuntDestination()
	{
		return false;
	}

	//-------------------------------------------------------------------------

	function PickDestination()
	{
		local NavigationPoint Path;
		local Actor HitActor;
		local vector HitNormal, HitLocation, NextSpot, ViewSpot;
		local float posZ;
		local bool bCanSeeLastSeen;
		local int i;

		MaybeClearHuntingEnemy();

		if( !ValidEnemy( ControllerEnemy ) )
		{
			UpdateEnemy();
			return;
		}

		Pawn.bAvoidLedges = false;
		Pawn.bCanJump = (Pawn.JumpZ > 0);

		if( ActorReachable( ControllerEnemy ) )
		{
			//DMTNS( "hunt using enemy reachable" );
			BlockedPath = None;
			if( (NumMoveAttempts < 8 + 8*GetSkill()) || 
				(GetTimeSinceEnemyLastDetected() < 15) || 
				((Normal( ControllerEnemy.Location - Pawn.Location ) dot vector(Pawn.Rotation)) > -0.5) )
			{
				Destination = ControllerEnemy.Location;
				MoveTarget = None;
				NumMoveAttempts++;
			}
			else
			{
				// giving up
				//2002.12.07 mdf-tbd: need to invalidate enemy if giving up?
				UpdateEnemy();
			}
			return;
		}

		if( SpecialHuntDestination() )
		{
			//DMTNS( "hunt using special hunt destination" );
			return;
		}
		
		NumMoveAttempts++;

		ViewSpot = Pawn.Location + Pawn.BaseEyeHeight * vect(0,0,1);
		bCanSeeLastSeen = Pawn.FastTrace( GetLastEnemySeenLocation( ), ViewSpot );
		
		//DMTNS( "bCanSeeLastSeen: " $ bCanSeeLastSeen );

		if( bCanSeeLastSeen )
			bHunting = !Pawn.FastTrace( GetLastEnemySeenLocation(), ControllerEnemy.Location );
		else
			bHunting = true;

		if( bDeviousHunting )
		{
			if( BlockedPath == None )
			{
				// block the first Path visible to the enemy
				if( GetPathToActor( ControllerEnemy, , false ) != PR_None )
				{
					for ( i=0; i<16; i++ )
					{
						if( NavigationPoint( RouteCache[i] ) == None )
							break;
						else if( ControllerEnemy.Controller.LineOfSightTo( RouteCache[i] ) )
						{
							BlockedPath = NavigationPoint( RouteCache[i] );
							break;
						}
					}
				}
				else if( CanStakeOut() )
				{
					//DMTNS( "stakeout" );
					UpdateEnemy();
					return;
				}
				else
				{
					//DMTNS( "update" );
					//2002.12.07 mdf-tbd: need to invalidate enemy if giving up?
					UpdateEnemy();
					return;
				}
			}
			// control Path weights
			ClearPaths();
			if( BlockedPath != None )
				BlockedPath.Cost = 1500;
			if( FindBestPathToward( ControllerEnemy, false ) )
			{
				//DMTNS( "using devious path" );
				return;
			}
		}
		else if( FindBestPathToward( ControllerEnemy, true ) )
		{
			//DMTNS( "using path to enemy" );
			return;
		}
		
		//DMTNS( "HERE?" );
		
		MoveTarget = None;
		
		if( NumMoveAttempts > 60 && ShouldGiveUpHunting() )
		{
			UpdateEnemy();
			U2P.AssetsHelperClass.static.HandleLostEnemy( U2P );
			UpdateEnemy();
			return;
		}

		if( !bTriedLastDetectedLocation )
		{
			Destination = GetLastEnemyDetectedLocation();
			bTriedLastDetectedLocation = true;
			if( Pawn.FastTrace( ControllerEnemy.Location, ViewSpot ) )
			{
				if( VSize( Pawn.Location - Destination ) < 20 )
				{
					#debug DMAI( "PickDestination -- calling MaybeSetEnemy" );
					MaybeSetEnemy( ControllerEnemy );
				}
				return;
			}
		}

		Pawn.bAvoidLedges = ( Pawn.CollisionRadius > 42 );
		posZ = GetLastEnemySeenLocation().Z + Pawn.CollisionHeight - ControllerEnemy.CollisionHeight;
		NextSpot = GetLastEnemySeenLocation() - Normal( ControllerEnemy.Velocity ) * Pawn.CollisionRadius;
		NextSpot.Z = posZ;
		if( Pawn.FastTrace( NextSpot, ViewSpot ) )
			Destination = NextSpot;
		else if( bCanSeeLastSeen )
			Destination = GetLastEnemySeenLocation();
		else
		{
			Destination = GetLastEnemySeenLocation();
			if( !Pawn.FastTrace( GetLastEnemySeenLocation(), ViewSpot ) )
			{
				// check if could adjust and see it
				if( PickWallAdjust( Normal( GetLastEnemySeenLocation( ) - ViewSpot ) ) || FindViewSpot() )
				{
					if( Pawn.Physics == PHYS_Falling )
						SetFall();
					else
						GotoLabel( AdjustFromWallLabel );
				}
				else if( VSize( ControllerEnemy.Location - Pawn.Location ) < 1200 )
				{
					//2002.12.07 mdf-tbd: need to invalidate enemy if giving up?
					UpdateEnemy();
					return;
				}
				else
				{
					//2002.12.07 mdf-tbd: need to invalidate enemy if giving up?
					UpdateEnemy();
					return;
				}
			}
		}
		
		// cheat -- update last detected location with enemy's current location
		SetLastEnemyDetectedLocation( ControllerEnemy.Location );
	}	

	//-------------------------------------------------------------------------

	function BlockFiring()
	{
		// make sure NPC can't fire for a bit
		if( (Level.TimeSeconds - AlertTime) > 8.0 )
			BCBlockFiring( U2PBasic.MinReAcquisitionDelay, false );	// don't react as quickly
		else
			BCBlockFiring( U2PBasic.MinAlertAcquisitionDelay, false ); // still fairly alert - react more quickly
	}
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		SetAlertness( 0.5 );
		bTriedLastDetectedLocation = false;
		bDeviousHunting = GetShouldUseDeviousTactics( 0.50, 0.50 );
		U2PBasic.bAlertedEnemyHunted = false;
		AlertTime = Level.TimeSeconds - GetTimeSinceEnemyLastDetected();
		TimeSinceBeginState = Level.TimeSeconds;
	}

	//-------------------------------------------------------------------------

	event EndState()
	{
		bHunting = false;
		RestoreAlertness();
		if( Pawn != None )
		{
			Pawn.bAvoidLedges = Pawn.default.bAvoidLedges;
			Pawn.bCanJump = (Pawn.JumpZ > 0);
		}
		EnableSenses();		
		BlockFiring();
	}

	//-------------------------------------------------------------------------

@ AdjustFromWallLabel:
	MoveToPoint( Destination, , MoveTarget ); 
	Goto( HuntLabel );

@ BeginLabel:
	ClearMoveAttempts();

@ HuntLabel:
	//!!mdf-tbd: FindSpecialAttraction();

	/*!!mdf-tbd:
	if( bSniping )
	{
		#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() ); //!!tbd: BC_StakeOut?
	}	#release BehaviorController.Update( BC_AttackUpdate ); //!!tbd: BC_StakeOut?
	
	if( Orders == OrdersFollow ) 
	{
		if( !LineOfSightTo( Controller(OrdersObject).Pawn ) )
			GS( AttackFallbackState );  //GS-tbd
	}
	else if( Orders == OrdersHold ) 
	{
		if( !LineOfSightTo( OrdersObject ) )
			GS( AttackFallbackState );  //GS-tbd
	}
	else if( Orders == OrdersDefend )
	{
		if( AmbushSpot != None )
		{
			if( !LineOfSightTo( AmbushSpot ) )
				GS( AttackFallbackState );  //GS-tbd
		}
		else if( !LineOfSightTo( OrdersObject ) )
			GS( AttackFallbackState );  //GS-tbd
	}
	*/

	WaitForLanding();
	if( CanSee( ControllerEnemy ) )
	{
		#debug DMAI( "AttackHuntState (CanSee) -- calling MaybeSetEnemy" );
		//!!mdf-tbd 08/26 just do a BC_EnemyRecovered? 
		// MaybeSetEnemy( ControllerEnemy );
		#debug   BehaviorController.Update( BC_EnemyRecovered, GetContext() );
		#release BehaviorController.Update( BC_EnemyRecovered );
	}
	PickDestination();

	if( Level.TimeSeconds - TimeSinceBeginState > 8.0 && !U2PBasic.bAlertedEnemyHunted )
	{
		U2PBasic.bAlertedEnemyHunted = true;
		U2P.AssetsHelperClass.static.HandleHuntEnemy( U2P );
	}

@ MoveSpecialLabel:
	if( TimeSinceTargetLastSeen( GetTarget() ) < U2PBasic.MaxHuntFireAtLastSeenTime )
	{
		Focus = None;
		FocalPoint = GetLastEnemySeenLocation();
	}
	else if( FaceTarget( 1 ) )
		Focus = ControllerEnemy;
	else
		Focus = MoveTarget;
		
	if( MoveTarget == None )
		MoveToPoint( Destination, , Focus );
	else
		MoveToActor( MoveTarget, TMT_None, , , Focus ); 
	
	Goto( HuntLabel );
	
@ AdjustPositionLabel:
	#debug DMAIA( "adjusting firing position  ControllerEnemy: " $ ControllerEnemy );
	NumMoveAttempts = 0;
@ AdjustPositionAgainLabel:
	// make sure enemy can be targeted from current position
	// hack: trace to center of enemy blocked doesn't mean can't shoot head etc.
	//!!tbd: call AdjustAim?
	//AddArrow( GetFireOffset( Pawn.Location, ControllerEnemy.Location ), ControllerEnemy.Location, ColorMagenta() );
	if( !Pawn.FastTrace( GetFireOffset( Pawn.Location, ControllerEnemy.Location ), ControllerEnemy.Location ) )
	{
		NumMoveAttempts++;
		if( NumMoveAttempts > 2 )
			Goto( GiveUpLabel );
			
		//DMTNS( "Adjusting firing position!" );

		//AddActor( Pawn, ColorCyan() );
		//AddActor( ControllerEnemy, ColorRed() );
		//AddArrow( Pawn.Location, Pawn.Location + 256.0*vector(Pawn.Rotation), ColorRed() );
		
		if( GetPossibleFiringLocation( Destination ) )
		{
			// move to within 2.0 units of the given point (instead of using default "reached destination" checks)
			// always face enemy at this point (we've acquired it and we're just fine-tuning our position)
			Focus = ControllerEnemy;
			FocalPoint = Focus.Location;
			MoveToPoint( Destination, 2.0, ControllerEnemy );
			
			// see if enemy targetable now
			Goto( AdjustPositionAgainLabel );
		}
	}

@ AdjustRotationLabel:
	#debug DMAIA( "adjusting firing rotation  ControllerEnemy: " $ ControllerEnemy );
	
	Focus = ControllerEnemy;
	FocalPoint = Focus.Location;
	FinishRotation( DefaultRotationThreshold );

@ GiveUpLabel:
	#debug DMAIA( "CanFire before BC_EnemyRecovered: " $ CanFire( true ) $ " Target: " $ GetTarget() );
	#debug   BehaviorController.Update( BC_EnemyRecovered, GetContext() );
	#release BehaviorController.Update( BC_EnemyRecovered );
} // AttackHuntState

/*-----------------------------------------------------------------------------
NOTE: some NPCs are allowed to enter this state without having any line of 
sight to their enemy, e.g. so they can leap over walls and such at their enemy
(making them somewhat "psychic").
*/

// just in case...
function NotifyLeapBegin();
function FakeNotifyLeapBeginTimer();

state @ AttackLeapState
{
	ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise, EnemyInLeapRange, EnemyInMeleeRange;

	//-------------------------------------------------------------------------

	function TryToDodge( vector DuckDir, bool bDuckLeft );
	function PlayRandomSound();

	//-------------------------------------------------------------------------

	function int GetLeapDamage( Pawn Other )
	{
		local vector ForwardLocation;
		local float DamageDistance;
		
		ForwardLocation = Pawn.Location + (Pawn.CollisionRadius + Other.CollisionRadius) * vector(Pawn.Rotation);
		ForwardLocation.Z = Other.Location.Z; // 2D check
		
		DamageDistance = VSize( Other.Location - ForwardLocation );
		
		return class'Util'.static.ScaleLinear( DamageDistance, 0.0, 512.0, U2PBasic.LeapMaxDamage, 0.0 );
	}
	
	//-------------------------------------------------------------------------

	function vector GetLeapMomentumTransfer( Pawn Other )
	{
		local vector ForwardLocation;
		local vector MomentumVector;
		local float MomentumDistance;
		local vector Result;

		ForwardLocation = Pawn.CollisionRadius * vector(Pawn.Rotation);
		MomentumVector = Pawn.CollisionRadius * Normal( Other.Location - Pawn.Location );

		MomentumDistance = VSize( MomentumVector - ForwardLocation );
		
		Result = Normal( MomentumVector ) * class'Util'.static.ScaleLinear( MomentumDistance, 0.0, Pawn.CollisionRadius, U2PBasic.LeapMaxMomentumTransfer, 0.0 );

		// Momentum into the ground probably won't move the victim
		if( Result.Z < 0 )
			Result.Z *= -0.5;

		return Result;
	}
	
	//-------------------------------------------------------------------------

	function eventBumpEnemy( Pawn Other )
	{
		//DMTNS( "BumpEnemy: " $ Other );
		if( Level.TimeSeconds - LastBumpDamageTime > 1.0 )
		{
			U2PBasic.HandleLeapImpactSound();
			Other.TakeDamage( GetLeapDamage( Other ), Pawn, Other.Location, GetLeapMomentumTransfer( Other ), class'DamageTypePhysical' );
			LastBumpDamageTime = Level.TimeSeconds;
		}
		
		if( Other.Health > 0 )
			Global.eventBumpEnemy( Other );
			
		if( FDecision( U2PBasic.LeapToMeleeOdds ) )
		{
			BehaviorController.SetBCEnabled( true );
			if( ValidEnemy( ControllerEnemy ) )
			{
				#debug   BehaviorController.Update( BC_MeleeRange, GetContext() );
				#release BehaviorController.Update( BC_MeleeRange );
			}
		}
		else
		{
			#debug   UpdateBehavior( true, GetContext() );
			#release UpdateBehavior( true );
		}
	}
	
	//-------------------------------------------------------------------------

	event bool NotifyHitWall( vector HitNormal, Actor Wall )
	{
		if( LeapLastHitWallNormal != HitNormal ||
			Level.TimeSeconds - LeapLastHitWallTime > LeapMinHitWallDelay )
		{
			U2P.LandedOnTexture( VSize(Pawn.Velocity) );
			LeapLastHitWallNormal = HitNormal;
			LeapLastHitWallTime = Level.TimeSeconds;
			return Global.NotifyHitWall( HitNormal, Wall );
		}
	}

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest ) { return false; } //NOTE: leap animation could always contain spawnshot notifies...
	
	//-------------------------------------------------------------------------

	function NotifyLeapBegin()
	{
		//DMTNS( "NotifyLeapBegin" );
		RemoveTimer( FakeNotifyLeapBeginTimerName );
		if( !bLeaping ) // in case 2nd notify comes in somehow
		{
			bLeaping = true;
			
			//DMTNS( "NotifyLeapBegin" );
			//U2P.DumpAgentInfo();
			
			U2P.AssetsHelperClass.static.HandleLeapSound( U2P );
			GotoLabel( StartLeapLabel );
		}
		else
		{
			DMTNS( "WARNING: got a 2nd LeapBegin notify while already leaping?!" );
			//U2P.DumpAgentInfo();
			//U2P.MakeErrorObvious( ET_Other );
		}
	}
	
	//-------------------------------------------------------------------------
	// Sent by Pawn when (if) it receives NotifyLeapBegin.

	function ReflectNotify( name NotifyName )
	{
		if( NotifyName == LeapBeginNotify )
		{
			if( !bLeapNotifyTimeSet )
				U2PBasic.LeapNotifyTime = Level.TimeSeconds + U2PBasic.LeapNotifyTime;

			NotifyLeapBegin();
		}
		else
		{
			Super.ReflectNotify( NotifyName );
		}
	}

	//-------------------------------------------------------------------------

	function FakeNotifyLeapBeginTimer()
	{
		//DMTNS( "WARNING: NPC leap animation doesn't have a LeapBegin notification: " $ Pawn );
		//U2P.MakeErrorObvious( ET_Other );
		//U2P.DumpAgentInfo();
		NotifyLeapBegin();
	}

	//-------------------------------------------------------------------------

	function DoLeapAttack( rotator LeapRotation, float LeapSpeed )
	{
		//AddArrow( Pawn.Location, LeapDestination, ColorYellow() );
		Pawn.Velocity = LeapSpeed * vector(LeapRotation);
		Pawn.SetPhysics( PHYS_Falling );
		//DMTNS( "Jump Velocity: " $ Pawn.Velocity $ " VSize: " $ VSize( Pawn.Velocity ) );
		//AddArrow( Pawn.Location, Pawn.Location + Pawn.Velocity, ColorGreen() );
		//Focus = ControllerEnemy;
		//Destination = ControllerEnemy.Location;
		Enable( Event_NotifyBump );
	}

	//-------------------------------------------------------------------------

	function AbortedLeap()
	{
		//DMTNS( "AbortedLeap" );
		NextLeapTime = Level.TimeSeconds + U2PBasic.LeapDelayFailure;
		#debug   UpdateBehavior( true, GetContext() );
		#release UpdateBehavior( true );
	}

	//-------------------------------------------------------------------------

	function FinishedLeap()
	{
		//DMTNS( "FinishedLeap"  );
		#debug   UpdateBehavior( true, GetContext() );
		#release UpdateBehavior( true );
	}
	
	//-------------------------------------------------------------------------
		
	event BeginState()
	{
		Disable( Event_NotifyBump );
		//DMTNS( "BeginState Physics: " $ EnumStr( enum'EPhysics', Pawn.Physics ) $ " Velocity: " $ Pawn.Velocity $ " Health: " $ Pawn.Health );
		#debug   StopFiring( 0.5, SFI_Behavior, GetContext() );
		#release StopFiring( 0.5, SFI_Behavior );
		BehaviorController.SetBCEnabled( false );
		Pawn.bFallingHitWallNotifications = true;
	}

	//-------------------------------------------------------------------------

	event EndState()
	{
		//if( Pawn != None )
		//	DMTNS( "  Physics: " $ EnumStr( enum'EPhysics', Pawn.Physics ) $ " Velocity: " $ Pawn.Velocity $ " Health: " $ Pawn.Health );
		CheckBehaviorEnabled();
		BCStartFiring();
		Enable( Event_NotifyBump );
		EnableRotation( true );
		RemoveTimer( FakeNotifyLeapBeginTimerName ); //mdf-tbr:
		UnLockAnimationController();
		bLeaping = false;
		if( Pawn != None )
			Pawn.bFallingHitWallNotifications = Pawn.default.bFallingHitWallNotifications;
	}
	
	//-------------------------------------------------------------------------
	
@ BeginLabel:
	//DMTNS( "begin label" );
	//StopMovement( true, true );
	Focus = ControllerEnemy;
	//DMTNS( "call FinishRotation" );
	FinishRotation( DefaultRotationThreshold );
		
	// only get the leap parameters once the NPC is facing the enemy or could be *way* off
	if( !GetLeapParameters( PendingLeapRotation, PendingLeapSpeed ) )
		AbortedLeap();

	//DMTNS( "final turning delay" );
	
	// do final turning + delay			
	StopMovement( true, true );
	StartTurnTime = Level.TimeSeconds;
	Focus = None;
	FocalPoint = Pawn.Location + 512.0*vector(PendingLeapRotation);
	FinishRotation( DefaultRotationThreshold );
	Sleep( U2PBasic.LeapDelayPreJump - (Level.TimeSeconds - StartTurnTime) );
	
	//DMTNS( "start leap animation" );
	bLeaping = false;
	if( U2P.AnimationController.SpecialAnimationLeap() == 0.0 )
	{
		DMTNS( "WARNING: NPC doesn't have a leap animation AnimSequence: " $ Pawn.AnimSequence);
		AbortedLeap();
	}
	
	// the first notify will be used to "refine" the LeapNotifyTime for subsequent jumps
	if( !bLeapNotifyTimeSet )
		U2PBasic.LeapNotifyTime = -Level.TimeSeconds;
			
	// in case notify not present...
	//AddTimer( FakeNotifyLeapBeginTimerName, 2.0, false );
	AddTimer( FakeNotifyLeapBeginTimerName, 1.0, false );
	//AddTimer( FakeNotifyLeapBeginTimerName, 0.25, false );

	//DMTNS( "wait for LeapBegin notification" );
	Stop; // wait for leap begin notification
	
@ StartLeapLabel:
	EnableRotation( false );
	//DMTNS( "leaping" );
	DoLeapAttack( PendingLeapRotation, PendingLeapSpeed );
	NextLeapTime = Level.TimeSeconds + U2PBasic.LeapDelaySuccess;
	//DMTNS( "wait for landing" );
	WaitForLanding();
	//DMTNS( "landed" );

	U2PBasic.HandleLeapLandSound(); // sounds in addition to landing thump

	//DMTNS( "landed, not moving for a bit" );	
	StopMovement( true, true );
	Sleep( U2PBasic.LeapDelayLand );
	EnableRotation( true );
	
	// turn to enemy (while stationary) before leaving state?
	if( U2PBasic.bTurnToEnemyAfterLeap )
	{
		Focus = ControllerEnemy;
		//DMTNS( "calling FinishRotation" );
		FinishRotation( DefaultRotationThreshold );
		//DMTNS( "called FinishRotation" );
	}
	
	//DMTNS( "FinishedLeap" );
	FinishedLeap();
} // AttackLeapState

//-----------------------------------------------------------------------------

state @ AttackMeleeState
{
	ignores SeeFriend, SeeOther, SeeAlertFriend, HearNoise, NotifyBump, EnemyInLeapRange, EnemyInMeleeRange;

	function PlayRandomSound();

	//-------------------------------------------------------------------------

	event EnemyNotInMeleeRange()
	{
		//DMTNS( "EnemyNotInMeleeRange" );
		if( bMeleeDamagedTarget )
		{
			#debug   BehaviorController.Update( BC_MeleeRangeLostHit, GetContext() );
			#release BehaviorController.Update( BC_MeleeRangeLostHit );
		}
		else
		{
			#debug   BehaviorController.Update( BC_MeleeRangeLost, GetContext() );
			#release BehaviorController.Update( BC_MeleeRangeLost );
		}
	}

	//-------------------------------------------------------------------------

	function NotifyMeleeDamagedEnemy( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		// update behavior once animation ends
		//DMTNS( "NotifyMeleeDamagedEnemy" );
		bMeleeDamagedTarget = true;
	}

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest ) { return false; }
	function bool CanDodge( optional bool bIgnoreFalling ) { return false; }
	
	//-------------------------------------------------------------------------

	function eventEnemyNotVisible()
	{
		#debug   BehaviorController.Update( BC_EnemyNotVisible, GetContext() );
		#release BehaviorController.Update( BC_EnemyNotVisible );
	}

	//-------------------------------------------------------------------------
	
	event BeginState()
	{
		//DMTNS( "BeginState!" );
		#debug   StopFiring( 0.0, SFI_Behavior, GetContext() );
		#release StopFiring( 0.0, SFI_Behavior );
		if( U2PBasic.MeleeSpeed > 0.0 )
		{
			Pawn.Velocity =  U2PBasic.MeleeSpeed * Normal(Pawn.Velocity) * Pawn.default.GroundSpeed;
			Pawn.DesiredSpeed = U2PBasic.MeleeSpeed;
		}
		if( StationaryPawn(ControllerEnemy) != None )
			Enable( Event_SeeEnemy );
		else
			Disable( Event_SeeEnemy );
	}
	
	//-------------------------------------------------------------------------
		
	event EndState()
	{
		//DMTNS( "EndState!" );
		
		MeleeAttackAbort();
		BCBlockFiring( 0.5, false ); // fire no sooner than 0.5 secs from now?
		//DMTNS( "EndState" );
		if( U2PBasic != None && U2PBasic.MeleeSpeed > 0.0 )
			U2PBasic.DesiredSpeed = U2PBasic.default.DesiredSpeed;
		bMeleeDamagedTarget = false;
	}

	//-------------------------------------------------------------------------

@ BeginLabel:
	Pawn.DesiredRotation = Rotator( ControllerEnemy.Location - Location );

@ FaceTargetLabel:
	//NOTE: if we just returned from MoveToXXX acceleration is now 0,0,0

	if( IsMobile() && U2PBasic.bHasMovingMeleeAttack )
	{
		#debug DMAIA( "moving melee attack -- matching enemy acceleration" );
		UpdateAcceleration( ControllerEnemy, U2PBasic.MeleeAccelerationChangeLimit, U2PBasic.MeleeAccelRate, U2PBasic.MeleeSpeed );
	}
	else
	{
		#debug DMAIA( "stationary melee attack -- stopping" );
		StopMovement( true, false );
	}

	if( NeedToTurn( ControllerEnemy.Location, NeedToTurnAngleCos ) )
	{
		Focus = GetTarget();
		FinishRotation( DefaultRotationThreshold );
	}

@ ReadyToAttackLabel:
	Pawn.DesiredRotation = Rotator( ControllerEnemy.Location - Pawn.Location );

	if( FDecision( U2PBasic.ImpaleToMeleeOdds ) && CanImpale( ControllerEnemy ) )
	{
		#debug DMAIA( "calling ImpaleAttack from MeleeAttackState" );
		ImpaleAttack();
		Goto( AttackDoneLabel );
	}
	else
	{
		#debug DMAIA( "calling MeleeAttack from MeleeAttackState" );
		MeleeAttack( 0 ); // attack!
		
		#debug DMAIA( "setting focus and calling FinishRotation, Target:" $ GetTarget() );
		Focus = GetTarget();
		FinishRotation( DefaultRotationThreshold ); // note: this latent yield guarantees we won't immediately loop again (infinite recursion)
		Sleep( MeleeEndTime - Level.TimeSeconds );
		#debug DMAIA( "melee attack done  bMeleeDamagedTarget: " $ bMeleeDamagedTarget );
		//DMTNS( "melee attack done  bMeleeDamagedTarget: " $ bMeleeDamagedTarget );
		if( bMeleeDamagedTarget )
		{
			#debug   BehaviorController.Update( BC_MeleeUpdateHit, GetContext() );
			#release BehaviorController.Update( BC_MeleeUpdateHit );
		}
		else
		{
			#debug   BehaviorController.Update( BC_MeleeUpdate, GetContext() );
			#release BehaviorController.Update( BC_MeleeUpdate );
		}
			
		Goto( FaceTargetLabel );
	}

@ AttackDoneLabel:
	Stop;
} // AttackMeleeState

//-----------------------------------------------------------------------------

state @ AttackMoveToCoverBaseState extends @ AttackFallbackState
{
	//ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise; // only worry about the current threat?
    ignores SeeFriend, SeeOther, SeeAlertFriend, HearNoise; // only worry about the current threat?
	function eventBumpEnemy( Pawn Other );

	//-------------------------------------------------------------------------

	function SetCurrentCoverSpot( CoverSpot NewCoverSpot )
	{
		AssignCoverSpot( NewCoverSpot );
		LastSpecialDestinationCheck = Level.TimeSeconds;	
	}
	
	//-------------------------------------------------------------------------

	function bool VerifyCoverSpot()
	{
		local bool bResult;

		if( CurrentCoverSpot == None )
		{
			#debug DMAI( "VerifyCoverSpot - CurrentCoverSpot not set, returning false" );
			bResult = false;
		}
		else if( CurrentCoverSpot.bDeleteMe )
		{
			#debug DMAI( "VerifyCoverSpot - CurrentCoverSpot was deleted, returning false" );
			bResult = false;
		}
		else if( (Level.TimeSeconds - LastSpecialDestinationCheck) < VerifyCoverRate )
		{
			#debug DMAI( "VerifyCoverSpot - was checked " $ (Level.TimeSeconds - LastSpecialDestinationCheck) $ " secs ago - returning true" );
			bResult = true;
		}
		else
		{
			#debug DMAI( "VerifyCoverSpot calling ValidCoverActor (somewhat expensive)" );
			bResult = ValidCoverActor( CurrentCoverSpot, ControllerEnemy, false );
			#debug DMAI( "  bResult: " $ bResult );
			LastSpecialDestinationCheck = Level.TimeSeconds;	
		}

		//DMTNS( "VerifyCoverSpot returning: " $ bResult );
		return bResult;
	}

	//-------------------------------------------------------------------------

	function TryToFindCover()
	{
		DMTNS( "WARNING: TryToFindCover needs to be overridden in a derived state!" );
	}
	
	//-------------------------------------------------------------------------

	function CoverSpot FindCoverActor( float MaxDistance, float	CosMinAngle, float CosMaxAngle, bool bIncludePathable )
	{
		local CoverSpot BestSpot;

		BestSpot = FindCoverSpot( ControllerEnemy, 0.0, MaxDistance, -2048.0, 2048.0, CosMinAngle, CosMaxAngle, bIncludePathable );
		if( BestSpot != None )
		{
			#debugbegin
			if( CurrentCoverSpot != None && VSize(CurrentCoverSpot.Location - BestSpot.Location) ~= 0.0 )
				DMTNS( "Warning: reselected same spot?!" );
			#debugend

			SetCurrentCoverSpot( BestSpot );
		}

		return BestSpot;
	}

	//-------------------------------------------------------------------------

	function bool ShouldClearSpecialColliders()
	{
		return Global.ShouldClearSpecialColliders(); // so won't try to reach cover through XMP items
	}

	//-------------------------------------------------------------------------
	// Head towards a good cover location and stick with it as long as the 
	// (any?) enemy can't see it. We can assume that there is LOS to the enemy 
	// (otherwise eventEnemyNotVisible should take us out of this state).

	function PickDestination()
	{
		local Controller C;
		
		/*!!mdf-tbd:
		// shook off enemy?
		if( GetTimeSinceEnemyLastSeen() > 3 ) //9
			#debug   SetControllerEnemy( None, GetContext() );
			#release SetControllerEnemy( None );
		*/
		
		if( !ValidEnemy( ControllerEnemy ) )
		{
			UpdateEnemy();
		}
		else
		{
			#debug DMAI( "CurrentCoverSpot IN: " $ CurrentCoverSpot );
			if( !ControllerEnemy.LineOfSightTo( Pawn ) ) // can this ever happen without getting eventEnemyNotVisible first?
			{
				// current location / stance is safe
				#debug DMAI( "current location not visible from enemy" );
				MoveTarget = Pawn;
				//!!mdf-tbd: we *don't* want to clear the CurrentCoverSpot here since
				//we pbly want to go back to it (only clear when its invalid or when
				//the meta state changes)
				//ClearCoverSpot();
			}
			else
			{
				if( !VerifyCoverSpot() )
				{
					#debug DMAI( "CurrentCoverSpot is invalid or not set - calling TryToFindCoverSpot" );
					ClearCoverSpot();
					TryToFindCover();
					#debug DMAI( "TryToFindCover returned: " $ CurrentCoverSpot );
				}
				else
				{
					#debug DMAI( "Keeping current cover spot: " $ CurrentCoverSpot );
				}

				//DMTNS( "CurrentCoverSpot: " $ CurrentCoverSpot );
	
				if( CurrentCoverSpot != None )
				{
					// have to keep making sure whether directly reachable or pathing required
					//!!! GMoveType = GetMoveTarget( CurrentCoverSpot );
	
					GetPathToActor( CurrentCoverSpot, MoveTarget, true );
					
					/* mdf-tbd: in situations with lots of NPCs, this happens on a regular basis.
					   From what I can tell, this may be happening in cases where the NPC should
					   be able to build a path but I'm not sure and a) this is happening rarely
					   enough that I don't want to spend time on this now and b) "fixing" this
					   might give undesirable results, since this seems to happen when the cover
					   spot is blocked by another NPC and the only path to it might be an
					   undesireable one (e.g. takes NPC way out of his way and possibly towards
					   his enemy. Just let the MoveNoDestLabel code handle this situation for
					   now and NPC will eventually try something else.
					if( MoveTarget == None )
					{
						//DMTNS( "Warning: can't build path to cover spot: " $ CurrentCoverSpot );
						//AddActor( Pawn, ColorCyan() );
						//AddActor( CurrentCoverSpot, ColorRed() );
						//AddArrow( Pawn.Location, CurrentCoverSpot.Location, ColorRed() );
						//for( C=Level.ControllerList; C!= None; C = C.nextController )
						//	AddActor( C.Pawn, ColorBlue() );
							
						//hack: try again and enable debug info (requires that FindPathToActor looks for this hack)
						//Pawn.CrouchHeight = 31.0;
						//FindPathToActor( CurrentCoverSpot, MoveTarget , , , false );
						//Pawn.CrouchHeight = Pawn.default.CrouchHeight;
					}
					*/
				}
				else
				{
					MoveTarget = None;
				}
			}
		}
	}
	
	//-------------------------------------------------------------------------

	function Actor GetFinalDestinationActor()
	{
		return CurrentCoverSpot;
	}
	
	//-------------------------------------------------------------------------

	function float GetReachedDestinationDistance()
	{
		return 1.0; // need to get real close to cover spot
	}
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		Super.BeginState();
		
		if( CurrentCoverSpot != None && VSize2D(Pawn.Location - CurrentCoverSpot.Location) > 512 )
		{
			//!!mdf-tbd: does this make sense - is there a better way?
			// the idea here is that generally NPC's will step a short distance
			// to re-acquire their enemy but if they have to move further to
			// hunt the enemy then we should clear the old cover spot or else
			// they will always tend to go back to it
			ClearCoverSpot();
		}
	}	

	//-------------------------------------------------------------------------

@ MoveNoDestLabel:
	#debug DMAIA( "setting focus and calling FinishRotation, Focus:" $ GetTarget() );
	Focus = GetTarget();
	if( Focus != None )
	{
		StopMovement( true, false );
		if( NeedToTurn( Focus.Location, NeedToTurnAngleCos ) )
			FinishRotation( DefaultRotationThreshold );
		else
			Sleep( 0.5 );
	}
	#debug DMAIA( "calling BC_CoverNotFound" );
	#debug   BehaviorController.Update( BC_CoverNotFound, GetContext() );
	#release BehaviorController.Update( BC_CoverNotFound );
	Goto( MovePickDestLabel ); // really just a fallback in case Update does nothing
} // AttackMoveToCoverBaseState

//-----------------------------------------------------------------------------
// State for "combat" use of cover when trying to get away from an enemy while
// attacking that enemy. Generally maintains focus on enemy (so can fire).

state @ AttackMoveToCoverCombatState extends @ AttackMoveToCoverBaseState
{
    ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise; // only worry about the current threat?
    //ignores SeeFriend, SeeOther, SeeAlertFriend, HearNoise; // only worry about the current threat?

	//-------------------------------------------------------------------------

	function eventEnemyNotVisible()
	{
		local Pawn TempPawn;

		//DMTNS( "eventEnemyNotVisible" );
		//AddActor( Pawn, ColorGreen() );
		// current enemy no longer visible
		if( OldControllerEnemy != None && LineOfSightTo( OldControllerEnemy ) )
		{
			// old enemy visible - swap with current enemy
			TempPawn = OldControllerEnemy;
			OldControllerEnemy = ControllerEnemy;
			#debug   SetControllerEnemy( TempPawn, GetContext() );
			#release SetControllerEnemy( TempPawn );
		}
		else 
		{
			#debug   BehaviorController.Update( BC_CoverReachedCover, GetContext() );
			#release BehaviorController.Update( BC_CoverReachedCover );
		}
	}

	//-------------------------------------------------------------------------

	function ETacticalMoveType GetTacticalMoveType()
	{
		return TMT_None; // otherwise bumps into walls & such plus "use of cover" should be the advanced tactic in the first place
	}

	//-------------------------------------------------------------------------

	function bool FaceTarget( float F )
	{
		return Pawn.bCanStrafe; // always face target when using cover (i.e. whether moving towards enemy or cover spot)
	}

	//-------------------------------------------------------------------------

	function TryToFindCover()
	{
		//DMTNS( "picking new cover spot" );
		#debug DMAIM( "looking for a cover spot within " $ U2PBasic.MaxUseCoverSearchDistance );
/*
		better to just allow pathable
		if( FindCoverActor( U2PBasic.MaxUseCoverSearchDistance, 0.0, -1.0, false ) != None )
			return;

		if( FindCoverActor( U2PBasic.MaxUseCoverSearchDistance, 0.707, 0.0, false ) != None)
			return;
*/

		// is direction meaningless? better to go by min distance?
		// could need to force shorter move time so MoveToActor returns every 0.25 secs or so instead of 1.2
		// at least 90 degrees and at most 180 (directly away -- to allow for pathing, not final destination)
//		if( FindCoverActor( U2PBasic.MaxUseCoverSearchDistance, 0.0, -1.0, true ) != None)
			//return;

//		FindCoverActor( U2PBasic.MaxUseCoverSearchDistance, 0.707, 0.0, true );
		FindCoverActor( U2PBasic.MaxUseCoverSearchDistance, 1.0, -1.0, true );
	}

	//-------------------------------------------------------------------------

	function PickDestination()
	{
		if( Pawn != None )
		{
			if( StationaryPawn(ControllerEnemy) != None && !StationaryPawn(ControllerEnemy).bHasAttack )
			{
				MoveTarget = None;
				#debug   BehaviorController.Update( BC_CoverNotNeeded, GetContext() );
				#release BehaviorController.Update( BC_CoverNotNeeded );
			}
			else
			{
				Super.PickDestination();
			}
		}	
	}
} // AttackMoveToCoverCombatState

//-----------------------------------------------------------------------------
// State for "fearful" use of cover when trying to get away from an enemy 
// without trying to attack that enemy. Generally maintains focus on 
// destination rather than enemy.

state @ AttackMoveToCoverFleeState extends @ AttackMoveToCoverBaseState
{
	//ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise; // only worry about the current threat?
    ignores SeeFriend, SeeOther, SeeAlertFriend, HearNoise; // only worry about the current threat?

	//-------------------------------------------------------------------------

	function bool FaceTarget( float F )
	{
		return false;
	}

	//-------------------------------------------------------------------------

	function TryToFindCover()
	{
		//DMTNS( "picking new cover spot" );
		if( FindCoverActor( U2PBasic.MaxFleeSearchDistance, 0.0, -1.0, true ) != None )
			return;

		if( FindCoverActor( U2PBasic.MaxFleeSearchDistance, 0.707, 0.0, true ) != None )
			return;

		if( FindCoverActor( U2PBasic.MaxFleeSearchDistance, 0.930, 0.707, true ) != None )
			return;
			
		FindCoverActor( U2PBasic.MaxFleeSearchDistance, 1.0, -1.0, true );
	}
} // AttackMoveToCoverFleeState

//-----------------------------------------------------------------------------
//!!mdf-tbd: mainly just use hunting behavior initially. We will probably want
// to track where the NPC came from when going to the cover spot so we can move
// between there and the cover spot.

state @ AttackRecoverEnemyState extends @ AttackHuntState
{
	ignores EnemyNotVisible; 

	//-------------------------------------------------------------------------

	function bool FaceTarget( float F )
	{
		local vector MoveLocation;
		local bool bResult;

		if( !Pawn.bCanStrafe )
			return false;
			
		// always face target when coming out of cover and heading towards
		// enemy's last seen or detected position as long as we started
		// this state fairly recently (don't want NPC looking at hidden
		// enemy all the time -- player should be able to get behind NPC).
		
		if( (Level.TimeSeconds - TimeSinceBeginState) < 3.0 )
		{
			/* doesn't work currently because PickDestination (in AttackHunt)
			   generally sends NPC directly towards enemy (cheats)
			if( MoveTarget != None )
				MoveLocation = MoveTarget.Location;
			else
				MoveLocation = Destination;
				
			bResult = ( VSize( MoveLocation - GetLastEnemySeenLocation() < 100.0 || 
					    VSize( MoveLocation - GetLastEnemyDetectedLocation() ) < 100.0 );
			*/
			
			bResult = true;
		}
		
		//DMTNS( "FaceTarget returning " $ bResult );
		return bResult;
	}

/*
	//-------------------------------------------------------------------------

	function bool MaybeSetEnemy( Pawn NewEnemy, optional bool bAlertingOthers )
	{
		local bool bResult;

		bResult = Global.MaybeSetEnemy( NewEnemy, bAlertingOthers );

		if( bResult )
			HandleRecoveredEnemy();

		return bResult;
	} 
*/	

	//-------------------------------------------------------------------------

	function BlockFiring()
	{
		// make sure NPC can't fire for a bit
		BCBlockFiring( U2PBasic.MinAlertAcquisitionDelay, false );
	}
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		Super.BeginState();
		TimeSinceBeginState = Level.TimeSeconds;
	}
} // AttackRecoverEnemyState

/*-----------------------------------------------------------------------------
Retreating for an NPC is going toward an item while still engaged with an enemy,
but fearing that enemy (so no desire to remain engaged).
*/

state @ AttackRetreatState extends @ MoveToGoalWithEnemyState
{
	ignores EnemyNotVisible, EnemyInLeapRange, EnemyInMeleeRange;

	//-------------------------------------------------------------------------

	event MayFall()
	{
		if( IsFacingTarget( ControllerEnemy, CosMinFacingTargetAngle ) ) // MoveTarget is enemy, not destination
			Pawn.bCanJump = TestCanJump();
	}

	//-------------------------------------------------------------------------

	function ShotFiredNotification( Pawn Shooter, vector FireDir, class<Projectile> ProjectileClass, float ProjSpeed )
	{	
		if( IsFacingTarget( ControllerEnemy, CosMinFacingTargetAngle ) && FRand() < 0.4 ) 
			return;

		Global.ShotFiredNotification( Shooter, FireDir, ProjectileClass, ProjSpeed );
	}

	//-------------------------------------------------------------------------

	function eventSeeEnemy( Pawn Seen )
	{
		if( Seen != ControllerEnemy && MaybeSetEnemy( Seen ) )
			Pawn.MakeNoise( 1.0 );
	}

	//-------------------------------------------------------------------------

	singular function eventHearNoiseThreat( float Loudness, Actor NoiseMaker )
	{
		if( ( NoiseMaker.Instigator == ControllerEnemy ) || LineOfSightTo( ControllerEnemy ) )
			return;

		#debug DMAI( "eventHearNoiseThreat -- calling MaybeSetEnemy" );
		if( MaybeSetEnemy( NoiseMaker.Instigator ) )
		{
			Pawn.MakeNoise( 1.0 );
			#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
			#release BehaviorController.Update( BC_AttackUpdate );
		}
	}

	//-------------------------------------------------------------------------

	function bool StopFearingEnemy()
	{
		return ( GetTimeSinceEnemyLastDetected() > 12 );
	}

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest ) { return ( U2PBasic.bHasMovingRangedAttack && Global.CanFire( bTest ) ); }

	//-------------------------------------------------------------------------

	function bool FindRetreatDestination()
	{
		return false; // mdt-tbd: add fleeing for NPCs (pick non-inventory destination away from enemy)?
	}

	//-------------------------------------------------------------------------

	function PickDestination()
	{
		// do I still fear my enemy?
		if( StopFearingEnemy() )
		{
			#debug   SetControllerEnemy( None, GetContext() );
			#release SetControllerEnemy( None );
		}
		
		if( ControllerEnemy == None )
		{
			#debug   BehaviorController.Update( BC_UpdateInactive, GetContext() );
			#release BehaviorController.Update( BC_UpdateInactive );
		}
		else if( GetReactionToEnemy( ControllerEnemy ) > REACTION_Fear )
		{
			#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
			#release BehaviorController.Update( BC_AttackUpdate );
		}
		else if( !FindRetreatDestination() )
		{
			#debug DMAI( " give up retreat" );
	
			// if nothing, then tactical move
			if( LineOfSightTo( ControllerEnemy ) )
			{
				LastInvFind = Level.TimeSeconds;
				bKamikaze = true;
				GotoState( AttackTacticalMoveState, DontCloseLabel );
			}
			else
			{
				#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
				#release BehaviorController.Update( BC_AttackUpdate );
			}
		}
	}

	//-------------------------------------------------------------------------

	function ChangeDestination()
	{
		local Actor OldTarget;
		local Actor Path;
		
		OldTarget = Home;
		PickDestination();
		if( Home == OldTarget )
		{
			bKamikaze = true;
			//log( "same old target" );
			GotoState( AttackTacticalMoveState, TacticalTickLabel );  //GS-tbd
		}
		else
		{
			GetPathToActor( Home, Path, true );
			if( Path == None )
			{
				//log( "no new target" );
				bKamikaze = true;
				GotoState( AttackTacticalMoveState, TacticalTickLabel );  //GS-tbd
			}
			else 
			{
				MoveTarget = Path;
				Destination = Path.Location;
			}
		}
	}
	
	//-------------------------------------------------------------------------

	function eventBumpEnemy( Pawn Other )
	{
		if( Other == ControllerEnemy && ((Other.Location - Pawn.Location) dot Pawn.Velocity) > 0 )
			bKamikaze = true;
		
		#debug DMAI( "eventBumpEnemy -- calling MaybeSetEnemy" );
		if( MaybeSetEnemy( Other ) && ControllerEnemy == Other && IsPreparedToFire( true ) )
		{
			GotoState( AttackStationaryState );  //GS-tbd
		}
	}
	
	//-------------------------------------------------------------------------

	function ReachedHome()
	{
		if( LineOfSightTo( ControllerEnemy ) )
			ChangeDestination();
		else
		{
			bKamikaze = true;
			#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
			#release BehaviorController.Update( BC_AttackUpdate );
		}
	}

	//-------------------------------------------------------------------------

	function PickNextSpot()
	{
		local Actor Path;

		if( Home == None )
		{
			PickDestination();
			if( Home == None )
				return;
		}
		//log( "find retreat spot" );
		if( AtDestinationActor( Home ) )
		{
			ReachedHome();
		}
		else
		{
			GetPathToActor( Home, Path, true );
			if( Path == None )
			{
				ChangeDestination();
			}
			else
			{
				MoveTarget = Path;
				Destination = Path.Location;
			}
		}
	}

	//-------------------------------------------------------------------------

@ BeginLabel:
@ MovePickDestLabel:
	WaitForLanding();
	PickDestination();

@ MoveActiveLabel:
	if( MoveTarget == None )
	{
		Sleep( 0.0 );
		Goto( MovePickDestLabel );
	}

@ FaceTargetLabel:

	if( FaceTarget( 2 ) )
		MoveToActor( MoveTarget, GetTacticalMoveType(), , , ControllerEnemy );
	else
		MoveToActor( MoveTarget, GetTacticalMoveType() );
	Goto( MovePickDestLabel );
} // AttackRetreatState

//-----------------------------------------------------------------------------

state @ AttackStakeOutState
{
	ignores EnemyNotVisible; 

	//-------------------------------------------------------------------------

	function eventTookDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		if( Pawn.Health > 0 )
		{
			bFrustrated = true;
			Global.eventTookDamage( Damage, Instigator, HitLocation, Momentum, DamageType );
		}
	}

	//-------------------------------------------------------------------------

	/*!!-mdf-tbd: I'm not sure when/if we want to do this -- currently an NPC
	  that is in AttackStakeOut (or a derived state) will immediately go out
	  of that state if, e.g. the enemy fires his weapon (which calls MakeNoise).
	  For now it seems that we should only set the enemy if there is nothing
	  between the instigator and the NPC? */
	  
	singular function eventHearNoiseThreat( float Loudness, Actor NoiseMaker )
	{
		#debug DMAI( "eventHearNoiseThreat -- calling MaybeSetEnemy" );
		if( Pawn.FastTrace( Pawn.Location, NoiseMaker.Instigator.Location ) )
		{
			if( MaybeSetEnemy( NoiseMaker.Instigator ) )
				EnemyDetected( ControllerEnemy.Location ); 
		}
	}
	
	//-------------------------------------------------------------------------

	function bool MaybeSetEnemy( Pawn NewEnemy, optional bool bAlertingOthers )
	{
		if( Global.MaybeSetEnemy( NewEnemy, bAlertingOthers ) )
		{
			Focus = ControllerEnemy;
			#debug   BehaviorController.Update( BC_EnemyAcquired, GetContext() );
			#release BehaviorController.Update( BC_EnemyAcquired );
			return true;
		}
		return false;
	} 
	
	//-------------------------------------------------------------------------

	function bool ContinueStakeOut()
	{
		local float StrengthDelta;
		local bool bResult;

		if( ControllerEnemy != None )
		{
			StrengthDelta = RelativeStrength( ControllerEnemy );
			bResult = ( (VSize( ControllerEnemy.Location - Pawn.Location ) <= 300 + (FRand() * StrengthDelta - U2PBasic.CombatStyle)*350) &&
						(Level.TimeSeconds - GetLastEnemyDetectedTime() <= 2.5 + FMax( -1, 3*(FRand() + 2*(StrengthDelta - U2PBasic.CombatStyle)))) &&
						CanStakeOut() );
		}

		return bResult;
	}

	//-------------------------------------------------------------------------

	event BeginState()
	{
		StopMovement( true, false );
		//DM( "BeginState StakeOut bClearShot: " $ bClearShot );
		Pawn.bCanJump = false;
		SetAlertness( 0.5 );
		RealLastDetectedLocation = GetLastEnemyDetectedLocation();
		if( GetTimeSinceEnemyLastSeen() > 5.0 || (GetTimeSinceEnemyLastDetected() > 6.0 && FRand() < 0.5) )
			FindNewStakeOutDir( ControllerEnemy );
	}

	//-------------------------------------------------------------------------
	
	event EndState()
	{
		SetLastEnemyDetectedLocation( RealLastDetectedLocation );
		RestoreAlertness();
		if( Pawn != None )
			Pawn.bCanJump = (Pawn.JumpZ > 0);
	}

	//-------------------------------------------------------------------------

@ BeginLabel:
	if( AmbushSpot == None )
		bSniping = false;

	if( bSniping && ( VSize( Pawn.Location - AmbushSpot.Location ) > 3 * Pawn.CollisionRadius ) )
	{
		#debug   SetControllerEnemy( None, GetContext() );
		#release SetControllerEnemy( None );
		OldControllerEnemy = None;
		#debug   BehaviorController.Update( BC_UpdateInactive, GetContext() );
		#release BehaviorController.Update( BC_UpdateInactive );
	}
	StopMovement( true, false );
	Focus = None;
	FocalPoint = GetLastEnemyDetectedLocation();
	FinishRotation( DefaultRotationThreshold );
	if( !ValidEnemy( ControllerEnemy ) )
		UpdateEnemy();

	Sleep( 1 + FRand() );
	FindSpecialAttraction();

	if( ContinueStakeOut() )
	{
		if( bSniping && AmbushSpot != None )
			EnemyDetected( Pawn.Location + AmbushSpot.LookDir );
		else if( FRand() < 0.3 || !Pawn.FastTrace( GetLastEnemyDetectedLocation() + vect( 0, 0, 0.9 ) * ControllerEnemy.CollisionHeight, Pawn.Location + vect( 0, 0, 0.8 ) * Pawn.CollisionHeight ) )
			FindNewStakeOutDir( ControllerEnemy );
		Goto( BeginLabel );
	}
	else
	{
		if( bSniping )
		{
			#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
			#release BehaviorController.Update( BC_AttackUpdate );
		}
		
		BlockedPath = None;	
		#debug   BehaviorController.Update( BC_StakeOutEnd, GetContext() );
		#release BehaviorController.Update( BC_StakeOutEnd );
	}
} // AttackStakeOutState

//-----------------------------------------------------------------------------

state @ AttackStakeOutCoverState extends @ AttackStakeOutState
{
	ignores EnemyNotVisible; 

	//-------------------------------------------------------------------------

	function eventTookDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		Super.eventTookDamage( Damage, Instigator, HitLocation, Momentum, DamageType );

		//DMTNS( "eventTookDamage Instigator" $ Instigator );
		//!!mdf-tbd: react to friendly fire also?
		if( Instigator != None && !Pawn.SameTeam( Instigator ) )
		{
			//DMTNS( "adding a FearLocation" );
			
			// discourage NPC from staying at this location when re-selecting cover		
			AddFearLocation( Pawn.Location, 5.0 );
			#debug   BehaviorController.Update( BC_CoverLeavingCover, GetContext() );
			#release BehaviorController.Update( BC_CoverLeavingCover );
		}
	}
	
	//-------------------------------------------------------------------------

	function bool ContinueStakeOut()
	{
		return ( Pawn != None); // let BC determine time to stay in stake out
	}
}

//-----------------------------------------------------------------------------

function FreezeNPCHackTimer()
{
	Pawn.GroundSpeed = Pawn.default.GroundSpeed;
}

//-----------------------------------------------------------------------------
// While in this state, NPC is stationary and (usually) firing at target.

state @ AttackStationaryState
{
	// 2002.11.11 added SeeEnemy -- we have an enemy, we can assume its in sight, no?
	//  and without this, additional SeeEnemy events can cause the behavior set up
	//  for this state (e.g. crouch for at least 1 sec) to get spammed?
	ignores HearNoise, NotifyBump, SeeFriend, SeeOther, SeeAlertFriend;

	//-------------------------------------------------------------------------

	event EnemyRangeTransition( float Distance )
	{
		#debug DMAIA( "EnemyRangeTransition calling CheckEnemyDistance: " $ Distance );
		CheckEnemyDistance( Distance );
	}

	//-------------------------------------------------------------------------

	function SharedTimerEvent()
	{
		#debug DMAIA( "SharedTimerEvent" );
		UpdateEnemy();
	}
	
	//-------------------------------------------------------------------------

	function eventSeeEnemy( Pawn Seen )
	{
		#debug   SetControllerEnemy( Seen, GetContext() ); //!!mdf-tbd: directly setting enemy?
		#release SetControllerEnemy( Seen ); //!!mdf-tbd: directly setting enemy?
		Disable( Event_SeeEnemy );
		Enable( Event_EnemyNotVisible );
		SetSharedTimer( 0.0, false );
		BCStartFiring();
	}
	
	//-------------------------------------------------------------------------

	function eventEnemyNotVisible()
	{
		if( IsMobile() || HasScript() )
		{
			#debug   BehaviorController.Update( BC_EnemyNotVisible, GetContext() );
			#release BehaviorController.Update( BC_EnemyNotVisible );
		}
		else
		{
			// not mobile (and not scripted) -- start a timer and UpdateEnemy if enemy not seen within X secs 
			Disable( Event_EnemyNotVisible );
			Enable( Event_SeeEnemy );
			SetSharedTimer( 30.0, false ); // may as well track enemy for a long time (stay alert)
		}
	}

	//-------------------------------------------------------------------------

	function bool CanUseStillAnimations() { return true; }

	//-------------------------------------------------------------------------

	function KeepAttacking()
	{
		if( !ValidEnemy( ControllerEnemy ) )
			UpdateEnemy();
	}

	//-------------------------------------------------------------------------

	function InitializeState()
	{
		//2002.12.08 mdf: don't change stance if last aim trace hit a friendly
		//since we'll probably have to move soon?
		if( !bLastAimLocationHitFriendly )
		{
			if( SelectStance( false ) )
			{
				#debug DMAIA( "stance changed" );
				GotoLabel( StanceChangeDelayLabel );
			}
		}
	}

	//-------------------------------------------------------------------------

	function bool IgnoreTargetRange() { return bAcceptedState; }
	
	//-------------------------------------------------------------------------
	// Try to find a location to the right or left of the NPC relative to the
	// enemy from which the NPC is likely to be able to fire. If one is found
	// sets Destination to that location and returns true. Sets bBlocked to 1
	// if move was blocked (so caller shouldn't bother trying longer moves 
	// in that direction).
	
	function bool SetValidFiringLocation( bool bTryRight, float Distance, out byte bBlocked )
	{
		local Actor TargetActor;
		local vector RightAngleDirection;
		local vector TargetActorLocation, TargetDestination, BaseLocation;
		local Actor HitActor;
		local vector HitNormal, HitLocation;
		
		TargetActor = GetTarget();
		TargetActorLocation = TargetActor.Location;
		
		RightAngleDirection = Normal( (TargetActorLocation - Pawn.Location) cross vect(0,0,1) );

		if( bTryRight )
			TargetDestination  = Pawn.Location + Distance *  RightAngleDirection;
		else
			TargetDestination  = Pawn.Location + Distance * -RightAngleDirection;

		class'UtilGame'.static.AdjustDestinationForPhysics( Pawn, TargetDestination );

		if( !Pawn.FitActorAt( TargetDestination ) )
		{
			bBlocked = 1;
			return false;
		}

		//AddArrow( Pawn.Location, TargetDestination, ColorOrange() );
		
		if( !PointReachable( TargetDestination ) )
		{
			bBlocked = 1;
			return false;
		}

		//2002.11.23 !!mdf-tbd: check for geometry under NPC so won't adjust partially/mostly off ledges
		BaseLocation = Pawn.Location - Pawn.CollisionHeight*vect(0,0,1);
		if( Pawn.Physics == PHYS_Walking && Pawn.FastTrace( BaseLocation - 16.0*vect(0,0,1), BaseLocation ) )
		{
			//DMTNS( "  ==> NOTHING UNDER NPC! <== " );
			return false;
		}
			
		//!!tbd: call AdjustAim (watch for recursion though)?
		//2002.12.08 -- FastTrace won't hit friendly force fields & NPCs & such
		//if( !Pawn.FastTrace( GetFireOffset( TargetDestination, TargetActorLocation ), TargetActorLocation ) )
		HitActor = Pawn.Trace( HitLocation, HitNormal, TargetActorLocation, GetFireOffset( TargetDestination, TargetActorLocation ), true );
		if( HitActor != None && 
			HitActor != TargetActor &&
			!OKToHit( HitActor, HitLocation, HitNormal ) ) // maybe ok to hit this actor anyway? (AdjustAim will make the final call)
		{
			return false;
		}

		Destination = TargetDestination;
		return true;
	}
	
	//-------------------------------------------------------------------------

	#debug   function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo, string ContextStr )
	#release function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo )
	{
		local bool bFoundAdjustedLocation;
		local byte bRightBlocked, bLeftBlocked;
		
		#debug   Global.StopFiring( SuggestedFireAgainDelay, SFInfo, ContextStr );
		#release Global.StopFiring( SuggestedFireAgainDelay, SFInfo );

		// if we still have a valid enemy, see if we can get to a firing position by
		// moving slightly right/left
		//DMTNS( "StopFiring Basic (" $ SuggestedFireAgainDelay $ "): " $ EnumStr( enum'EStopFiringInfo', SFInfo ) $ " (" $ ContextStr $ ")" );

		if( Level.TimeSeconds >= NextAdjustPositionTime ) // don't adjust if already adjusting
		{
			if( (SFInfo == SFI_NoLOS || SFInfo == SFI_NoShot || SFInfo == SFI_OutOfRange) && // only try to adjust if shot is blocked (e.g. as opposed to SFI_Behavior)
				U2PBasic.bCanAdjustStationaryPosition && // mainly for full-body animations -- can't interrupt these by moving NPC
				BehaviorController.GetCheckBehaviorDelay() >= AdjustAgainDelay && // don't adjust if behavior is about to timeout anyway -- just update behavior below
				IsMobile() &&
				ValidEnemy( ControllerEnemy ) )
			{
				//DMTNS( "  trying to adjust position" );
				
				// moving side to side while prone won't look good
				if( Pawn.GetStance() != ST_Prone || Pawn.GetDesiredStance() != ST_Prone )
				{
					bFoundAdjustedLocation = SetValidFiringLocation( true, Pawn.CollisionRadius, bRightBlocked );
					if( !bFoundAdjustedLocation )
						bFoundAdjustedLocation = SetValidFiringLocation( false, Pawn.CollisionRadius, bLeftBlocked );
					if( !bFoundAdjustedLocation && bRightBlocked == 0 )
						bFoundAdjustedLocation = SetValidFiringLocation( true, 2*Pawn.CollisionRadius, bRightBlocked );
					if( !bFoundAdjustedLocation && bLeftBlocked == 0 )
						bFoundAdjustedLocation = SetValidFiringLocation( false, 2*Pawn.CollisionRadius, bLeftBlocked );
					if( !bFoundAdjustedLocation && bRightBlocked == 0 )
						bFoundAdjustedLocation = SetValidFiringLocation( true, 4*Pawn.CollisionRadius, bRightBlocked );
					if( !bFoundAdjustedLocation && bLeftBlocked == 0 )
						bFoundAdjustedLocation = SetValidFiringLocation( false, 4*Pawn.CollisionRadius, bLeftBlocked );
				}
			
				if( bFoundAdjustedLocation )
				{
					NextAdjustPositionTime = Level.TimeSeconds + AdjustAgainDelay;
					GotoLabel( AdjustPositionLabel );
				}
				else
				{
					// NOTE: don't do this if SFI_Behavior because a) we may
					// not want to leave the state in that case and b) we could
					// get an infinite recursion crash because UpdateBehavior
					// can result in additional calls to StopFiring with 
					// SFI_Behavior.
					#debug   UpdateBehavior( true, GetContext() );
					#release UpdateBehavior( true );
				}
			}				
		
			//DMTNS( "  bFoundAdjustedLocation: " $ bFoundAdjustedLocation );
		}
		else
		{
			//DMTNS( "  still carrying out last adjust position" );
		}
	}

	//-------------------------------------------------------------------------

	function bool ShouldAbortState()
	{
		// bail right away if NPC can't/isn't going to fire (if NPC is one that can fire)
		return( U2PBasic.bHasRangedAttack &&
			  (BehaviorController.GetMinFiringDelay() > U2PBasic.MaxStationaryFiringDelay || 
			  !FDecision( U2PBasic.AttackStationaryCanFireOdds ) || 
			  !CanFire( false ) || 
			  !IsPreparedToFire( true, true, U2Weapon.RatingLow )) );
	}

	//-------------------------------------------------------------------------

	event BeginState()
	{
		if( ShouldAbortState() )
		{
			bAcceptedState = false;
			#debug DMAIA( " bailing from AttackStationary state" );
			#debug   BehaviorController.Update( BC_AttackCantFire, GetContext() );
			#release BehaviorController.Update( BC_AttackCantFire );
		}
		else
		{
			bAcceptedState = true;
			if( StationaryPawn(ControllerEnemy) != None )
				Enable( Event_SeeEnemy );
			else
				Disable( Event_SeeEnemy );
		}
		#debug DMAIA( " bHasRangedAttack:            " $ U2PBasic.bHasRangedAttack );
		#debug DMAIA( " MinFiringDelay:              " $ BehaviorController.GetMinFiringDelay() ); 
		#debug DMAIA( " AttackStationaryCanFireOdds: " $ U2PBasic.AttackStationaryCanFireOdds );
		#debug DMAIA( " CanFire:                     " $ CanFire( true ) );
		#debug DMAIA( " IsPreparedToFire:            " $ IsPreparedToFire( true ) );
	}

	//-------------------------------------------------------------------------

	event EndState()
	{
		local byte OldStance;
		
		#debug DMAIA( "EndState" );
		SetSharedTimer( 0.0, false );
		#debug SetControllerTarget( None, GetContext() );
		#release SetControllerTarget( None );
		NextAdjustPositionTime = 0.0;
		
		if( Pawn != None )
		{
			OldStance = Pawn.GetStance();
		
			if( RestoreStance() )
			{
				//DMTNS( "restoring stance OldStance: " $ OldStance );
				
				// utter hack -- keep NPC from moving for long enough to change stance?
				if( OldStance == ST_Prone )
					AddTimer( FreezeNPCHackTimerName, ProneStanceChangeDuration );
				else
					AddTimer( FreezeNPCHackTimerName, CrouchStanceChangeDuration );
					
				Pawn.GroundSpeed = 0.0;
			}
		}
	}

	//-------------------------------------------------------------------------

@ ChallengeLabel:
	#debug DMAIL( ChallengeLabel );
	StopMovement( true, false );
	Pawn.DesiredRotation = rotator( ControllerEnemy.Location - Pawn.Location );
	Goto( FaceTargetLabel );

@ BeginLabel:
	#debug DMAIL( BeginLabel );
	Focus = GetTarget();

	if( Focus == None )
	{
		#debug   BehaviorController.Update( BC_UpdateInactive, GetContext() );
		#release BehaviorController.Update( BC_UpdateInactive );
	}
	if( Pawn(Focus) != None && !ValidEnemy( Pawn(Focus) ) )
		UpdateEnemy();
		
	StopMovement( true, true );
	#debug DMAIA( " calling initialize state" );
	InitializeState();
	
@ FaceTargetLabel:
	Focus = GetTarget();
	//!!mdf-tbd: check whether prepared to attack and have possibility of aborting 
	// stationary attack (e.g. to use cover). Should there be a meta state like
	// MS_NotPrepared with associated behaviors (close,findcover?
	#debug DMAIL( FaceTargetLabel );
	if( NeedToTurn( Focus.Location, NeedToTurnAngleCos ) )
	{
		#debug DMAIL( "FinishRotation -- begin" );
		FinishRotation( DefaultRotationThreshold );
		#debug DMAIL( "FinishRotation -- end" );
	}

	#debug DMAIA( "Ready to attack in " $ GetStateName() );

@ AttackOngoingLabel:
	Focus = GetTarget();
	#debug DMAIL( AttackOngoingLabel );

	if( Focus != None && Focus.bDeleteMe )
	{
		#debug   BehaviorController.Update( BC_TargetInvalid, GetContext() );
		#release BehaviorController.Update( BC_TargetInvalid );
	}
	else if( ControllerEnemy != None && !ValidEnemy( ControllerEnemy ) )
	{
		UpdateEnemy();
	}
	
	//!!mdf CheckAttackStatus();

	//!!mdf-tbd: need a latent yield here but with new approach we probably
	//don't even need to be looping this code?
	RefireDelay = GetCurrentFireRate();

	if( RefireDelay >= 0.05 && RefireDelay <= U2Weapon.MaxRapidFireRate )
		Sleep( RefireDelay );
	else
		Sleep( 0.5 ); // need at least some latent yield here

	Goto( AttackOngoingLabel );

@ StanceChangeDelayLabel:
	#debug DMAIA( "StanceChangeDelayLabel" );

	// NOTE: DesiredStance is set but Stance won't change (if possible) until next tick
	
	// make sure state doesn't time-out for at least some time after going to crouching/prone
	BehaviorController.GetTimeOutDelays( OldCheckBehaviorDelay, OldCheckMetaStateDelay ); // save off old times in case stance change fails
	if( Pawn.GetDesiredStance() == ST_Crouching )
	{
		BehaviorController.SetMinTimeOutDelay( U2PBasic.MinStayCrouchingTime );
	}
	else if( Pawn.GetDesiredStance() == ST_Prone )
	{
		BehaviorController.SetMinTimeOutDelay( U2PBasic.MinStayProneTime );
	}
		
	// when we stand up (assume stance change won't fail) don't crouch/go prone again for a while
	ReduceStanceAgainTime = Level.TimeSeconds + U2PBasic.MinReduceStanceAgainDelay;

	FinishAnim();   // let stance change anim finish (if any)
	Sleep( 0.001 ); // make sure at least 1 tick passes
	
	if( Pawn.GetStance() == ST_Standing )
	{
		// stance change failed -- restore timers
		BehaviorController.RestoreTimeOutDelays( OldCheckBehaviorDelay, OldCheckMetaStateDelay );
	}
	
	#debug DMAIA( "after FinishAnim  Stance: " $ Pawn.GetStance() );
	
	Goto( FaceTargetLabel );

@ AdjustPositionLabel:
	#debug DMAIA( "adjusting firing position  ControllerEnemy: " $ ControllerEnemy );
	//AddActorAt( Pawn, Destination, ColorPink() );
	Focus = ControllerEnemy;
	FocalPoint = Focus.Location;
	MoveToPoint( Destination, 2.0, ControllerEnemy );
	//DMTNS( "  MoveToPoint returned " $ EnumStr( enum'EMoveResult', MoveResult ) );
	StopMovement( true, true );
	NextAdjustPositionTime = 0.0;
	
@ AdjustRotationLabel:
	#debug DMAIA( "adjusting firing rotation  ControllerEnemy: " $ ControllerEnemy );
	
	Focus = ControllerEnemy;
	FocalPoint = Focus.Location;
	FinishRotation( DefaultRotationThreshold );
	//DMTNS( "  finished rotation" );
	
	Goto( AttackOngoingLabel );
} // AttackStationaryState

//-----------------------------------------------------------------------------

state @ AttackTacticalMoveState
{
	ignores HearNoise, NotifyBump, SeeFriend, SeeOther, SeeAlertFriend;

	//-------------------------------------------------------------------------

	function UpdateTacticalMoveBehavior()
	{
		#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
		#release BehaviorController.Update( BC_AttackUpdate );
	}

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest )	{ return ( U2PBasic.bHasMovingRangedAttack && FDecision( U2PBasic.AttackTacticalMoveCanFireOdds ) && Global.CanFire( bTest ) ); }

	//-------------------------------------------------------------------------

	function ShotFiredNotification( Pawn Shooter, vector FireDir, class<Projectile> ProjectileClass, float ProjSpeed )
	{	
		#debug DMAI( "RW: " $ Shooter );

		if( IsFacingTarget( ControllerEnemy, CosMinFacingTargetAngle ) && FRand() < 0.4 ) 
			return;

		Global.ShotFiredNotification( Shooter, FireDir, ProjectileClass, ProjSpeed );
	}

	//-------------------------------------------------------------------------

	function SetFall() //about to fall
	{
		#debug DMAI( "SetFall" );

		StopMovement( true, false );
		Destination = Pawn.Location; //!! what if NPC is jumping/falling to a destination -- shouldn't we keep Destination?
		Global.SetFall();
	}

	//-------------------------------------------------------------------------

	function StartFalling()
	{
		//!!mdf-tbd: shut movement down until landed?
		GotoLabel( BeginLabel );
	}
	
	//-------------------------------------------------------------------------

	event bool NotifyHitWall( vector HitNormal, Actor Wall )
	{
		#debug DMAI( "NotifyHitWall" );

		if( Pawn.Physics != PHYS_Falling )
		{
			if( !ValidEnemy( ControllerEnemy ) )
			{
				UpdateEnemy();
			}
			else
			{
				if( bChangeDir || FRand() < 0.5 || ((ControllerEnemy.Location - Pawn.Location) dot HitNormal) < 0 )
				{
					Focus = ControllerEnemy;
				}
				else
				{
					bChangeDir = true;
					Destination = Pawn.Location - HitNormal * FRand() * 500;
				}
			}
		}

		return false;
	}

	//-------------------------------------------------------------------------

	function FearThisSpot( Actor aSpot )
	{
		#debug DMAI( "FearThisSpot" );

		Destination = Pawn.Location + 120 * Normal( Pawn.Location - aSpot.Location ); 
	}

	//-------------------------------------------------------------------------

	function eventEnemyNotVisible()
	{
		#debug DMAI( "eventEnemyNotVisible" );

		#debug   StopFiring( 0.2, SFI_Behavior, GetContext() );
		#release StopFiring( 0.2, SFI_Behavior );
		
		if( Aggressiveness > RelativeStrength( ControllerEnemy ) )
		{
			if( Pawn.FastTrace( ControllerEnemy.Location, GetLastEnemySeeingLocation() ) )
			{
				GotoLabel( RecoverEnemyLabel );
			}
			else
			{
				#debug   BehaviorController.Update( BC_EnemyNotVisible, GetContext() );
				#release BehaviorController.Update( BC_EnemyNotVisible );
			}
		}
		Disable( 'EnemyNotVisible' );
	}

	//-------------------------------------------------------------------------

	//!!mdf-tbd: pain volumes, gas grenades & such?
	function PawnIsInPain( PhysicsVolume PainVolume )
	{
		#debug DMAI( "PawnIsInPain -- GS AttackRetreat #4" );
		GotoState( AttackRetreatState ); //GS-tbd
	}

	/*-------------------------------------------------------------------------
	Choose a destination for the tactical move, based on aggressiveness and the
	tactical situation. Make sure destination is reachable.
	*/

	function PickDestination( bool bCanCharge )
	{
		local vector PickDir, EnemyDir, EnemyPart, X, Y, Z, MinDest;
		local Pawn CurrentEnemy;
		local Actor HitActor;
		local vector HitLocation, HitNormal, CollSpec;
		local float Aggression, EnemyDist, MinDist, StrafeSize, OptDist;
		local bool bSuccess, bNoReach;

		#debug DMAI( "PickDestination: " $ bCanCharge );

		CurrentEnemy = ControllerEnemy;
		
		if( !ValidEnemy( CurrentEnemy ) )
		{
			UpdateEnemy();
			return;
		}

		if( Orders == OrdersHold )
			bCanCharge = false;

		bChangeDir = false;
		if( Pawn.PhysicsVolume.bWaterVolume && !Pawn.bCanSwim && Pawn.bCanFly )
		{
			Destination = Pawn.Location + 75 * ( VRand() + vect(0,0,1) );
			Destination.Z += 100;
			return; //!!mdf-tbd no reachability check
		}
		if( CurrentEnemy.PhysicsVolume.bWaterVolume )
			bCanCharge = bCanCharge && Pawn.bCanSwim;
		else 
			bCanCharge = bCanCharge && (Pawn.bCanFly || Pawn.bCanWalk);

		EnemyDist = VSize( Pawn.Location - CurrentEnemy.Location );

		bSuccess = false;
		if( (bSniping || Orders == OrdersHold) /*!!mdf && PriorityObjective() == 0 */ )
			bCanCharge = false;

		Aggression = 2 * ( U2PBasic.CombatStyle + FRand() ) - 1.1;
		if( CurrentEnemy.IsPlayerPawn() && ( GetReactionToEnemy( CurrentEnemy ) == REACTION_Fear ) && ( U2PBasic.CombatStyle > 0 ) )
			Aggression = Aggression - 2 - 2 * U2PBasic.CombatStyle;

		//DMTNS( "Base Aggression: " $ Aggression );
		
		// adjust Aggression based on attack capabilities
		if( !IsPreparedToAttack( true ) )
		{
			//DMTNS( "  not prepared to attack -- Aggression += 2  * StyleRunAway" );
			Aggression += 2 * StyleRunAway;
		}
		else
		{
			// mdf-tbd: 2nd parameter should be passed the likely use (fire/altfire) for the attack.
			// but we pbly don't want to call RateSelf here (slow & might not get same result as
			// when shot is actually fired. It might make sense if we simply call RateSelf/
			// SwitchToBestWeapon periodically in a timer and squirrel away relevant info such
			// as what those calls returned and the time at which they were last called
			Aggression += GetAttackStyle( CurrentEnemy );
		}

		// adjust Aggression based on enemy's attack capabilities
		Aggression += 2 * CurrentEnemy.Controller.GetDefenseStyle( Pawn );

		// mdf-tbd: in some cases should really be going to a "runaway" state

		if( EnemyDist > 1000 )
		{
			//DMTNS( "  boosting Aggression by 1" );
			Aggression += 1;
		}
			
		if( bCanCharge )
			bCanCharge = ( Aggression >= FRand() );

		if( ( Pawn.Physics == PHYS_Walking ) || ( Pawn.Physics == PHYS_Falling ) )
		{
			if( Pawn.Location.Z > CurrentEnemy.Location.Z + 150 ) //tactical height advantage
			{
				//DMTNS( "  tactical height advantage" );
				Aggression = FMax( 0.0, Aggression - 1.0 + U2PBasic.CombatStyle );
			}
			else if( Pawn.Location.Z < CurrentEnemy.Location.Z - Pawn.CollisionHeight ) // below enemy
			{
				if( EnemyDist < (1.1 * (CurrentEnemy.Location.Z - Pawn.Location.Z)) && !ActorReachable( CurrentEnemy ) ) 
				{
					bNoReach = true;
					//DMTNS( "  can't reach enemy -- reducing Aggression" );
					Aggression = -1.5 * FRand();
				}
			}
		}

		if( UseTacticalJumps() )
		{
			GetAxes( Rotation, X, Y, Z );

			if( FRand() < 0.5 )
			{
				Y *= -1;
				TryToDodge( Y, false );
			}
			else
				TryToDodge( Y, true );
		}
				
		if( ((CurrentEnemy.Velocity - Pawn.Velocity) dot (CurrentEnemy.Location - Pawn.Location)) > 0 )
		{
			//DMTNS( "  boosting Aggression by up to 0.4" );
			Aggression += 0.4 * FRand();
		}
		
		//DMTNS( "  final Aggression: " $ Aggression );
			 
		EnemyDir = (CurrentEnemy.Location - Pawn.Location)/EnemyDist;
		if( U2PBasic.bJumpy )
			MinDist = 160;
		else
			MinDist = FMin( 160.0, 3*Pawn.CollisionRadius );
		OptDist = 80 + FMin( EnemyDist, 250 * ( FRand() + FRand() ) );  
		Y = EnemyDir cross vect(0,0,1);
		if( Pawn.Physics == PHYS_Walking )
		{
			Y.Z = 0;
			EnemyDir.Z = 0;
		}
		else 
			EnemyDir.Z = FMax( 0, EnemyDir.Z );

		StrafeSize = FMax( -0.7, FMin( 0.85, ( 2 * Aggression * FRand() - 0.3 ) ) );
		EnemyPart = EnemyDir * StrafeSize;
		StrafeSize = FMax( 0.0, 1 - Abs( StrafeSize ) );
		// mdf-tbd: fix? Y not normalized above?
		//PickDir = StrafeSize * Y;
		PickDir = StrafeSize * Normal( Y );
		if( bStrafeDir )
			PickDir *= -1;
		bStrafeDir = !bStrafeDir;
		CollSpec.X = Pawn.CollisionRadius;
		CollSpec.Y = Pawn.CollisionRadius;
		CollSpec.Z = FMax( 6, Pawn.CollisionHeight - 18 );
		
		MinDest = Pawn.Location + MinDist * ( PickDir + EnemyPart );
		HitActor = Pawn.Trace( HitLocation, HitNormal, MinDest, Pawn.Location, false, CollSpec );
		if( HitActor == None )
		{
			bSuccess = ( Pawn.Physics != PHYS_Walking );
			if( !bSuccess )
			{
				CollSpec.X = FMin( 14, 0.5 * Pawn.CollisionRadius );
				CollSpec.Y = CollSpec.X;
				HitActor = Pawn.Trace( HitLocation, HitNormal, MinDest - (18 + Pawn.MaxStepHeight) * vect(0,0,1), MinDest, false, CollSpec );
				bSuccess = ( HitActor != None );
			}
			if( bSuccess )
				Destination = MinDest + ( PickDir + EnemyPart ) * OptDist;
		}
	
		if( !bSuccess )
		{					
			CollSpec.X = Pawn.CollisionRadius;
			CollSpec.Y = Pawn.CollisionRadius;
			MinDest = Pawn.Location + MinDist * ( EnemyPart - PickDir ); 
			HitActor = Pawn.Trace( HitLocation, HitNormal, MinDest, Pawn.Location, false, CollSpec );
			if( HitActor == None )
			{
				bSuccess = ( Pawn.Physics != PHYS_Walking );
				if( !bSuccess )
				{
					CollSpec.X = FMin( 14, 0.5 * Pawn.CollisionRadius );
					CollSpec.Y = CollSpec.X;
					HitActor = Pawn.Trace( HitLocation, HitNormal, MinDest - (18 + Pawn.MaxStepHeight) * vect(0,0,1), MinDest, false, CollSpec );
					bSuccess = ( HitActor != None );
				}
				if( bSuccess )
					Destination = MinDest + ( EnemyPart - PickDir ) * OptDist;
			}
			else 
			{
				if( ( U2PBasic.CombatStyle <= 0 ) || ( CurrentEnemy.IsPlayerPawn() && ( GetReactionToEnemy( CurrentEnemy ) == REACTION_Fear ) ) )
					EnemyPart = vect(0,0,0);
				else if( ( EnemyDir dot EnemyPart ) < 0 )
					EnemyPart = -1 * EnemyPart;
				PickDir = Normal( EnemyPart - PickDir + HitNormal );
				MinDest = Pawn.Location + MinDist * PickDir;
				CollSpec.X = Pawn.CollisionRadius;
				CollSpec.Y = Pawn.CollisionRadius;
				HitActor = Pawn.Trace( HitLocation, HitNormal, MinDest, Pawn.Location, false, CollSpec );
				if( HitActor == None )
				{
					bSuccess = ( Pawn.Physics != PHYS_Walking );
					if( !bSuccess )
					{
						CollSpec.X = FMin( 14, 0.5 * Pawn.CollisionRadius );
						CollSpec.Y = CollSpec.X;
						HitActor = Pawn.Trace( HitLocation, HitNormal, MinDest - (18 + Pawn.MaxStepHeight) * vect(0,0,1), MinDest, false, CollSpec );
						bSuccess = ( HitActor != None );
					}
					if( bSuccess )
						Destination = MinDest + PickDir * OptDist;
				}
			}	
		}
					
		if( bSuccess )
		{
			// mdf-tbd: should !NeedToTurn test go into || (has X || Y && Z currently)?
			if( U2PBasic.bJumpy || 
				(TrySplashDamageAttack() && 
				 (FRand() < 0.1 + 0.8 * GetSkill()) && 
				 (CurrentEnemy.Location.Z - CurrentEnemy.CollisionHeight <= Pawn.Location.Z + Pawn.MaxStepHeight - Pawn.CollisionHeight)) && 
				!NeedToTurn( CurrentEnemy.Location, NeedToTurnAngleCos ) )
			{
				if( (U2PBasic.bJumpy && FRand() < 0.75) || SplashJump() )
				{
					// try jump move
					Pawn.SetPhysics( PHYS_Falling );
					StopMovement( true, false );
					Destination = MinDest;
					return; 
				}
			}
			PickDir = ( Destination - Pawn.Location );
			EnemyDist = VSize( PickDir );
			if( EnemyDist > MinDist + 2 * Pawn.CollisionRadius )
			{
				PickDir = PickDir/EnemyDist;
				HitActor = Pawn.Trace( HitLocation, HitNormal, Destination + 2 * Pawn.CollisionRadius * PickDir, Pawn.Location, false );
				if( ( HitActor != None ) && ( ( HitNormal dot PickDir ) < -0.6 ) )
					Destination = HitLocation - 2 * Pawn.CollisionRadius * PickDir;
			}
		}
	}

	//-------------------------------------------------------------------------

	event BeginState()
	{
		if( !IsMobile() )
		{
			#debug DMAIA( " bailing from AttackTacticalMove state" );
			#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
			#release BehaviorController.Update( BC_AttackUpdate );
		}
		else
		{
			MinHitWall += 0.15;
			bAdjustFromWalls = false;
			if( Pawn != None )
			{
				Pawn.bAvoidLedges = true;
				Pawn.bStopAtLedges = true;
				Pawn.bCanWalkOffLedges = false;
				Pawn.bCanJump = false;
				Pawn.bCanStrafe = Pawn.default.bCanStrafe || U2PBasic.bCanStrafeDuringTacticalMoves;
			}
		}
		if( StationaryPawn(ControllerEnemy) != None )
			Enable( Event_SeeEnemy );
		else
			Disable( Event_SeeEnemy );
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		MinHitWall -= 0.15;
		bAdjustFromWalls = true;
		if( Pawn != None )
		{
			Pawn.bAvoidLedges = Pawn.default.bAvoidLedges;
			Pawn.bStopAtLedges = Pawn.default.bStopAtLedges;
			Pawn.bCanWalkOffLedges = Pawn.default.bCanWalkOffLedges;
			Pawn.bCanJump = (Pawn.JumpZ > 0);
			if( !Pawn.bCanStrafe )
			{
				// otherwise leftover velocity could cause NPC
				// to temporarily turn away from target in next state
				StopMovement( true, true );
			}
			RestoreCanStrafe();
		}
	}

	//-------------------------------------------------------------------------

@ TacticalTickLabel:
	Sleep( 0.02 );

@ BeginLabel:
@ MovePickDestLabel:
	Focus = ControllerEnemy;
	Destination = Focus.Location; //!!mdf-tbd: why set destination here?
	WaitForLanding();

	PickDestination( true ); // might change state
		
@ MoveActiveLabel:
	// don't try tactical moves through XMP items
	if( Level.HasSpecialColliders() && Pawn.FastTrace( Destination, Pawn.Location ) )
	{
		UpdateTacticalMoveBehavior();
		Stop;
	}
	
	if( !Pawn.bCanStrafe )
	{
		//DMTNS( "looking at destination during move" ); 
		MoveToPoint( Destination );
	}
	else
	{
@ MoveActiveStrafeLabel:
		//DMTNS( "looking at enemy during move" ); 
		MoveToPoint( Destination, , ControllerEnemy );	
	}

	if( !ValidEnemy( ControllerEnemy ) )
	{
		UpdateEnemy();
	}
	else if( !LineOfSightTo( ControllerEnemy ) )
	{
		if( Pawn.FastTrace( ControllerEnemy.Location, GetLastEnemySeeingLocation() ) )
		{
			Goto( RecoverEnemyLabel );
		}
		else
		{
			#debug   BehaviorController.Update( BC_EnemyNotVisible, GetContext() );
			#release BehaviorController.Update( BC_EnemyNotVisible );
		}
	}

@ DontCloseLabel:
	Focus = ControllerEnemy;
	Destination = ControllerEnemy.Location; //!!mdf-tbd: and here
	WaitForLanding();

	PickDestination( false ); // might change state
		
	Goto( MoveActiveLabel );

@ RecoverEnemyLabel:
	HidingSpot = Pawn.Location;

	Destination = GetLastEnemySeeingLocation() + 4 * Pawn.CollisionRadius * Normal( GetLastEnemySeeingLocation() - Pawn.Location );
	// don't try tactical moves through XMP items
	if( Level.HasSpecialColliders() && Pawn.FastTrace( Destination, Pawn.Location ) )
	{
		UpdateTacticalMoveBehavior();
		Stop;
	}
	//DMTNS( "recover enemy move" ); 
	MoveToPoint( Destination, , ControllerEnemy );

	if( CanFire( false ) && IsPreparedToFire( true ) && LineOfSightTo( ControllerEnemy ) )
	{
		// mdf-tbd: cleanup this mess -- Focus should be handled already in FireAt -- look at all cases like this
		Focus = ControllerEnemy;
		StopMovement( true, false );

		if( SplashDamageAttack() )
		{
			//mdf-tbd: stop firing?
			Sleep( 0.2 );
		}
		else
		{
			Sleep( 0.35 + 0.3 * FRand() );
		}

		if( ( FRand() + 0.1 > U2PBasic.CombatStyle ) )
		{
			Enable( Event_EnemyNotVisible );
			Destination = HidingSpot + 4 * Pawn.CollisionRadius * Normal( HidingSpot - Pawn.Location );
			Goto( MoveActiveLabel );
		}
	}

	Goto( MovePickDestLabel );
} // AttackTacticalMoveState

//-----------------------------------------------------------------------------

state @ AttackTacticalMoveMeleeState extends @ AttackTacticalMoveState
{
	ignores HearNoise, NotifyBump, SeeFriend, SeeOther, SeeAlertFriend;
	
	function UpdateTacticalMoveBehavior()
	{
		if( ControllerEnemy != None && CheckMeleeAttackRange( ControllerEnemy ) )
		{
			#debug   BehaviorController.Update( BC_MeleeUpdate, GetContext() );
			#release BehaviorController.Update( BC_MeleeUpdate );
		}
		else
		{
			Super.UpdateTacticalMoveBehavior();
		}
	}
}

//-----------------------------------------------------------------------------
// Retreat to a location while facing enemy.

state @ AttackTacticalRetreatState extends @ AttackTacticalMoveState
{
	ignores HearNoise, NotifyBump, SeeFriend, SeeOther, SeeAlertFriend;

	//-------------------------------------------------------------------------

	function UpdateRetreatBehavior()
	{
		//DMTNS( "AttackTacticalRetreatState.UpdateRetreatBehavior" );
		#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
		#release BehaviorController.Update( BC_AttackUpdate );
	}
	
	//-------------------------------------------------------------------------

	function PickDestination( bool bCanCharge )
	{
		local vector RetreatDir, TargetLocation;
		local float RetreatDistance;
		local bool bTryLeftNext, bSuccess;
		local vector HitLocation, HitNormal;
		local Actor HitActor;
		local int i;

		if( !ValidEnemy( ControllerEnemy ) )
		{
			UpdateEnemy();
			return;
		}

		RetreatDistance = U2PBasic.MaxTacticalRetreatDistance - VSize( StateStartLocation - Pawn.Location );
		if( RetreatDistance <= 10.0 )
		{
			UpdateRetreatBehavior();
			return;
		}

		bTryLeftNext = (FRand() < 0.50 );			
		RetreatDir = Pawn.Location - ControllerEnemy.Location;
		if( Pawn.Physics == PHYS_Walking )
			RetreatDir.Z = 0;
		RetreatDir = Normal( RetreatDir );

		//!!mdf-tbd: make using a random vector an option
		//!!mdf-tbd: check for blocking pawns also?			
        for( i=0; i<3 && !bSuccess; i++ )
		{
			//RetreatDir =  Pawn.Location + RetreatDistance * vector(rotator(RetreatDir) + rotator(RandomSpreadVector( 90.0 )) );
			//TargetLocation = Pawn.Location + RetreatDistance * RetreatDir;

			if( i == 0 )
			{
				// try straight back
				//DMTNS( "back" );
				TargetLocation = Pawn.Location + RetreatDistance*RetreatDir;
				//AddArrow( Pawn.Location, TargetLocation, ColorPink() );
			}
			else if( bTryLeftNext )
			{
				// try left
				//DMTNS( "left" );
				TargetLocation = Pawn.Location + RetreatDistance*Normal( RetreatDir cross vect(0,0,1) );
				bTryLeftNext = false;
			}
			else
			{
				// try right
				//DMTNS( "right" );
				TargetLocation = Pawn.Location + RetreatDistance*Normal( vect(0,0,1) cross RetreatDir );
				bTryLeftNext = true;
			}
			
			class'UtilGame'.static.AdjustDestinationForPhysics( Pawn, TargetLocation );

			if( Pawn.FitActorAt( TargetLocation ) != 0 )
			{
				//AddActorAt( Pawn, TargetLocation, ColorPink() );
				bSuccess = PointReachable( TargetLocation );
			}
		}
		
		if( bSuccess )
		{
			//AddArrow( Pawn.Location, TargetLocation );
			Destination = TargetLocation;
		}
		else
		{
			#debug DMAI( "AttackTacticalRetreatState.PickDestinaion -- couldn't find a backoff destination" );
			UpdateRetreatBehavior();
			Destination = Pawn.Location;
		}
	}

	//-------------------------------------------------------------------------

	event BeginState()
	{
		Super.BeginState();
		
		Pawn.bCanStrafe = Pawn.default.bCanStrafe || U2PBasic.bCanStrafeDuringTacticalRetreat;
		
		if( ControllerEnemy != None )
			StateStartLocation = ControllerEnemy.Location;
		else
			StateStartLocation = Pawn.Location;
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		Super.EndState();
		
		if( Pawn != None )
		{
			if( !Pawn.bCanStrafe )
			{
				// otherwise leftover velocity could cause NPC
				// to temporarily turn away from target in next state
				StopMovement( true, true );
			}
			RestoreCanStrafe();
		}
	}
	
	//-------------------------------------------------------------------------

@ BeginLabel:
@ MovePickDestLabel:
	WaitForLanding();
	PickDestination( true ); // might change state
	
@ MoveActiveLabel:
	// don't try tactical moves through XMP items
	if( Level.HasSpecialColliders() && Pawn.FastTrace( Destination, Pawn.Location ) )
	{
		#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
		#release BehaviorController.Update( BC_AttackUpdate );
		UpdateRetreatBehavior();
		Stop;
	}
	MoveToPoint( Destination, , ControllerEnemy );
	if( MoveResult == MR_DestinationReached )
		UpdateRetreatBehavior();
	
	Goto( MovePickDestLabel );
	//#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
	//#release BehaviorController.Update( BC_AttackUpdate );
} // AttackTacticalRetreatState

//-----------------------------------------------------------------------------

state @ AttackTacticalRetreatMeleeState extends @ AttackTacticalRetreatState
{
	ignores HearNoise, NotifyBump, SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend;

	function UpdateRetreatBehavior()
	{
		//DMTNS( "AttackTacticalRetreatMeleeState.UpdateRetreatBehavior" );
		if( ControllerEnemy != None && CheckMeleeAttackRange( ControllerEnemy ) )
		{
			#debug   BehaviorController.Update( BC_MeleeUpdate, GetContext() );
			#release BehaviorController.Update( BC_MeleeUpdate );
		}
		else
		{
			Super.UpdateRetreatBehavior();
		}
	}
}

//-----------------------------------------------------------------------------

state @ AttackTauntState extends @ AcquisitionState
{
	ignores BeginFalling, EnemyInLeapRange, NotifyLanded; 

	function PlayRandomSound();

	//-------------------------------------------------------------------------

	event BeginState()
	{
		if( Pawn.Health < 0.60 * Pawn.default.Health )
		{
			#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
			#release BehaviorController.Update( BC_AttackUpdate );
		}
		else		
		{
			Super.BeginState();
		}
	}
	
	//-------------------------------------------------------------------------

@ PostBeginLabel:
	//DMTNS( "Finished rotating, sleeping for " $ U2PBasic.MinAcquisitionDelay - (Level.TimeSeconds - LastAcquireTime) $ " secs" );
	Sleep( U2PBasic.MinAcquisitionDelay - (Level.TimeSeconds - LastAcquireTime) );

	// tbd: separate properties for controlling taunts?	
	U2PBasic.HandleAcquireEnemySound();
	if( FDecision( U2PBasic.TauntAnimationOdds ) )
	{
		StopMovement( true, true );
		//DMTNS( "TAUNT!" );
		Sleep( SetSpecialAnim( 'U2_Taunt',  true ) );
		//Sleep( U2PBasic.PostAcquisitionAnimationDelay );
	}
	#debug   UpdateBehavior( false, GetContext() );
	#release UpdateBehavior( false );
} // AttackTauntState

//-----------------------------------------------------------------------------

state @ CantMoveState
{
@ BeginLabel:
	Stop;
}

/*-----------------------------------------------------------------------------
NPC stops moving and plays a cowering animation forever.
*/

state @ CoweringState
{
	ignores BeginFalling, SeeEnemy, SeeFriend, SeeAlertFriend, SeeOther, NotifyBump, HearNoise, EnemyNotVisible; 
	ignores NotifyLanded, DamageAttitudeTo, EnemyInLeapRange, EnemyInMeleeRange, NotifyHitWall;

	function PlayRandomSound();

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest ) { return false; }
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		StopMovement( true, false );
		#debug   StopFiring( 0.5, SFI_Behavior, GetContext() );
		#release StopFiring( 0.5, SFI_Behavior );
		BehaviorController.SetBCEnabled( false );
		Pawn.MeshAgentSetInputCurValue( 'specialstate', 'cower' );
		Pawn.MeshAgentSetInputLock( 'specialstate', true );
		AgentSpecialStateBegin();
	}

	//-------------------------------------------------------------------------

	event EndState()
	{
		if( Pawn != None )
			Pawn.MeshAgentSetInputLock( 'specialstate', false );
		AgentSpecialStateEnd();
		CheckBehaviorEnabled();
	}
			
	//-------------------------------------------------------------------------
	
@ BeginLabel:
@ TurnLabel:
	if( ControllerEnemy != None && NeedToTurn( ControllerEnemy.Location, NeedToTurnAngleCos ) )
	{
		Focus = ControllerEnemy;
		FocalPoint = ControllerEnemy.Location + vect(0,0,1) * ControllerEnemy.BaseEyeHeight;
		FinishRotation( DefaultRotationThreshold );
		Focus = None;
		FocalPoint = Pawn.Location + 256*vector(Pawn.Rotation);
    }
   	Sleep( 1.0 );
	Goto( TurnLabel );	
	
/* !!mdf-tbd: currently no way to get out of cowering	
@ StopCoweringLabel:	
	#debug   UpdateBehavior( true, GetContext() );
	#release UpdateBehavior( true );
*/		
} // CoweringState

//-----------------------------------------------------------------------------

state @ DeadLockedState
{
	ignores HearNoise, NotifyBump, SeeFriend, SeeOther, SeeAlertFriend;

@ BeginLabel:	
	Sleep( 0.1 );
	#debug   UpdateBehavior( false, GetContext() );
	#release UpdateBehavior( false );
} // DeadLockedState

//-----------------------------------------------------------------------------

state @ DodgingState
{
	ignores BeginFalling, SeeEnemy, SeeFriend, SeeAlertFriend, SeeOther, NotifyBump, HearNoise, EnemyNotVisible; 
	ignores NotifyLanded, DamageAttitudeTo, EnemyInLeapRange, EnemyInMeleeRange, NotifyHitWall;

	//-------------------------------------------------------------------------

	function PlayRandomSound();
	function bool CanDodge( optional bool bIgnoreFalling ) { return false; }
	function bool CanFire( bool bTest ) { return ( bDodgeFinished && Global.CanFire( bTest ) ); }
	function HandlePanic() { if( bDodgeFinished ) Global.HandlePanic(); }
	function HandleIncoming( Actor IncomingActor, vector IncomingDirection, float IncomingSpeed );
	function EnemyAcquired();
	
	//-------------------------------------------------------------------------

	function ReflectNotify( name NotifyName )
	{
		if( NotifyName == StayNotify )
		{
			if( U2PBasic.DodgeTime <= 0.0 )
				U2PBasic.DodgeTime = Level.TimeSeconds - StartDodgeTime;
			GotoLabel( DodgeFinishedLabel );
		}
		else
		{
			Super.ReflectNotify( NotifyName );
		}
	}

	//-------------------------------------------------------------------------

	function float GetDodgeSpeed()
	{
		local float DodgeDistance;
		local float RawDodgeSpeed;
		 
		DodgeDistance = VSize( U2PBasic.DodgeDestination - Pawn.Location );
		RawDodgeSpeed = DodgeDistance / Abs(U2PBasic.DodgeTime);
		
		//DMTNS( "DodgeDistance: " $ DodgeDistance );
		//DMTNS( "DodgeTime:     " $ U2PBasic.DodgeTime );
		//DMTNS( "RawDodgeSpeed: " $ RawDodgeSpeed );
		//DMTNS( "DodgeSpeed:    " $ RawDodgeSpeed / Pawn.GroundSpeed );
		return ( RawDodgeSpeed / Pawn.GroundSpeed );
	}

	//-------------------------------------------------------------------------

	event BeginState()
	{
		//DMTNS( "BeginState flipping Physics: " $ EnumStr( enum'EPhysics', Pawn.Physics ) $ " Velocity: " $ Pawn.Velocity );
		bDodgeFinished = false;
		EnableRotation( false );
		U2P.bIgnoreImpactForces = true;
		U2P.bCanKnockDown = false;
		BehaviorController.SetBCEnabled( false );
		StartDodgeTime = Level.TimeSeconds;
	}

	//-------------------------------------------------------------------------

	event EndState()
	{
		//DMTNS( "EndState" );
		EnableRotation( true );
		UnlockAnimationController( true );
		if( U2P != None )
		{
			//DMTNS( "  flipping Physics: " $ EnumStr( enum'EPhysics', U2P.Physics ) $ " Velocity: " $ U2P.Velocity $ " Speed: " $ VSize( U2P.Velocity ) );
			U2P.bIgnoreImpactForces = U2P.default.bIgnoreImpactForces;
			U2P.bCanKnockDown = U2P.default.bCanKnockDown;
		}
		CheckBehaviorEnabled();
	}
			
	//-------------------------------------------------------------------------

@ BeginLabel:
	//DMTNS( "BeginLabel" );
	if( U2PBasic.bJumpDodges )
	{
		//DMTNS( "doing a jump dodge" );
		// abort if NPC isn't falling or doesn't have right velocity (might happen if takes damage)
		if( Pawn.Physics != PHYS_Falling || Pawn.Velocity.Z <= 0 || VSize(Pawn.Velocity) < 70 )
		{
			//mdf-tbd: this would kill momentum xfer if NPC hit as about to dodge and resulting velocity isn't right
			Pawn.Velocity = vect(0,0,0);
			Goto( DoneLabel );
		}

		// velocity launched, just wait for the dodge animation to finish
		FinishAnim();
	}
	else
	{
		//DMTNS( "doing a roll dodge" );
		// dodge along the ground, use MoveToPoint
		
		//AddCylinder( U2PBasic.DodgeDestination, Pawn.CollisionRadius, Pawn.CollisionHeight, ColorBlue() );
		//DMTNS( "Moving " $ VSize( Pawn.Location - U2PBasic.DodgeDestination ) $ " units at speed of: " $ GetDodgeSpeed() );
		MoveToPoint( U2PBasic.DodgeDestination, , , GetDodgeSpeed() );
		//DMTNS( "MoveToPoint returned -- " $ VSize( Pawn.Location - U2PBasic.DodgeDestination ) $ " units from destination" );
	}

@ DodgeFinishedLabel:
	//DMTNS( "DodgeFinishedLabel" );
	if( U2P != None )
		U2P.LandedOnTexture( 500.0 );
		
	StopMovement( true, true ); // make sure movement stopped?
	bDodgeFinished = true;
	EnableRotation( true );
	
	// turn to enemy (if any)
	StartTurnTime = Level.TimeSeconds;
	Focus = ControllerEnemy;
	if( Focus != None )
	{
		if( NeedToTurn( Focus.Location, NeedToTurnAngleCos ) )
			FinishRotation( DefaultRotationThreshold );
	}
	else
	{
		FocalPoint = Pawn.Location + 256.0*vector(Pawn.Rotation);
	}
	
	Sleep( U2PBasic.PostDodgeDelay - (Level.TimeSeconds - StartTurnTime) );
	MaybeFire( 0 ); // alt fire too?

@ DoneLabel:
	#debug   UpdateBehavior( true, GetContext() );
	#release UpdateBehavior( true );
} // DodgingState

//-----------------------------------------------------------------------------

state @ EnemyKilledState
{
	ignores EnemyNotVisible; 

	//-------------------------------------------------------------------------
		
	event BeginState()
	{
		Super.BeginState();
		SetAlertness( -0.3 );
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		RestoreAlertness();
		Super.EndState();
	}
} // EnemyKilledState

//-----------------------------------------------------------------------------

state @ FindAirState
{
	ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise, NotifyBump;

	//-------------------------------------------------------------------------
	// NOTE: NotifyHeadVolumeChange appears to not be implemented currently --
	// its not being called anywhere. HeadVolumeChange *is* still being called 
	// (on the Pawn...)

	event bool NotifyHeadVolumeChange( PhysicsVolume NewHeadVolume )
	{
		Global.NotifyHeadVolumeChange( NewHeadVolume );
		if ( !NewHeadVolume.bWaterVolume )
		{
			#debug   UpdateBehavior( false, GetContext() );
			#release UpdateBehavior( false );
		}
		return false;
	}

	//-------------------------------------------------------------------------

	function eventEnemyNotVisible()
	{
		////log("enemy not visible");
		//mdf-tbd: tell BC?
	}

	//-------------------------------------------------------------------------

@ MoveDoneLabel:	
	#debug   UpdateBehavior( false, GetContext() );
	#release UpdateBehavior( false );
} // FindAirState

//-----------------------------------------------------------------------------
// Can't move, can't shoot, can't rotate/aim, not moved by damage.

state @ FrozenState
{
	ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise, EnemyInLeapRange, EnemyInMeleeRange;
	
	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest )	{ return false; }

	//-------------------------------------------------------------------------

	event BeginState()
	{
		if( BehaviorController != None )
			BehaviorController.SetBCEnabled( false );
		Super.BeginState();
		Focus = None;
	}

	//-------------------------------------------------------------------------

	event EndState()
	{
		CheckBehaviorEnabled();
		Super.EndState();
	}
} // FrozenState

//-----------------------------------------------------------------------------

state @ GameEndedState
{
	function PlayRandomSound();

	//-------------------------------------------------------------------------
	// Changing orders could result in a state change.

	function bool SetOrders( optional name NewOrders, optional Actor NewOrdersObject, optional float NewOrdersThreshold, optional Object NewOrderGiver, optional bool bAcknowledge );
} // GameEndedState

//-----------------------------------------------------------------------------

state @ HandleInvalidLandingState
{
	ignores EnemyNotVisible, HearNoise, NotifyBump, SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend; // sensory input
	ignores BeginFalling, NotifyLanded, NotifyHitWall, NotifyHeadVolumeChange, NotifyPhysicsVolumeChange; // physics
	ignores ShotFiredNotification;
	ignores DamageAttitudeTo, EnemyInLeapRange, EnemyInMeleeRange;

	//-------------------------------------------------------------------------
	
	function EnemyAcquired();

	//-------------------------------------------------------------------------

	function HandledInvalidLanding()
	{
		#debug   UpdateBehavior( true, GetContext() );
		#release UpdateBehavior( true );
	}
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		BehaviorController.SetBCEnabled( false );
		Super.BeginState();
	}

	//-------------------------------------------------------------------------
	
	event EndState()
	{
		Super.EndState();
		CheckBehaviorEnabled();
	}
} // HandleInvalidLandingState

//-----------------------------------------------------------------------------
// NPC wants to (or has been ordered to) "hold" some location (OrdersObject).
// This state makes sure the NPC is close enough to this location at which 
// point NPC will transition to HoldingState. This is done without checking
// for LineOfSight to the Hold location (mdf-tbd: this seems like it has 
// potential for being a bug if the Hold location is on the other side of a
// wall for example)?

state @ HoldState
{
	//-------------------------------------------------------------------------

	function FearThisSpot( Actor aSpot )
	{
		#debug DMAIA( "FearThisSpot sending NPC to wandering state" );
		Destination = Pawn.Location + 120 * Normal( Pawn.Location - aSpot.Location ); 
		GotoState( WanderingState, MoveActiveLabel ); //GS-tbd
	}

	//-------------------------------------------------------------------------
	
	function HandleHoldAtDestination(); // refactoring hack
	
	//-------------------------------------------------------------------------

	function PickDestination()
	{
		local Actor HA;

		HA = GetHoldActor();
				
		#debug DMAIA( "PickDestination - HA: " $ HA );

		if( HA == None )
		{
			#debug DMAI( "PickDestination -- HA isn't a HoldSpot -- might go freelancing???" );
			#debug DMAI( "SetOrders " $ GetContext() );
			if( !bStationary )
				SetOrders( OrdersNone );
			bStationary = false;
			GotoState( DefaultState ); //GS-tbd
		} 
		else if( AtDestinationActor( HA ) )
		{
			#debug DMAI( "PickDestination -- close to HA go to HoldingState" );
			HandleHoldAtDestination();
			GotoState( HoldingState, WavingLabel ); //GS-tbd (allow hold and holding to work together?)
		}
		else
		{
			#debug DMAI( "PickDestination -- finding a path to HA" );
			GetPathToActor( HA, MoveTarget, true );
			if( MoveTarget == None ) 
			{
				#debug DMAI( "no path -- clearing orders and going to default state " $ GetContext() );
				SetOrders( OrdersNone );
				GotoState( DefaultState ); //GS-tbd
			} 
		}
	}

	//-------------------------------------------------------------------------

@ BeginLabel:
@ MovePickDestLabel:
	WaitForLanding();
	PickDestination();

@ MoveActiveLabel:
	if( MoveTarget == None )
	{
		#debug DMAIM( "Hold -- no MoveTarget?" );
		StopMovement( true, false );
		Sleep( 0.1 );
		Goto( MovePickDestLabel );
	}

	// try to get within 8 units in call to MoveToActor, but PickDestination may decide destination reached before this
	#debug DMAIM( "Hold -- moving toward " $ MoveTarget );
	MoveToActor( MoveTarget, TMT_None, , HoldReachedDistance2D );
	Goto( MovePickDestLabel );
} // HoldState

//-----------------------------------------------------------------------------

/* 
mdf-tbd: currently requires that the NPC has been ordered to hold at some
OrdersObject. Could be useful for basic NPCs, but not through Orders and 
currently relies on Roaming state to sent NPC to hold/holding state (current
basic wandering state won't do this?
*/

state @ HoldingState
{
	//-------------------------------------------------------------------------

	event bool NotifyLanded( vector HitNormal )
	{
		SetPhysics( PHYS_None );
		return true;
	}

	//-------------------------------------------------------------------------

	function bool CheckHoldActor()
	{
		local Actor HA;

		HA = GetHoldActor();
		
		if( HA == None )
		{
			#debug DMAI( "give up hold" );
			#debug DMAI( "SetOrders " $ GetContext() );
			if( !bStationary )
				SetOrders( OrdersNone );
			bStationary = false;
		} 
		else if( HoldSpot(HA) != None )
		{
			HoldSpot(HA).Holder = Pawn;
		}
		
		return ( HA != None );
	}

	//-------------------------------------------------------------------------

	function SetFocus()
	{
		local Actor HA;

		HA = GetHoldActor();
		
		Focus = None;
		MoveTarget = None;
		FocalPoint = HA.Location + 1000 * vector(HA.Rotation);
	}
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		#debug   SetControllerEnemy( None, GetContext() );
		#release SetControllerEnemy( None );
		StopMovement( true, false );
		RestoreAlertness();
	}

	//-------------------------------------------------------------------------

	event EndState()
	{
		local Actor HA;
		
		if( !bStationary )
		{
			HA = GetHoldActor();
			ClearHoldSpot( HA );
		}
	}

	//-------------------------------------------------------------------------

@ BeginLabel:
	if( !CheckHoldActor() )
		GotoState( DefaultState ); //GS-tbd

@ WavingLabel:
	// mdf-tbd:
	if( bStationary && LPawn.GetStance() != StationaryStance )
	{
		//DMTN( "Setting stance to:" $ StationaryStance );
		LPawn.SetStance( StationaryStance );
	}
	//!!mdf-tbd: 
	//else 
		//have properties control odds of standing / crouching / going prone 

	// match holdspot's rotation if was ordered to it (stationary NPCs maintain their current rotation)
	// no -- just keep NPC in stakeout longer but once back to holding, restore rotation?
	SetFocus();
	//AddArrow( Pawn.Location, FocalPoint, ColorMagenta() );
	//Sleep( 2.5 ); replace with FinishRotation?
	FinishRotation( DefaultRotationThreshold );

	// Let NPC wander around once he reaches the holdspot (he'll periodically 
	// go back to it via hold/holding and this should be ok.
	if( IsMobile() )	
		GotoState( DefaultState );

	Stop;	
} // HoldingState

//-----------------------------------------------------------------------------
// Impaling attack behavior

state @ ImpalingState
{
	ignores BeginFalling, SeeEnemy, SeeFriend, SeeAlertFriend, SeeOther, NotifyBump, HearNoise, EnemyNotVisible; 
	ignores NotifyLanded, DamageAttitudeTo, EnemyInMeleeRange, NotifyHitWall/*, eventTakeDamage*/;

	//-------------------------------------------------------------------------

	function PlayRandomSound();
	function bool CanFire( bool bTest )	{ return false; } // mib-tbd: impaler shouldn't be shooting (allowable on unimpaling)
	function bool IsImpaling() { return true; }
	#debug   function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo, string ContextStr );
	#release function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo );
	function bool FaceTarget( float F ) { return false; }

	//-------------------------------------------------------------------------

	event Tick( float DeltaTime )
	{
		Super.Tick( DeltaTime );
		ControllerEnemy.UpdateMountPhysics();
	}
	
	//-------------------------------------------------------------------------
	
	function ImpaleAttackAbort()
	{
		ImpaleAttackAnimationAbort();
		if( ImpaleVictim != None )
			UnImpalePawn();
		#debug   BehaviorController.Update( BC_AttackUpdate, GetContext() );
		#release BehaviorController.Update( BC_AttackUpdate );
	}
	
	//-------------------------------------------------------------------------
	
	event EnemyNotInMeleeRange()
	{
		if( ImpaleVictim == None )
			ImpaleAttackAbort();
	}

	//-------------------------------------------------------------------------

	function HandleKnockDown()
	{
		ImpaleAttackAnimationAbort();
		Global.HandleKnockDown();
	}

	//-------------------------------------------------------------------------

	function ImpalePawn()
	{
		local U2PlayerController U2PC;
		
		ImpaleVictim = ControllerEnemy;

		//DMTNS( "ImpalePawn: " $ ImpaleVictim );

		if( !ValidEnemy( ImpaleVictim ) || !CheckMeleeAttackRange( ImpaleVictim ) )
		{
			ImpaleAttackAbort();
		}
		else
		{
			EnableRotation( false );
			ImpaleVictim.SetCollision( false, false, false );

			U2PC = U2PlayerController( ImpaleVictim.Controller );
			if( U2PC != None )
			{
				U2PC.NotifyImpaled();
				U2PC.ClientFlash( class'Fell'.default.FlashScale*20, class'Fell'.default.FlashFog*20 );
				class'UtilGame'.static.MakeShake( ImpaleVictim, ImpaleVictim.Location, 512, U2PBasic.ImpaleAttachShakeMag, U2PBasic.ImpaleAttachShakeSecs );
			}

			ImpaleMountVictim( ImpaleVictim );

			U2PBasic.MeleeDamageTarget( U2PBasic.ImpaleAttachDamage, 0.0, Class'DamageTypePhysical' );

			StopMovement( true, true );
			Focus = None;
		}
	}

	//-------------------------------------------------------------------------

	function ImpaleMountVictim( Pawn Victim )
	{
		Victim.MountOrgRotation=rot(0,32768,0);
		Victim.MountParentNode = U2PBasic.ImpaleMountNode;
		Victim.SetPhysics(PHYS_MovingBrush);
		if( Pawn.Weapon != None )
			Victim.MountSetParent(Pawn.Weapon);
		else
			Victim.MountSetParent(Pawn);
	}

	//-------------------------------------------------------------------------
	
	function ImpaleUnMountVictim( Pawn Victim )
	{
		Victim.MountOrgRotation=rot(0,0,0);
		Victim.MountOrgLocation=vect(0,0,0);
		Victim.MountParentNode = "";
		Victim.SetPhysics(PHYS_Falling);
		Victim.MountSetParent(None);
	}

	//-------------------------------------------------------------------------
	
	function ImpaleSetLaunchVector( Pawn Victim )
	{
		// get the orientation of the mount point I'm attached to
		//!! CDH (mib): replace with mount node rotation accessor
		local LookTarget MountDummy;

		if( Pawn != None )
		{
			MountDummy = Spawn( class'LookTarget', Self );
			MountDummy.MountParentNode = U2PBasic.ImpaleMountNode;
			MountDummy.SetPhysics( PHYS_MovingBrush );
			if( Pawn.Weapon != None )
				MountDummy.MountSetParent( Pawn.Weapon );
			else
				MountDummy.MountSetParent( Pawn );
			MountDummy.UpdateMountPhysics();
			Victim.Velocity = vector( MountDummy.Rotation );
			MountDummy.Destroy();
			MountDummy = None;
		}
	}

	//-------------------------------------------------------------------------

	function UnImpalePawn()
	{
		//DMTNS( "UnImpalePawn: " $ ImpaleVictim );
		if( ImpaleVictim != None )
		{
			if( U2PlayerController(ImpaleVictim.Controller) != None )
				U2PlayerController(ImpaleVictim.Controller).NotifyUnImpaled();

			ImpaleUnMountVictim( ImpaleVictim );
			ImpaleSetLaunchVector( ImpaleVictim );
			ImpaleVictim.Velocity = ImpaleVictim.Velocity * U2PBasic.ImpaleDetachMomentum;
			ImpaleVictim.SetCollision( true, true, true );
			EnableRotation( true );
			ImpaleVictim.bRotateToDesired = ImpaleVictim.default.bRotateToDesired;

			class'UtilGame'.static.MakeShake( ImpaleVictim, ImpaleVictim.Location, 512, U2PBasic.ImpaleDetachShakeMag, U2PBasic.ImpaleDetachShakeSecs );
			//U2PBasic.MeleeDamageTarget( U2PBasic.ImpaleDetachDamage, 0, Class'DamageTypePhysical' );
			U2PBasic.MeleeDamageTarget( U2PBasic.ImpaleDetachDamage, U2PBasic.ImpaleDetachMomentum, Class'DamageTypePhysical' );
			
			ImpaleVictim = None;
		}
		
		#debug   UpdateBehavior( true, GetContext() );
		#release UpdateBehavior( true );
	}

	//-------------------------------------------------------------------------

	event BeginState()
	{
		//#debug DMAIA( "Impaling BeginState" );
		// start the impale animation
		// we don't want to get yanked out of this state by the BC
		BehaviorController.SetMinTimeOutDelay( U2P.AnimationController.SpecialAnimationImpaleAttack() );
		BehaviorController.SetBCEnabled( false );
		StopMovement( true, true );
	}

	//-------------------------------------------------------------------------
	
	event EndState()
	{
		//DMTNS( "Impaling EndState" );
		UnImpalePawn();
		CheckBehaviorEnabled();
	}
} // ImpalingState
	
//-----------------------------------------------------------------------------

state @ KnockDownState
{
	ignores BeginFalling, SeeEnemy, SeeFriend, SeeAlertFriend, SeeOther, NotifyBump, HearNoise, EnemyNotVisible; 
	ignores NotifyLanded, DamageAttitudeTo, EnemyInLeapRange, EnemyInMeleeRange, NotifyHitWall;

	//-------------------------------------------------------------------------

	function PlayRandomSound();
	function bool CanFire( bool bTest ) { return false; }
	function bool CanDodge( optional bool bIgnoreFalling ) { return false; }
	function EnemyAcquired();
	function HandlePanic(); // make sure no panic until knockdown done (takes precendence)

	//-------------------------------------------------------------------------

	function float KnockDownAnim()
	{
		local float KnockDownTime;
		
		KnockDownTime = U2P.AnimationController.SpecialAnimationDamageKnockDown();
		if (KnockDownTime == 0.0)
		{
			DMTNS( "WARNING - no knockdown animation for " $ Pawn $ " AnimSequence: " $ Pawn.AnimSequence );
			KnockDownTime = 1.0;
		}
		
		return KnockDownTime;
	}
	
	//-------------------------------------------------------------------------

	function bool CanDoRagdollHit() { return false; }

	//-------------------------------------------------------------------------

	event BeginState()
	{
		//DMTNS( "BeginState Physics: " $ EnumStr( enum'EPhysics', Pawn.Physics ) $ " Velocity: " $ Pawn.Velocity $ " Health: " $ Pawn.Health );
		#debug   StopFiring( 0.5, SFI_Behavior, GetContext() );
		#release StopFiring( 0.5, SFI_Behavior );
		EnableRotation( false );
		BehaviorController.SetBCEnabled( false );
		LPawn.bSpecialHardLandings = false; // leaving this on can cause a state change, circumventing the knockdown anim below
	}

	//-------------------------------------------------------------------------

	event EndState()
	{
		//if( Pawn != None )
		//	DMTNS( "EndState Physics: " $ EnumStr( enum'EPhysics', Pawn.Physics ) $ " Velocity: " $ Pawn.Velocity $ " Health: " $ Pawn.Health );
		//else
		//	DMTNS( "EndState" );

		EnableRotation( true );
		UnlockAnimationController();
		if( LPawn != None )
			LPawn.bSpecialHardLandings = LPawn.default.bSpecialHardLandings;
		DodgeEnableTime = Level.TimeSeconds + 0.25;
		CheckBehaviorEnabled();
	}
			
	//-------------------------------------------------------------------------
	
@ BeginLabel:
	//DMTNS( "damage launch" );	
	U2P.AnimationController.SpecialAnimationDamageLaunch();
	//DMTNS( "wait for landing" );
	WaitForLanding();
	StopMovement( true, false );
	
	//DMTNS( "sleep 5.0" );
	//Sleep( 5.0 );
	//DMTNS( "KnockDownAnim" );	
	Sleep( KnockDownAnim() );
	#debug   UpdateBehavior( true, GetContext() );
	#release UpdateBehavior( true );
} // KnockDownState

//-----------------------------------------------------------------------------

state @ ScriptedState
{
	//-------------------------------------------------------------------------

	function EnemyAcquired()
	{
		// script might block reacting to enemy...
		AutoBegin( '', '' );
	}

	//-------------------------------------------------------------------------
	// If above call to AutoBegin is reflected back to this function then the
	// script is allowing the NPC to go autonomous.

	function eventAutoBegin( name DestinationState, name DestinationLabel )
	{
		#debug   BehaviorController.Update( BC_EnemyAcquired, GetContext() );
		#release BehaviorController.Update( BC_EnemyAcquired );
	}

	//-------------------------------------------------------------------------
	// mdf-tbd: how to handle blocking destinations like other Pawns etc.

	function eventBumpAll( Actor Other )
	{
		Super.eventBumpAll( Other );
		
		if( SpecialGoal != None && Other == SpecialGoal )
		{
			// If we bump the final destination generate a "destinationreached" event?
			
			//2002.11.23 !!mdf-tbd: don't spam avoid bump handling?
			//DMTNS( GetStateName() $ ": eventNotifyBump bumped SpecialGoal: " $ Other $ " time until ok to move: " $ NextScriptedMoveTime - Level.TimeSeconds );
			if( Level.TimeSeconds >= NextScriptedMoveTime )
				GotoLabel( ReachedDestinationLabel );
			/*OLD
			#debug DMAIM( GetStateName() $ ": eventNotifyBump bumped SpecialGoal -- jumping to ReachedDestination label: " $ Other );
			GotoLabel( ReachedDestinationLabel );
			*/
		}
		/*
		else if( (SpecialGoal != None) && VSize( Pawn.Location - MoveTarget.Location ) < 64.0 )
		{
			// bumped into something near movetarget -- pretend we reached it for now
			#debug DMAIM( GetStateName() $ ": eventNotifyBump bumped SpecialGoal -- jumping to ReachedDestination label: " $ Other );
			GL( ReachedDestinationLabel );
		}
		*/
	}

	//-------------------------------------------------------------------------

	function bool CanFire( bool bTest ) { return false; }
		
	//-------------------------------------------------------------------------

	function bool IsRepeatFire( bool bPrimary )
	{
		return ( GetSpecifiedFireRate( bPrimary ) <= U2Weapon.MaxRapidFireRate );
	}

	//-------------------------------------------------------------------------

	function MaybeFire( byte bUseAltMode )
	{
		bScriptPendingFire = false;
		
		#debug DMAIA( "MaybeFire: " $ bUseAltMode );
		if( IsPreparedToFire( true ) )
		{
			if( ControllerTarget == None || !NeedToTurn( ControllerTarget.Location, NeedToTurnAngleCos ) )
			{
				// tell script controller to start timing fire duration
				ScriptController.StartScriptedFiring();
	
				FireShot( bUseAltMode );
	
				#debug DMAIA( "MaybeFire: IsFiring(): " $ byte(IsFiring()) $ " (bFire=" $ bFire $ " bAltFire=" $ bAltFire $ ")" );
			}
			else
			{
				bScriptPendingFire = true;
				bScriptPendingFireUseAltMode = bUseAltMode;
				GotoLabel( TurnLabel );
				#debug DMAIA( "MaybeFire: NeedToTurn -- can't fire" );
			}
		}
		else
		{
			#debug DMAIA( "MaybeFire: not prepared for attack?" );
			#debug DMAIA( "  Weapon: " $ Pawn.Weapon );
			#debug DMAIA( "  IsPreparedToFire: " $ IsPreparedToFire( true ) );
		}
	}

	//-------------------------------------------------------------------------

	function HandleFinishedRotation()
	{
		if( bScriptPendingFire )
			GotoLabel( FireLabel );
		else
			Super.HandleFinishedRotation();
	}

	//-------------------------------------------------------------------------
	
	function StopFiringUpdate( float SuggestedFireAgainDelay )
	{
		// disabled when firing at a special target under script control?
		// no -- just always disable (special target doesn't have to be set)?
		//if( ControllerTarget == None )
		//	Global.StopFiringUpdate( SuggestedFireAgainDelay );
	}

	//-------------------------------------------------------------------------

	function Actor GetTarget()
	{
		// special target takes priority when under script control
		if( ControllerTarget != None )
			return ControllerTarget;
		else
			return ControllerEnemy;
	}

	//-------------------------------------------------------------------------

	function float TimeSinceTargetLastSeen( Actor TargetActor )
	{
		return 0.0;
	}
	
	//-------------------------------------------------------------------------

	function bool TryToHit( 
		Actor TargetActor, 
		float TargetDistance,
		float SpreadDegrees,
		bool bLOSToTarget, 
		float TryToHitBaseOddsMin, 
		float TryToHitBaseOddsMax, 
		float TryToHitBaseDistance, 
		float TryToHitMinMissDistance, 
		float TryToHitMaxHitDistance )
	{
		if( ScriptedAimOdds < 0.0 )
		{
			return Super.TryToHit( 
							TargetActor, 
							TargetDistance, 
							SpreadDegrees,
							bLOSToTarget, 
							TryToHitBaseOddsMin, 
							TryToHitBaseOddsMax, 
							TryToHitBaseDistance, 
							TryToHitMinMissDistance, 
							TryToHitMaxHitDistance );
		}
		else
		{
			return FDecision( ScriptedAimOdds );
		}
	}
	
	//-------------------------------------------------------------------------

	function bool ShouldTryToLead( Actor TargetActor, float TargetDistance, bool bTrySplash )
	{
		return true;
	}
	
	//-------------------------------------------------------------------------

	function bool TestAimLocation( vector ProjStart, float ProjSpeed, Actor TargetActor, vector AimLocation, float MaxMissDistance, bool bCanHitOtherPawns )
	{
		return true; // never fail to fire if firing under script control?
	}
	
	//-------------------------------------------------------------------------

	function bool AdjustAim( class<Projectile> ProjectileClass, float ProjSpeed, vector ProjStart, float WeaponFireSpread, bool bLeadTarget, bool bWarnTarget, bool bTossed, bool bTrySplash )
	{
		#debug DMAIA( "AdjustAim: " $ ControllerTarget );
		Global.AdjustAim( ProjectileClass, ProjSpeed, ProjStart, WeaponFireSpread, bLeadTarget, bWarnTarget, bTossed, bTrySplash );
		
		// always return true for scripted firing?
		return true;
	}

	//-------------------------------------------------------------------------

	event BeginState()
	{
		//DMTNS( "BeginState: clearing Enemy and OldEnemy" );
		// 2002.12.14 (mdf) if we are going scripted (e.g. no more enemy or
		// SetScript called with a new script), make *sure* any enemy(s) cleared
		// and shut down the behavior controller.
		#debug   SetControllerEnemy( None, GetContext() );
		#release SetControllerEnemy( None );
		OldControllerEnemy = None;
		UpdateEnemy( false );
		
		Super.BeginState();
	}
	
	//-------------------------------------------------------------------------

@ FireLabel:
	#debug DMAI( "FireLabel: " $ bScriptedIdleAnims );

	if( bScriptPendingFire )
	{
		MaybeFire( bScriptPendingFireUseAltMode );
		// mdf-this shouldn't be necessary (but it still seems to be for E3...)
		Sleep( 0.5 ); // mdf-tbr: FinishAnim not waiting?
		Goto( FireLabel );
	}

	if( Orders == OrdersFollow || Pawn(GetSpecialGoal()) != None )
	{
		Sleep( 1.5 );
		Goto( BeginLabel );
	}

	Stop;
} // ScriptedState

//-----------------------------------------------------------------------------

state @ TestMoveState
{
	ignores EnemyNotVisible;

	//-------------------------------------------------------------------------

	event BeginState()
	{
		Super.BeginState();
		SetOrdersObject( TestMoveTarget ); // so it shows up in the debug menu
	}
}
	
//-----------------------------------------------------------------------------

state @ WanderingState
{
	ignores EnemyNotVisible;

	//-------------------------------------------------------------------------

	function FearThisSpot( Actor aSpot )
	{
		Destination = Pawn.Location + 120 * Normal( Pawn.Location - aSpot.Location ); 
	}

	//-------------------------------------------------------------------------

	function float GetExtraWanderDistance()
	{
		local float OrderObjectDistance, MinDistance;
		local Actor ActualOrdersObject;
		
		if( Orders == OrdersFollow )
		{
			if( Controller(OrdersObject) != None )
				ActualOrdersObject = Controller(OrdersObject).Pawn;
			else
				ActualOrdersObject = OrdersObject;
			
			//!!mdf-tbd: orders shouldn't be handled in wandering (roaming?)
			OrderObjectDistance = VSize( Pawn.Location - ActualOrdersObject.Location );
			
			if( Pawn(ActualOrdersObject) != None )
				MinDistance = 256.0;
			else
				MinDistance = 32.0;
			
			if( OrderObjectDistance < MinDistance )
				return 0.0; // close enough?
			else
				return FMin( OrderObjectDistance - MinDistance, 200 + 6*Pawn.CollisionRadius );
		}
		else
		{
			return Super.GetExtraWanderDistance(); //!!mdf was: ( 450 + 12*Pawn.CollisionRadius );
		}
	}

	//-------------------------------------------------------------------------

	function SetWanderMoveSpeed()
	{
		if( OrdersObject != None )
			WanderMoveSpeed = 1.0;
		else
			Super.SetWanderMoveSpeed();
	}
	
	//-------------------------------------------------------------------------

	function bool ShouldWanderPause()
	{
		return ( OrdersObject == None && Super.ShouldWanderPause() );
	}
	
	//-------------------------------------------------------------------------
	
	function bool PickDestination()
	{
		local Actor LocalMoveTarget;
		
		if( OrdersObject != None )
			GetPathToActor( OrdersObject, LocalMoveTarget, true );
		
		if( LocalMoveTarget == None )
			return Super.PickDestination();
		
		Destination = LocalMoveTarget.Location;
		return true;
	}
} // WanderingState

//-----------------------------------------------------------------------------

state @ WanderingPanicState
{
	ignores BeginFalling, SeeEnemy, SeeFriend, SeeAlertFriend, SeeOther, NotifyBump, HearNoise, EnemyNotVisible; 
	ignores NotifyLanded, EnemyInLeapRange, EnemyInMeleeRange, NotifyHitWall;

	//-------------------------------------------------------------------------
	
	function EndPanic()
	{
		#debug   UpdateBehavior( true, GetContext() );
		#release UpdateBehavior( true );
		Global.EndPanic();
	}
	
	//-------------------------------------------------------------------------
	
	event BeginState()
	{
		BehaviorController.SetBCEnabled( false );
		Super.BeginState();
	}
	
	//-------------------------------------------------------------------------
	
	event EndState()
	{
		Super.EndState();
		CheckBehaviorEnabled();
	}
}
	
//-----------------------------------------------------------------------------

defaultproperties
{
	Aggressiveness=0.300000
	VerifyCoverRate=0.500000
	ExecuteOrdersThreshold=0.500000
	BehaviorControllerClass=Class'U2AI.BehaviorControllerBasic'
	DefaultAcquisitionState='Acquisition'
	DefaultDeadLockedState='DeadLocked'
	DefaultImmobileState='hold'
	DefaultImmobileAttackState='AttackStationary'
	MaxFallbackNoDetectTime=5.000000
	MaxHuntTime=30.000000
	LeapMinHitWallDelay=0.200000
	bProbeHearNoise=true
	bProbeNotifyBump=true
	bProbeEnemyInMeleeRange=true
	bProbeSeeEnemy=true
	CosMinFacingTargetAngle=0.866000
     UseReticleOnEvents(0)="UseReticleText"
     UseReticleOnEvents(1)="UseReticleCorners"
     UseReticleOnEvents(2)="UseReticleTopBars"
     ProximityReticleOnEvents(0)="ProximityReticleCorners"
     ProximityReticleOnEvents(1)="ProximityReticleTopBars"
}

Overview Package Class Source Class tree Glossary
previous class      next class frames      no frames
Class file time: sk 3-1-2016 10:38:44.000 - Creation time: sk 3-1-2016 10:48:42.968 - Created with UnCodeX