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

U2AIOld.U2NPCControllerBaseOld


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
//=============================================================================
// U2NPCControllerBaseOld.uc
// Created By: Steve Polge, Mike Fox
// Created On: 8/01/00
// $Author: Mfox $
// $Date: 12/17/02 8:33p $
// $Revision: 56 $
//=============================================================================

//NOTE (mdf): U2AIOld used for bot support only

class U2NPCControllerBaseOld extends U2NPCControllerShared
	config(User);

/*-----------------------------------------------------------------------------
Orders:

For the time being I'm keeping Orders support here so these can be used by both
advanced and basic creatures. Afaik, there will be no need for basic NPCs to
be ordered by the player, but internally, or through scripting, we may need to
use some of these:

Pbly need:
	follow:		designate one NPC as a leader and the others follow that one
	here:		used for testing
	hold:		stay in some general area
	none:		freelancing
	
Not sure:
	attack:		not applicable except for bots in team games?
	defend:		not applicable except for bots in team games?

Afaik, all of the ReplicationInfo stuff should be moved down to the bot code. 
Unless we are going to need to replicate order-related info for basic NPCs in 
multiplayer games, or if we want clients to be able to see the internal orders
for basic NPCs this should only be needed for bots (when players want to see
what their bot teammates' orders are). The PRI also contains a bunch of other
stuff related to players' scores etc. which should be totally irrelevant for
basic NPCs.

bIsPlayer BS:

Currently NPCs with !bIsPlayer:
	+have somewhat reduced ability to see other Pawns (tbd)
	+have somewhat reduced LOS checks (tbd)
	+won't show themselves to other non-players (fixed? and tbd)
	+won't be heard by other NPCs unless has a player enemy or tags match (tbd)
	+won't hear some sounds played through PlaySound
	+won't use R_PLAYERONLY paths (obsolete?)
	+have lower net priority (ok?)
	+can't be outside of the game world in some cases (ok?)

Ideally, this would only be set for real (human) players and bots but I 
currently have this set for advanced NPCs because:

	+these need to
		+be able to react to other NPCs, including monsters
		+should have good visibility checks

*/

/*-----------------------------------------------------------------------------
mdf-tbd:

Replacing all occurences of 'TeamCannon' (doesn't exist in U2 or UW) with
StationaryPawn -- see comments there for more info.

Keep here:
	Stationary Pawn code -- might want some Basic NPCs (e.g. Araknids) to be
	able to react to these (attack/avoid etc.) if they are smart enough.

Move to U2NPCControllerAdvancedOld:
	weapon code (add interface here, extend using weapon code in Advanced)

Move to U2NPCControllerBotOld:
	teamgame code
	anything bIsPlayer related (unless it should be generalized to base/advanced classes

+clean up timer mess

+bots would be more fun if they would choose somewhat randomly among weapons
 which have more or less the same AIRating. Currently one weapon will tend
 to completely dominate.

+really need code (especially if above done) so that bot will prefer to
 keep current selection (high odds initially, decreasing with time, 
 possibly according to success vs current enemy). Currently, bot often
 rapidly switching between alt/pri fire for example.


=== misc todo ===

+wtf is up with mesh offsets (see U2MarineLight in TestU2). The feet seem to 
be almost 16 units below the CC, with the head not poking out at all. -- 

Reference pose only?

=== Todo ===

Where did polyc go?

Orders: NPCs without PRI's will need to store RealOrders elsewhere in case, say, they go freelancing 
then want to return to their original Orders.

=== Misc ===

Should Triggers be placeable?

Can we adopt "Super" with an uppercase "S" as the standard -- of the 430 or so uses of this 
in the script code about 410 of these are using "Super" with only a few cases using "super".
This would make these always be syntax-colored correctly (currently the "standard" in 
usertype.dat uses "S"). Same for "Global"...

(I personally don't care which but since most of the existing cases are using Super...).

Same with self/Self (mostly using Self currently but lots of engine uses of self, so either
way is fine with me...).

=== Thoughts ===

We should really support team dm if possible (potentially not more than a day's work 
and provides a nice option).

Would be neat if NPCs could destroy pickups which they don't use (bPlayerOnly pickups etc.) but 
this would mean having support for damageable pickups and maybe showing damage with smoke. This
is pretty similar to how the translocator worked in UT.

Weapons should look at damage radius and determine "dangerous" distance from this
instead of hard-coding these (so that changes to the weapon/projectile properties
will automatically be taken into account).

+base controller supports dialog so non-weapon using NPCs (like the seagoat) can
be ordered

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

// state name consts exclusive to (old) U2AI
const AttackingState					= 'Attacking';				// master attack state -- decide what to do
const FallingState						= 'Falling';				// falling	
const TakeHitState						= 'TakeHit';				// reacting to taking a hit

// label name consts exclusive to (old) U2AI
const ContinueWanderLabel				= 'ContinueWander';
const FallSpecialLabel					= 'FallSpecial';
const FallLongLabel						= 'FallLong';
const FireWhileFallingLabel				= 'FallWhileFiring';
const LandedLabel						= 'Landed';
const PausingLabel						= 'Pausing';
const PlayOutLabel						= 'PlayOut';
const SplashLabel						= 'Splash';
const TakeHitLabel						= 'TakeHit';

const NonRangedFireTimerName			= 'NonRangedFireTimer';

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

const HoldReachedDistance2D				=  16.0;
const HoldReachedDistanceSquared2D		= 256.0;

const MinMoveSpeedMultiplier			=  0.05;	// min movement speed for scripting

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

var name DefaultMeleeAttackState;	// state used to carry out melee attacks (UT bots basically closed until weapon close enough to discharge)

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

var float MaxHuntTime;
var int MaxMoveToActorAttemptsRoaming;

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

// orders
var name	Orders;						// orders a bot is carrying out 
var	Actor	OrdersObject;				// object referred to by orders ( if applicable )
var Object  OrderGiver;					// source of orders (e.g. player, GameAIController)

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

// internal AI flags
var bool	bBigJump;
var bool	bCamping;					
var bool	bCampOnlyOnce;
var bool	bChangeDir;					// tactical move boolean
var bool	bClearShot;					
var bool	bDeviousHunting;			// if true, try to sneak up behind enemy when hunting
var bool	bFireFalling;
var bool	bFiringPaused;				//!!mdf-tbd: pbly broken at this point...
var bool	bFrustrated;				
var bool	bGathering;					
var bool	bInitLifeMessage;
var bool	bIsPaused;					// is the script paused? (i.e. by dialog)
var bool	bKamikaze;					
var bool	bLeading;					// set when NPC attacking and has followers
var bool	bMustHunt;
var bool	bNoShootDecor;				// set to true to prevent NPC from targetting a decoration 2x within Roaming state (cleared on entering Roaming state)
var bool	bReadyToAttack;				// can attack again 
var bool	bSniping;					// mdf-tbd: approach changed in 777?
var bool	bStationary;				// if set NPC can only rotate/aim
var bool	bStayFreelance;				// in UT was used by assault to force bot to stay freelancing? Never true currently.
var bool	bStrafeDir;					
var bool	bTriedLastDetectedLocation; // used with hunting state
var bool	bWantsToCamp;				

var float LastInvFind;
var float RefireDelay;

var name LastPainAnim;
//mdf-tbe: moved to "shared" for now var	float LastAcquireTime;

var float CampTime;
var float LastCampCheck;
var float LastAttractCheck;
var Ambushpoint AmbushSpot;				// current AmbushSpot if applicable
var Actor RoamTarget;					// current goal actor for roaming state if applicable
var Actor OldMoveTarget;

var NavigationPoint BlockedPath;
var vector RealLastDetectedLocation;

var name NextState, NextLabel;			// mdf-tbd: can we eliminate these (see 777+ approach)?

//mdf-tbd: not used? 
//var float Rating;
//var name RealState, RealLabel;
//var bool	bSpecialAmbush;
//var bool	bPowerPlay;
//var bool	bViewTarget;				// is being used as a viewtarget
//var AlternatePath AlternatePath;		// used by game AI for team games with bases
var bool  bGoosedTimer;					// !!mdf hack
var float AttackStationaryStopTime;

var float AttackNonRangedCheckRate;		// rate at which to check for firing situation in attack states apart from ranged attack
var float AttackNonRangedFailedRate;	// inreased rate to use if check at AttackNonRangedCheckRate failed
var float AttackReadyToAttackOdds;		// !!mdf hack
var float TimeBetweenAttacks;			// seconds - modified by difficulty (not used with new ai)

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

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

	ErrorStr = "";

	// ignore transitions within the same state for now?
	if( NewState != OldState )
	{
		switch( NewState )
		{
		case AttackStationaryState:
			if( !IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) )
				ErrorStr = "transition to ranged attack when not prepared!";
			break;

		case AttackMeleeState:
			if( !IsPreparedToMelee( true, true, U2Weapon.RatingIneffective ) )
				ErrorStr = "transition to melee attack when not prepared!";
			break;
		}
	}

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

//-----------------------------------------------------------------------------
// 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;

	if( bStationary )
	{
		if( AssignHoldSpot( Pawn ) ) // 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; }

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

function bool AssignHoldSpot( Actor LocationActor )
{
	local HoldSpot HS;

	HS = LocationActor.Spawn( class'HoldSpot' );

	if( HS != None )
	{
		if( HoldSpot(OrdersObject) != None )
			OrdersObject.Destroy();
		OrdersObject = HS;
	}
	else
	{
		#debug DMAI( "Can't create holdspot at given location" );
	}

	return ( HS != None );
}

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

event Destroyed()
{
	#debug DMAIA( "Calling RemoveAllTimers" );
	RemoveAllTimers();
	ClearHoldSpots();
	Super.Destroyed();
}

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

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

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

function ResetGlobalAISettings()
{
	bFire = 0;
	bAltFire = 0;
	bKamikaze = false;
	BlockedPath = None;
}

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

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

	#debug DMAI( "Restart" );
	GotoState( DefaultState );
}

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

function Possess( Pawn P )
{
	#debug DMAI( "Possess" );

	Super.Possess( P );

	P.PreSetMovement();
	
	SetPeripheralVision();

	Aggressiveness = U2PBasic.BaseAggressiveness;

	// preserve Pawn's rotation initially for placed Pawns
	FocalPoint = Pawn.Location + 512*vector(Pawn.Rotation);

	Pawn.SetMovementPhysics(); 
	if( Pawn.Physics == PHYS_Walking )
		Pawn.SetPhysics( PHYS_Falling );
	Enable( Event_NotifyBump );

	AssignScriptController();

	#debug DMAI( "Possess: Controller=" $ Self $ " Pawn=" $ Pawn $ " script controller=" $ ScriptController );

	//!!mdf hack
	//DMTNS( "AddTimer in Possess: " $ AttackNonRangedCheckRate );
	AddTimer( NonRangedFireTimerName, AttackNonRangedCheckRate, true );

	if( U2PBase.bFrozen )
	{
		SetFrozen( true ); // mainly for looking at animations in-game
	}
	else 
	{
		if( U2PBase.bStationary )
			SetStationary( true );
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}
}

//-----------------------------------------------------------------------------
/* mdf-tbd:
event PreBeginPlay()
{
	Super.PreBeginPlay();
	//bInitialFear = ( Pawn.ReactionToPlayer == REACTION_Fear );
}
*/

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

/*
mdf-tbr: for testing
event PostBeginPlay()
{
	Super.PostBeginPlay();
}
*/

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

function EnemyAcquired()
{
	GotoState( AcquisitionState );
}

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

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

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

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

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

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

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

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

function SharedTimerEvent()
{
	#debug DMAIA( "Global.SharedTimerEvent called (event will be ignored)" );
}

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

function bool IsMeleeAttacking()
{
	return false;
}

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

function bool IsFiring()
{
	return ( bFire + bAltFire != 0 );
}

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

function float GetAttackStyle( Actor TargetActor )
{
	return 0.0;
}

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

function MaybeStopFiring( optional float SuggestedFireAgainDelay )
{
	if( GetCurrentFireRate() > U2Weapon.MaxRapidFireRate )
	{
		#debug   StopFiring( SuggestedFireAgainDelay, SFI_Behavior, GetContext() );
		#release StopFiring( SuggestedFireAgainDelay, SFI_Behavior );
	}
}

//-----------------------------------------------------------------------------
//!!mdf hack return true if should up timer rate

function bool NonRangedFireCheck()
{
	local bool bGooseTimer;

	//if( ControllerEnemy != None )
	if( ControllerEnemy != None && (bFire + bAltFire) == 0 )
	{
		if( CanFire( false ) && IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) )
		{
			//if( Pawn.IsA( 'U2Izarian' ) )
			//	DMTNS( "  NonRangedFireCheck calling CombatMove" );
			CombatMove();
		}
		/*
		else
		{
			bFire = 0;
			bAltFire = 0;
		}
		*/

		bGooseTimer = ( (bFire + bAltFire) == 0 );
		
	}

	return bGooseTimer;
}

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

final function NonRangedFireTimer()
{
	local bool bGooseTimer;

	//DMTNS( "==> NonRangedFireTimer  bGoosedTimer: " $ bGoosedTimer );
	bGooseTimer = NonRangedFireCheck();

	if( bGoosedTimer != bGooseTimer )
	{
		if( bGooseTimer )
		{
			//DMTNS( "  AddTimer 0.1" );
			AddTimer( NonRangedFireTimerName, AttackNonRangedFailedRate, true );
			bGoosedTimer = true;
		}
		else
		{
			AddTimer( NonRangedFireTimerName, AttackNonRangedCheckRate, true );
			bGoosedTimer = false;
		}
	}
}

//-----------------------------------------------------------------------------
// Returns true if the NPC is "prepared", e.g. has a good enough weapon and 
// enough inventory and Health to carry out the orders, go hunting etc. Returns 
// true by default subclasses can override this as necessary.

// mdf-tbd: add a "risk" parameter to indicate how "well-stocked" NPC should
// be and scale return value accordingly in subclasses. Maybe also path in
// a minimum  Health amount (percentage of max Health)?

function bool ReadyForAction()
{
	return true;
}

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

function bool ReadyForOrders()
{
	return true;
}

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

function bool CanMeleeAttack()
{
	// check Weapon.bMeleeWeapon / in inventory?
	return false;
}

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

function bool ShouldTransitionToMeleeAttack()
{
	#debug DMAI( "ShouldTransitionToMeleeAttack" );
	return CanMeleeAttack();
}

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

function bool SpecialAttackTransition()
{
	return false;
}

//-----------------------------------------------------------------------------
// Should be implemented in subclasses which use weapons to support weapon
// firing. NPCs which have notification based ranged attacks will fire their
// projectiles though their animations.

function FireShot( byte bUseAltMode );

function ResetAttackTimer( float SuggestedFireAgainDelay )
{
	local float TimerTime;

	if( SuggestedFireAgainDelay <= 0.0 )
	{
		// if there is time left on the timer, leave it alone
		if( TimerCounter > 0.0 )
			return;

		SuggestedFireAgainDelay = TimeBetweenAttacks;
	}

	TimerTime = (0.5 + 0.5 * FRand()) * SuggestedFireAgainDelay;
	
	// mdf-tbd: pretty much impossible to know what this
	// does unless you understand the code intimately -- who handles this timer?
	// NOTE: In retreating state this doesn't seem to result in a check for
	// being able to fire once the time is up but other states seem to be 
	// reacting fairly well. I'd much rather see this map to a global "check
	// whether should fire now" timer.
	SetSharedTimer( TimerTime, false );
}

//-----------------------------------------------------------------------------
// Stop the actual attack animation / weapon firing.

protected function ClearAttack()
{
}

//-----------------------------------------------------------------------------
// Specified time used to determine when NPC next checks for being able to
// attack (defaults to TimeBetweenAttacks).
// 
// If bDisabled = true, then NPC won't be able to fire for a while because the
// weapon is changing or the NPC isn't facing his enemy.

#debug function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo, string ContextStr )
#release function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo )
{
	#debug DMAIA( "StopFiring base (" $ ContextStr $ "): " $ SuggestedFireAgainDelay );

	//mdf-tbd: LastFireTime = -1.0;
	U2P.AnimationController.SpecialAnimationClear();

	ResetAttackTimer( SuggestedFireAgainDelay );
}

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

function ChangedWeapon()
{
	local byte bUseAltMode;

	if( Pawn != None && Pawn.Weapon != None )
	{
		if( bFire > 0 || bAltFire > 0 )
		{
			Pawn.Weapon.RateSelf( ControllerEnemy, bUseAltMode );
			FireShot( bUseAltMode );
		}
		Pawn.Weapon.SetHand( 0 );
	}
}

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

function FireAt( Actor A )
{
	DMN( "FireAt() -- should be implemented in subclass!" );
}

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

function DoRangedAttack()
{
	FireAt( ControllerEnemy );
}

//-----------------------------------------------------------------------------
// combo move

function SpecialFire()
{
	bFiringPaused = true;
	NextState = AttackingState;
	NextLabel = BeginLabel; 
	StopMovement( true, false );
	GotoState( AttackStationaryState );
}

//-----------------------------------------------------------------------------
//@ INPUT -- PROCESSED EVENTS
//-----------------------------------------------------------------------------

function eventTakeDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
{
	//DMTNS( "NPCCBase eventTakeDamage -- Damage" @ Damage @ "Instigator" @ Instigator @ "HitLocation" @ HitLocation @ "Momentum" @ Momentum @ "DamageType" @ DamageType );

	U2PBase.eventTakeDamage( Damage, Instigator, HitLocation, Momentum, DamageType );

	// NOTE: actual damage might be filtered out later one but we still want the NPC
	// to possibly react to having "taken damage" even if he wasn't hurt.
	if( Pawn != None && Pawn.Health > 0 ) //note: otherwise can get accessed nones due to NPC dying from damage and ScriptController getting cleared
		TookDamage( Damage, Instigator, HitLocation, Momentum, DamageType );
}

//-----------------------------------------------------------------------------
// mdf-tbi: move into eventTookDamage once I'm sure this is OK

function TookDamageBase( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
{
	local name DestinationState;
	local name DestinationLabel;

	// mdf: don't react if dead (was resurrecting dead NPCs...)
	if( Pawn != None && Pawn.Health > 0 )
	{
		// set Instigator as enemy?
		DamageAttitudeTo( Instigator, Damage, DamageType );
	
		// mdf-tbd: does this make sense? enemy might be nowhere in sight and might not have had anything to do with the damage?
		if( ControllerEnemy != None )
			EnemyDetected( ControllerEnemy.Location );
	
		if( NextState == TakeHitState )
		{
			if( ControllerEnemy != None && GetReactionToEnemy( ControllerEnemy ) == REACTION_Fear )
			{
				NextState = AttackRetreatState;
				NextLabel = BeginLabel;
			}
			else
			{
				NextState = AttackingState;
				NextLabel = BeginLabel;
			}
			DestinationState = TakeHitState;
		}
		else
		{
			DestinationState = AttackingState;
		}

		#debug DMAI( "TookDamageBase -- Pawn is valid (set and alive)  DestinationState: " $ DestinationState $ " DestinationLabel: " $ DestinationLabel );
		StateTransition( DestinationState, DestinationLabel ); 
	}
	else
	{
		#debug DMAI( "TookDamageBase -- Pawn is NOT valid (not set/dead)" );
	}
}

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

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

	TookDamageBase( Damage, Instigator, HitLocation, Momentum, DamageType );
}

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

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

function EReaction GetReactionToEnemy( Pawn EnemyPawn )
{
	local EReaction ReturnedReaction;
	local float CurrentRelativeStrength;
	
	if( bKamikaze )
		ReturnedReaction = REACTION_Attack;
	else if( StationaryPawn(EnemyPawn) != None  )
		ReturnedReaction = REACTION_Fear;
	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;
		}
	}
	
	//DMTNS( "GetReactionToEnemy " $ EnemyPawn $ " returning: " $ EnumStr( enum'EReaction', ReturnedReaction ) $ " bKamikaze: " $ bKamikaze $ " RelativeStrength: " $ RelativeStrength( EnemyPawn ) $ " Aggresiveness: " $ Aggressiveness );

	return ReturnedReaction;
}

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

function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
{
	if( Pawn == None || Pawn.Health <= 0 )
		return;

	if( ControllerEnemy == None && ValidEnemy( Other ) )
	{
		#debug DMAI( "DamageAttitudeTo -- calling MaybeSetEnemy" );
		if( MaybeSetEnemy( Other ) )
		{ 
			NextState = AttackingState; 
			NextLabel = BeginLabel;
		}
	}

	if( ControllerEnemy != None && ControllerEnemy == Other )
		EnemyDetected( ControllerEnemy.Location );

	if( NextState == TakeHitState )
	{
		NextState = AttackingState; 
		NextLabel = BeginLabel;
		GotoState( TakeHitState ); 
	}
	else if( ControllerEnemy != None )
		GotoState( AttackingState );
}

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

function SetRoamTarget( Actor NewRoamTarget )
{
	// should only ever be set in Roaming state
	DMAssert( false, GetContext() );
}

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

function bool UseTacticalJumps()
{
	return false;
}

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

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

	if( OldControllerEnemy == P )
		OldControllerEnemy = None;

	if( ControllerEnemy == None )
	{
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}
}

//-----------------------------------------------------------------------------
// NOTE: Killed replaced by NotifyKilled in 777 (and duplicate calls to killed
// in both Pawn.Destroy and Pawn.Died removed).

function NotifyKilled( Controller Killer, Controller Killed, Pawn KilledPawn, class<DamageType> DamageType )
{
	local Controller C;

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

	if( OldControllerEnemy == KilledPawn )
		OldControllerEnemy = None;

	if( ControllerEnemy == KilledPawn )
	{
		bFire = 0;
		bAltFire = 0;

		UpdateEnemy( true );

		if( ControllerEnemy == None )
			HandleEnemyKilledSafe( Killer, KilledPawn );
		else
			HandleEnemyKilledUnSafe( Killer, KilledPawn );

		GotoState( AttackingState ); 
	}
//	else
//	{
//		DMTN( "Enemy not = KilledPawn: " $ ControllerEnemy );
//	}

	// ick: tbd -- bot can't just call super unless we change NotifyKilled to return 
	// info back to indicate whether GameRelatedKilled code should be used.
	GameRelatedKilled( Killer, Killed, KilledPawn, DamageType );
}	

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

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

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

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

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

function bool PreparedToHunt()
{
	//DMTNS( "PreparedToHunt" );
	return( GetSkill() >= 0.5 && ReadyForAction() );
}

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

function bool TestCanJump()
{
	return( (MoveTarget != None) && (MoveTarget.Physics != PHYS_Falling || Pickup(MoveTarget) == None) );
}

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

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

// stubs for functionality which only exists in bots (ideally refactor code in
// here to get rid of these, but this may turn into a ROT item).
function SendMessageAcknowledgeOrders( Controller OrderGiver, float Wait );
function SendMessageNearPoint( Pawn Point, float Wait );
function SendMessageInPosition( float Wait );
function SetRealOrders( name NewOrders, Actor NewOrdersObject, Object NewOrderGiver );
function name GetRealOrders() { return Orders; }

//-----------------------------------------------------------------------------
// 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( bVisibleAI && OrdersObject != None && OrdersObject.default.bHidden )
		HideActor( OrdersObject );

	OrdersObject = NewOrdersObject;

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

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

function UpdateOrders( name NewOrders, Object NewOrderGiver, Actor NewOrdersObject )
{
	Orders = NewOrders;
	OrderGiver = NewOrderGiver;
	SetOrdersObject( NewOrdersObject );
}

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

function HandleOrdersAttack()
{
	U2PBasic.CampingRate = 0.0;
}

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

function HandleOrdersDefend()
{
	SetOrdersObject( SetDefense() );
	if( OrdersObject == None )
	{
		#debug DMAI( " defender couldn't find defense object" );
		#debug DMAI( "SetOrders " $ GetContext() );
		SetOrders( OrdersNone, None, 0.0, OrderGiver, false );
	}
	else
	{
		U2PBasic.CampingRate = 1.0;
	}
}

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

function HandleOrdersFollow()
{
	Aggressiveness += 1;
	SetOrdersObject( Actor(OrderGiver) );
}

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

function HandleOrdersHold()
{
	Aggressiveness += 1;
	if( Controller(OrderGiver) != None )
		AssignHoldSpot( Controller(OrderGiver).Pawn );
}

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

function HandleOrdersNone()
{
	OrderGiver = None;
}

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

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

	if( Orders == OrdersHold )
	{
		DestinationState = HoldState;
	}

	return ( DestinationState != NoState );
}

/*-----------------------------------------------------------------------------
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 bValidOrders;
	local name DestinationState, DestinationLabel;

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

	//-------------------------------------------------------------------------
	// cleanup, re-initialization
	//-------------------------------------------------------------------------

	// mdf-tbd: bLeading set if given attack orders & has followers -- applies to bots only currently
	bLeading = false;

	// mdf-tbd:
	if( NewOrders != GetRealOrders() && Pawn != None )
	{ 
		// mdf-tbd: resolve polymorphically by moving into appropriate states -- don't use IsInState!
		if( (IsInState( RoamingState ) && bCamping) || IsInState( WanderingState ) )
			GotoState( RoamingState, PreBeginLabel );
	}

	// mdf-tbd:
	if( bSniping && NewOrders != OrdersDefend )
		bSniping = false;

	// mdf-tbd:
	bStayFreelance = false;

	Aggressiveness = U2PBasic.BaseAggressiveness;
	if( Orders == OrdersFollow )
		Aggressiveness -= 1;

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

	//-------------------------------------------------------------------------
	// process new orders
	//-------------------------------------------------------------------------

	UpdateOrders( NewOrders, OrderGiver, NewOrdersObject );

	bValidOrders = true;
	switch( NewOrders )
	{
		case OrdersNone:
			HandleOrdersNone();
			break;

		case OrdersAttack:
			HandleOrdersAttack();
			break;

		case OrdersDefend:
			HandleOrdersDefend();
			break;

		case OrdersFollow:
			HandleOrdersFollow();
			break;

		case OrdersHold:
			HandleOrdersHold();
			break;

		default:
			bValidOrders = false;
			break;
	}

	SetRealOrders( Orders, OrdersObject, OrderGiver );

	if( bAcknowledge && Controller(OrderGiver) != None )
		SendMessageAcknowledgeOrders( Controller(OrderGiver), 5.0 );

	// respond to orders asap
	if( Orders != OrdersNone && ReadyForOrders() )
	{
		if( DetermineOrdersTransition( DestinationState, DestinationLabel ) )
			GotoState( DestinationState, DestinationLabel );
	}

	#debug DMAI( "SetOrders (end) -- Orders: " $ Orders $ " OrdersObject: " $ OrdersObject $ " OrderGiver: " $ OrderGiver );

	return bValidOrders;
}

//-----------------------------------------------------------------------------
//@ PATHING/MOVEMENT
//-----------------------------------------------------------------------------

function EMoveType GetMoveTargetFollow( Actor GoalActor, out Actor Path, optional float GoalDistance )
{
	if( GoalActor == None || GoalActor.bDeleteMe )
	{
		if( Orders == OrdersFollow )
		{
			#debug DMAI( "SetOrders " $ GetContext() );
			SetOrders( OrdersNone );
		}

		return MT_None;
	}
	else
	{
		return Super.GetMoveTargetFollow( GoalActor, Path, GoalDistance );
	}
}

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

function EMoveType SetMoveTarget( Actor GoalActor, optional float GoalDistance, optional bool bWaitForLanding )
{
	if( Orders == OrdersFollow )
		GoalActor = OrdersObject;

	return Super.SetMoveTarget( GoalActor, GoalDistance, bWaitForLanding );
}

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

function AmbushPickSpot()
{
	local NavigationPoint N;

	for ( N=Level.NavigationPointList; N!=None; N=N.NextNavigationPoint )
	{
		// find closest ambush spot which isn't already taken
		// mdf-tbd: this doesn't check for whether owner of ambush spot is an enemy
		if( AmbushPoint(N) != None && !N.Taken && 
			(AmbushSpot == None || VSize( Pawn.Location - AmbushSpot.Location ) > VSize( Pawn.Location - N.Location)) )
		{
				AmbushSpot = AmbushPoint( N );
		}
	}
}

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

function AmbushClearOtherSpots()
{
	local Controller C;

	#debug DMAI( "AmbushClearOtherSpots" );
	for ( C=Level.ControllerList; C!=None; C=C.NextController )
	{
		if( U2NPCControllerBaseOld(C) != None && 
			C.Pawn != Pawn && 
			GetAttitudeTo( C.Pawn ) != ATTITUDE_Enemy && 
			U2NPCControllerBaseOld(C).AmbushSpot == AmbushSpot )
		{
			U2NPCControllerBaseOld(C).AmbushSpot = None;
		}
	}
}

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

function bool AmbushFindSpot()
{
	if( AmbushSpot == None )
		AmbushPickSpot();

	// if none found, use current MoveTarget if possible mdf-tbd: this doesn't check for whether owner of ambush spot is an enemy
	if( AmbushSpot == None && AmbushPoint(MoveTarget) != None && !AmbushPoint(MoveTarget).Taken )
		AmbushSpot = AmbushPoint( MoveTarget );
					
	if( AmbushSpot != None )
	{
		if( VSize( AmbushSpot.Location - Pawn.Location ) < 2 * Pawn.CollisionRadius )
		{
			if( Orders == OrdersDefend )
				SendMessageInPosition( 60.0 );
			bSniping = ( Orders == OrdersDefend && AmbushSpot.bSniping );
			CampTime = 10.0;
			Pawn.SetSightRadius( AmbushSpot.SightRadius );
			GotoState( RoamingState, CampLongLabel );
		}
		else
		{	
			FindPathToActor( AmbushSpot, MoveTarget );
			if( MoveTarget == None )
				AmbushSpot = None;
		}

		if( AmbushSpot != None )
		{
			AmbushSpot.Taken = true;

			// make sure nobody else is after this spot
			AmbushClearOtherSpots();
		}
	}

	return( AmbushSpot != None );
}	

//-----------------------------------------------------------------------------
//@ STATE TRANSITIONS
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Used for specific state transitions so that subclasses/states can hook into
// these.

function StateTransition( name DestinationState, optional name DestinationLabel )
{
	GotoState( DestinationState, DestinationLabel );
}

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

function UpdateEnemy( optional bool bTryRadiusCheck )
{
	if( !ValidEnemy( OldControllerEnemy ) )
		OldControllerEnemy = None;

	// mdf-tbd: this is potentially bad if the enemy is still valid but went
	// out of sight etc. and wasn't cleared. Either code which handles loss
	// of LOS, will clear enemy 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 code.
	#debug   SetControllerEnemy( OldControllerEnemy, GetContext() );
	#release SetControllerEnemy( OldControllerEnemy );
	if( !ValidEnemy( ControllerEnemy ) )
	{
		#debug   SetControllerEnemy( OldControllerEnemy, GetContext() );
		#release SetControllerEnemy( OldControllerEnemy );
		OldControllerEnemy = None;
	}

	if( ControllerEnemy == None && bTryRadiusCheck )
	{
		#debug   SetControllerEnemy( FindLocalEnemy( MaxRadiusEnemiesDistance ), GetContext() );
		#release SetControllerEnemy( FindLocalEnemy( MaxRadiusEnemiesDistance ) );
	}
}

//-----------------------------------------------------------------------------
// @ WhatToDoNext

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

	DestinationState = NoState;
	DestinationLabel = NoLabel;

	#debug DMAI( "WhatToDoNext (" $ ContextStr $ ") script controller=" $ ScriptController $ " Enemy=" $ ControllerEnemy $ " OldControllerEnemy=" $ OldControllerEnemy );

	if( !ShouldDestroyNPC() )
	{
		ResetGlobalAISettings();
		RestoreRealOrders();

		UpdateEnemy();

		// mdf-tbd: should this only be cleared if !bKeepEnemy?
		bReadyToAttack = false;

		if( ControllerEnemy != None )
		{
			bReadyToAttack = (GetSkill() >= 0.5);
			DestinationState = AttackingState;
		}
		else if( HasScript() )
		{
			if( GetStateName() == ScriptedState )
			{
				bMaintainCurrentState = true;
			}
			else
			{
				DestinationState = ScriptedState;
				DestinationLabel = BeginLabel;
			}
		}
		else if( bStationary )
		{
			DestinationState = HoldState;
		}
		else if( Orders == OrdersNone || !ReadyForOrders() || !DetermineOrdersTransition( DestinationState, DestinationLabel ) )
		{
			DestinationState = DefaultState;
			if( GetSkill() > 0.625 )
				bReadyToAttack = true; 
		}

		if( bMaintainCurrentState )
		{
			#debug DMAI( "WTDN maintaining current state: " $ GetStateName() );
		}
		else
		{
			#debug DMAI( "WTDN (base) selecting " $ DestinationState $ "," $ DestinationLabel $ " bReadyToAttack=" $ bReadyToAttack );
			GotoState( DestinationState, DestinationLabel );
		}
	}
	else
	{
		#debug DMAI( "WTDN -- NPC will be destroyed" );
	}
} // WhatToDoNext

//-----------------------------------------------------------------------------
//@ UW BOT CODE 
//-----------------------------------------------------------------------------

function HandleTakeHit( vector HitLocation, int Damage, class<DamageType> DamageType )
{
	if( Pawn.LastPainAnimTime - Level.TimeSeconds > 0.1 )
	{
		Pawn.PlayTakeHit( HitLocation, Damage, DamageType );
		BeginState();
		GotoState( TakeHitState, BeginLabel );
	}
}	
	
//-----------------------------------------------------------------------------

function NotifyTakeHit( pawn InstigatedBy, vector HitLocation, int Damage, class<DamageType> DamageType, vector Momentum )
{
	local bool bOptionalTakeHit;

	bFireFalling = false;
	bOptionalTakeHit = ( ( Level.TimeSeconds - Pawn.LastPainAnimTime > 0.3 + 0.88 * GetSkill() )
						&& (Damage * FRand() > 0.08 * Pawn.Health) && (GetSkill() < 0.625) ); 

	if( (Pawn.Weapon == None || !Pawn.Weapon.bPointing) &&  // note: makes sure that ongoing shot isn't interrupted by taking damage (or NPCs might never get shots off)
		!Pawn.JumpInProgress() && 
		(bOptionalTakeHit || (Momentum.Z > 140) || (Damage * FRand() > ( 0.17 + 0.16 * GetSkill() ) * Pawn.Health)) ) 
	{
		HandleTakeHit( HitLocation, Damage, DamageType );  

		if( Pawn.SameTeam( InstigatedBy ) )
			U2P.AssetsHelperClass.static.HandleFriendlyFire( U2Pawn(InstigatedBy), U2P );

		if( ( ControllerEnemy != None ) && ( FRand() * ( 8*GetSkill() - 4 ) > 0.5 ) )
		{
			NextState = FallingState;
			NextLabel = FireWhileFallingLabel;
		}
	}
	else if ( (Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z)
				&& (Momentum.Z/Pawn.PhysicsVolume.Gravity.Z < -0.5) )
		bFireFalling = true;
	else if( NextState == TakeHitState )
		NextState = NoState;
}

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

function Actor SetDefense()
{
	return None;
}

//-----------------------------------------------------------------------------
// 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 GiveUpTactical( bool bCanCharge );

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

function byte PriorityObjective()
{
	return 0;
}

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

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

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

function bool FindSpecialAttraction()
{
	return false;
}

//-----------------------------------------------------------------------------
// 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 bool CanFire( bool bTest ) { return true; }

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

function bool IsPreparedToFire( bool bOwner, optional bool bCheckWeaponRating, optional int MinWeaponRating )
{
	local byte bUseAltMode;

	// !!mdf-tbd: how often will this be called and if NPCs only have 1/2 weapons -- can we optimize this stuff?
	return (
		Pawn != None &&
		Pawn.Weapon != None && 
		!Pawn.Weapon.bMeleeWeapon && 
		(!bOwner || (Pawn.Weapon.CanFire() && Pawn.Weapon.HasEnoughAmmo(1))) &&
		(!bCheckWeaponRating || Pawn.Weapon.RateSelf( ControllerEnemy, bUseAltMode ) >= MinWeaponRating) );
}

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

function bool IsPreparedToMelee( bool bOwner, optional bool bCheckWeaponRating, optional int MinWeaponRating )
{
	/*
	tbd: pbly want this but need to test it carefully

	local byte bUseAltMode;
	return( (!bCheckWeaponRating || Pawn.Weapon.RateSelf( ControllerEnemy, bUseAltMode ) > MinWeaponRating ) &&
			Pawn.Weapon != None && 
			Pawn.Weapon.bMeleeWeapon && 
			(!bOwner || Pawn.Weapon.CanFire()) )
	);
	*/

	return ( Pawn != None && Pawn.Weapon != None && Pawn.Weapon.bMeleeWeapon && (!bOwner || Pawn.Weapon.CanFire()) );
}

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

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 );
		}
		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 = Normal( Pawn.Location - Other.Pawn.Location );
				GotoState( WanderingState, BeginLabel );
			}
		}

		// mdf-tbd: setting timer on other!?
		if( U2NPCControllerBaseOld(Other) != None )
			U2NPCControllerBaseOld(Other).SetSharedTimer( FClamp( TimerRate, 0.001, 0.2 ), false );

		return true;
	}
	return false;
}

//-----------------------------------------------------------------------------
// Enemy already set to Pawn that bumped us.

function HandleBumpedByEnemy()
{
	bReadyToAttack = true;
	GotoState( AttackStationaryState );
}

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

#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 bool FriendlyBumpSpecial()
{
	local bool bResult;

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

		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) );
}

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

function eventBumpFriend( Pawn Other )
{
	if( TimerRate <= 0.0 )
		SetSharedTimer( 1.0, false );

	Super.eventBumpFriend( Other );
}

//-----------------------------------------------------------------------------
	
function SetFall()
{
	Super.SetFall();

	if( ControllerEnemy != None )
	{
		NextState = AttackingState; //default
		NextLabel = BeginLabel;
		GotoState( FallingState );
	}
}

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

event LongFall()
{
	SetFall();
	if( ControllerEnemy != None && Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z )
		GotoState( FallingState, FireWhileFallingLabel );
	else 
		GotoState( FallingState, FallLongLabel );
}

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

function ExecuteDodge( bool bLeft, vector DodgeDestination )
{
	Super.ExecuteDodge( bLeft, DodgeDestination );
	
	if( ( Pawn.Weapon != None ) && Pawn.Weapon.bSplashDamage
		&& ( ( bFire != 0 ) || ( bAltFire != 0 ) ) && ( ControllerEnemy != None ) 
		&& !Pawn.FastTrace( ControllerEnemy.Location, DodgeDestination ) 
		&& Pawn.FastTrace( ControllerEnemy.Location, Pawn.Location ) )
	{
		#debug DMAI( "ExecuteDodge - clear firing" );
		bFire = 0;
		bAltFire = 0;
	}

	GotoState( FallingState, DuckingLabel );
}

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

function CombatMove()
{	
	#debug DMAI( "CombatMove" );
	//DMTNS( "CombatMove" );

	if( ControllerEnemy == None )
		return;

	//if( GetSkill() > 0.5 )
	if( FDecision( AttackReadyToAttackOdds ) )
		bReadyToAttack = true;

	if( Pawn.Weapon == None )
	{
		bAltFire = 0;
		bFire = 0;
		return;
	}

	if( bReadyToAttack && IsFacingTarget( ControllerEnemy, CosMinFacingTargetAngle ) )
	{
		if( NeedToTurn( ControllerEnemy.Location, NeedToTurnAngleCos ) )
		{
			#debug   StopFiring( 0.1, SFI_Orientation, GetContext() );
			#release StopFiring( 0.1, SFI_Orientation );
		}
		else 
		{
			FireAt( ControllerEnemy ); 
		}
	}		
	else 
	{
		// keep firing if rapid fire weapon unless can't see enemy
		MaybeStopFiring( TimeBetweenAttacks );

		if( (bFire + bAltFire > 0) && (GetTimeSinceEnemyLastSeen() > 1.0 || NeedToTurn( ControllerEnemy.Location, NeedToTurnAngleCos )) )
		{
			bFire = 0;
			bAltFire = 0;
		}
	}
}

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

function BigJump( Actor JumpDest )
{
	Pawn.SetPhysics( PHYS_Falling );
	Pawn.Velocity = Pawn.GroundSpeed * Normal( JumpDest.Location - Pawn.Location );
	if( JumpSpot(JumpDest) != None && JumpSpot(JumpDest).bAlwaysAccel )
	{
		bBigJump = true;
		Pawn.Acceleration = Pawn.AccelRate * Normal( Destination - Pawn.Location );
	}
	else
	{ 
		StopMovement( true, false );
	}
		
	if( Pawn.bCountJumps )
		Pawn.Inventory.OwnerEvent( 'Jumped' );
	Pawn.Velocity.Z = Pawn.JumpZ;
	Pawn.Velocity = EAdjustJump( Destination, Pawn.Velocity.Z, Pawn.GroundSpeed );
	bSpecialJump = true;
	Pawn.DesiredRotation = rotator( JumpDest.Location - Pawn.Location );
	FocalPoint = JumpDest.Location + 100 * (JumpDest.Location - Pawn.Location);
	if ( Pawn.PhysicsVolume.Gravity == Pawn.PhysicsVolume.default.Gravity )
		MoveTarget = None;
	
	Pawn.bBlockAdjustJump = true;
	SetFall();
}

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

function bool PickLocalInventoryDestination( float MaxDist, float MinDistraction )
{
	local Pickup LocalPickup, BestPickup;
	local float NewWeight, BestWeight;
	local float DistanceToPickup;
	local bool bResult;

	#debug DMAIM( "PickLocalInventoryDestination -- MaxDist: " $ MaxDist $ " MinDistraction: " $ MinDistraction );
	bResult = false;
	if( Pawn != None && Pawn.bCanPickupInventory )
	{
		// first look at nearby inventory < MaxDist (mdf: use 2*MaxDist for weapons)
		//!!mdf-tbd: VCA seems to be really slow -- should it be avoided/fixed?
		foreach VisibleCollidingActors( class'Pickup', LocalPickup, 2*MaxDist, Pawn.Location, true )
		{
			DistanceToPickup = VSize( LocalPickup.Location - Pawn.Location );

			// only look for weapons at 2xMaxDist
			if( WeaponPickup(LocalPickup) == None && DistanceToPickup > MaxDist )
				continue;

			// mdf-tbd: check for PHYS_Falling means bots very unlikely to after
			// weapon tossed by immediate victim since it will take a while to
			// land. Ideally, bots would wait for the weapon to land but we don't
			// want them going after weapons that are going to fall a long way and/or
			// far away.
			if( LocalPickup.ReadyToPickup( 0.0 ) && 
				LocalPickup.MaxDesireability/60 > BestWeight && 
				LocalPickup.Physics != PHYS_Falling && 
				LocalPickup.Location.Z < (Pawn.Location.Z + Pawn.MaxStepHeight + Pawn.CollisionHeight) )
			{
				// mdf-tbd: BotDesireability not too good about encouraging bot to take
				// weapon even if it already has one as a defensive measure.
				
				NewWeight = LocalPickup.BotDesireability( Pawn );

				if( (NewWeight > MinDistraction) || 
					(LocalPickup.Inventory != None && WeaponPickup(LocalPickup) != None && (DistanceToPickup < 0.6*MaxDist)) )
				{
					NewWeight = NewWeight/DistanceToPickup;
					if( NewWeight > BestWeight )
					{
						BestWeight = NewWeight;
						BestPickup = LocalPickup;
					}
				}
			}
		}

		// mdf-tbd: add support for trying for next N best from above if can't reach best one (not more than 2/3 though)
	    if( BestPickup != None )
		{
			Pawn.bCanJump = ( BestPickup.Location.Z > Pawn.Location.Z - Pawn.CollisionHeight - Pawn.MaxStepHeight );
			if( ActorReachable( BestPickup ) )
			{
				MoveTarget = BestPickup;
				bResult = true;
			}
			Pawn.bCanJump = true;
		}
	}

	#debug DMAIM( "PickLocalInventoryDestination returning MoveTarget: " $ MoveTarget );
	return bResult;
}

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

function bool ShouldDestroyNPC()
{
	return false;
}

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

function GameRelatedKilled( Controller Killer, Controller Killed, Pawn KilledPawn, class<DamageType> DamageType );

//-----------------------------------------------------------------------------
//@ STATE CODE -- BASE STATES
//-----------------------------------------------------------------------------

state @ EnemyKilledState
{
	ignores EnemyNotVisible; 

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

	//-------------------------------------------------------------------------
		
	event EndState()
	{
		RestoreAlertness();
	}
} // EnemyKilledState

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

state @ MoveToGoalBaseState
{
	//-------------------------------------------------------------------------

	function SharedTimerEvent()
	{
		//DMTNS( "SharedTimerEvent" );
		bReadyToAttack = true;
		Enable( Event_NotifyBump );
	}

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

	function SetFall()
	{
		NextState = GetStateName(); 
		NextLabel = LandedLabel;
		GotoState( FallingState ); 
	}

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

@ LandedLabel:
	if( MoveTarget == None )
		Goto( MovePickDestLabel );
	Goto( MoveActiveLabel );

@ TakeHitLabel:
	Goto( MoveActiveLabel );

// idiot checks (give more info than "invalid label xxx" and make obvious)
@ MovePickDestLabel:
	NPCError( ET_Other, "WARNING: label '" $ MovePickDestLabel $ "' needs to be implemented in " $ GetStateName() );
	Stop;

@ MoveActiveLabel:
	NPCError( ET_Other, "WARNING: label '" $ MoveActiveLabel $ "' needs to be implemented in " $ GetStateName() );
	Stop;

@ GiveUpLabel:
	#debug DMAIL( GiveUpLabel );
	NavigationError( ET_Move, "gave up trying to get to MoveTarget" );
	Goto( ErrorLabel );

@ ErrorLabel:
	#debug DMAIL( ErrorLabel );
	NavigationError( ET_InternalPath, "at move error label" );
	Pawn.StopMovement( true, true );
	Stop;
} // MoveToGoalBaseState

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

state @ MoveToGoalWithEnemyState extends @ MoveToGoalBaseState
{
	//-------------------------------------------------------------------------

	function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
	{
		if( Pawn.Health > 0 )
		{
			if( NextState == TakeHitState )
			{
				NextState = GetStateName(); 
				NextLabel = TakeHitLabel;
				GotoState( TakeHitState ); 
			}
			else if( !IsFacingTarget( ControllerEnemy, CosMinFacingTargetAngle ) && ( GetSkill() > 0.75 * FRand() ) )
				GotoLabel( MoveActiveLabel );
		}
	}
} // MoveToGoalWithEnemyState

//-----------------------------------------------------------------------------
//@ STATE CODE -- MAIN STATES
//-----------------------------------------------------------------------------

/*-----------------------------------------------------------------------------
Creature has just reacted to stimulus, and set an enemy - depending on strength
of stimulus, and ongoing stimulii, vary time to focus on target and start 
attacking (or whatever).  FIXME - need some acquisition specific animation
HearNoise, SeeEnemy used to improve/change stimulus. */

state @ AcquisitionState
{
	ignores BeginFalling, NotifyLanded; 

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

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

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

	function eventSeeEnemy( Pawn Seen )
	{
		if( MaybeSetEnemy( Seen ) )
		{
			Pawn.MakeNoise( 1.0 );
			GotoState( AttackingState );
		}
	} 
	
	//-------------------------------------------------------------------------

	function eventBumpEnemy( Pawn Other )
	{
		if( MaybeSetEnemy( Other ) )
		{
			Pawn.MakeNoise( 1.0 );
			GotoState( AttackingState );
		}
	} 
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		SetAlertness( -0.5 );
	}

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

	event EndState()
	{
		RestoreAlertness();
		LastAcquireTime = Level.TimeSeconds;
	}
		
	//-------------------------------------------------------------------------

@ PlayOutLabel:
	StopMovement( true, false );
    if( Pawn.AnimFrame < 0.6 && Pawn.IsAnimating() )
	{
		Sleep( 0.05 );
		Goto( PlayOutLabel );
	}
		
@ BeginLabel:
	StopMovement( true, false );
	if( NeedToTurn( GetLastEnemySeenLocation(), NeedToTurnAngleCos ) )
	{	
		Focus = None;
		FocalPoint = GetLastEnemySeenLocation();
		FinishRotation( DefaultRotationThreshold );
	}
	FocalPoint = GetLastEnemySeenLocation();
	if( ControllerEnemy == None )
	{
		#debug   WhatToDoNext( GetContext() );	
		#release WhatToDoNext();	
	}
	
	if( StationaryPawn(ControllerEnemy) != None )
		GotoState( AttackingState );

	if( GetReactionToEnemy( ControllerEnemy ) == REACTION_Fear )  //will run away from noise
	{
		EnemyDetected( ControllerEnemy.Location );
		GotoState( AttackingState );
	}
	else if( GetSkill() >= 0.5 )
	{
		bMustHunt = true;
		GotoState( AttackingState );
	}
	else if( Level.TimeSeconds - LastAcquireTime > 0.3 )
	{
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}
	else
	{
		Sleep( 0.1 );
		Goto( BeginLabel );
	}
} // AcquisitionState

/*-----------------------------------------------------------------------------
Master attacking state - choose which type of attack to do from here. 
*/

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

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

	function ChooseAttackMode()
	{
		local EReaction ReactionToEnemy;
		local Pawn TempPawn;
		local bool bWillHunt;

		bWillHunt = bMustHunt;
		bMustHunt = false;
		if( !ValidEnemy( ControllerEnemy ) )
		{
			#debug   WhatToDoNext( GetContext() );
			#release WhatToDoNext();
			return;
		}

		ReactionToEnemy = GetReactionToEnemy( ControllerEnemy );
		if( (Level.TimeSeconds - LastAttractCheck > 0.5) || 
			ReactionToEnemy == REACTION_Fear || 
			PriorityObjective() > 1 ) 
		{
			/*OLD
			// old approach totally borks attacking currently because GameAI approach
			// doesn't make state changes for the AI
			if( FindSpecialAttraction() )
				return;
			*/
			//NEW
			if( FindSpecialAttraction() )
			{
				GotoState( AttackFallbackState, MoveSpecialLabel );
				return;
			}

			if( ControllerEnemy == None )
			{
				#debug   WhatToDoNext( GetContext() );
				#release WhatToDoNext();
				return;
			}
		}
			
		if( IsMobile() && ReactionToEnemy == REACTION_Fear )
		{
			GotoState( AttackRetreatState );
			return;
		}
		/* mdf-tbd: shouldn't be in attacking state at all if enemy is a friend
		   and GetReactionToEnemy only returns fear/hate currently
		else if( ReactionToEnemy == REACTION_Friendly )
		{
			#debug   WhatToDoNext( GetContext() );
			#release WhatToDoNext();
			return;
		}
		*/
		else if( !LineOfSightTo( ControllerEnemy ) )
		{
			if( OldControllerEnemy != None && GetReactionToEnemy( OldControllerEnemy ) == REACTION_Attack && LineOfSightTo( OldControllerEnemy ) )
			{
				// swap current, old enemies
				TempPawn = ControllerEnemy;
				#debug   SetControllerEnemy( OldControllerEnemy, GetContext() );
				#release SetControllerEnemy( OldControllerEnemy );
				OldControllerEnemy = TempPawn;
			}	
			else 
			{
				// NEW BEGIN
				if( IsMobile() && FindSpecialAttraction() )
				{
					// old approach totally borks attacking currently because GameAI approach
					// doesn't make state changes for the AI
					GotoState( AttackFallbackState, MoveSpecialLabel );
				}
				else if( ControllerEnemy == None )
				{
					#debug   WhatToDoNext( GetContext() );
					#release WhatToDoNext();
				}
				else if( !IsMobile() || 
					(Orders == OrdersHold && GetTimeSinceEnemyLastSeen() > 5.0) ||
					(!bWillHunt && (bSniping || (VSize( ControllerEnemy.Location - Pawn.Location) <= 600 + (FRand() * RelativeStrength( ControllerEnemy ) - U2PBasic.CombatStyle) * 600))) )
				{
					ClearMoveAttempts();
					GotoState( AttackStakeOutState );
				}
				else
				{
					GotoState( AttackHuntState );
				}
				// NEW END

				return;
			}
		}	

		// mdf-tbd: ick
		if( !SpecialAttackTransition() )
		{		
			if( bReadyToAttack )
				SetSharedTimer( TimeBetweenAttacks, false );
			GotoState( AttackTacticalMoveState );
		}
	}
	
	//-------------------------------------------------------------------------
	// EnemyNotVisible implemented so engine will update LastEnemySeenLocation

	function eventEnemyNotVisible()
	{
	}

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

	function SharedTimerEvent()
	{
		//DMTNS( "SharedTimerEvent" );
		bReadyToAttack = true;
	}

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

	event BeginState()
	{
		// mdf-tbd: NPCs seem to be firing all the time and this helps but
		// ultimately need to look into the firing code. Its possible that
		// this is also causing problems firing, e.g. with the Takkra because
		// this stops firing as soon as it starts?
		//StopFiring();
		if( TimerRate <= 0.0 )
			SetSharedTimer( TimeBetweenAttacks  * ( 1.0 + FRand() ), false ); 
		if( Pawn != None && Pawn.Physics == PHYS_None )
			Pawn.SetMovementPhysics(); 
	}

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

@ BeginLabel:
	//log( class$" choose Attack" );
	ChooseAttackMode();
} // AttackingState

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

state @ AttackCloseState extends @ MoveToGoalWithEnemyState
{
    ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise;
	//mdf-tbd: -- hmm borks moving around friendly NPCs...
	//ignores NotifyBump, SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise;

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

	event MayFall()
	{
		if( MoveTarget != ControllerEnemy )
			return;

		Pawn.bCanJump = ActorReachable( ControllerEnemy );
		if( !Pawn.bCanJump )
			GotoState( AttackTacticalMoveState, DontCloseLabel );
	}

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

	function FearThisSpot( Actor aSpot )
	{
		Destination = Pawn.Location + 120 * Normal( Normal( Destination - Pawn.Location ) + Normal( Pawn.Location - aSpot.Location ) ); 
		GotoState( AttackTacticalMoveState, MoveActiveStrafeLabel );
	}

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

	function TryToDodge( vector DuckDir, bool bDuckLeft )
	{
		if( FRand() < 0.6 )
		{
			Global.TryToDodge( DuckDir, bDuckLeft );
			return;
		}
		if( MoveTarget == ControllerEnemy ) 
			TryStrafe( DuckDir );
	}

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

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

		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 bool TryStrafe( vector SideDir )
	{ 
		local vector Extent, HitLocation, HitNormal;
		local Actor HitActor;

		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;
		}
		Destination = Pawn.Location + 250 * SideDir;
		GotoState( AttackTacticalMoveState, MoveActiveStrafeLabel );
		return true;
	}
			
	//-------------------------------------------------------------------------

	function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
	{
		local float Pick;
		local vector SideDir, Extent;
		local bool bWasOnGround;

		#debug DMAI( "DamageAttitudeTo" );
		bWasOnGround = ( Pawn.Physics == PHYS_Walking );

		if( Pawn.Health <= 0 )
			return;

		if( NextState == TakeHitState )
		{
			if( GetReactionToEnemy( ControllerEnemy ) == REACTION_Fear )
			{
				NextState = AttackRetreatState;
				NextLabel = BeginLabel;
			}
			else if( StrafeFromDamage( damage, DamageType, false ) )
			{
				NextState = AttackTacticalMoveState;
				NextLabel = DontCloseLabel;
			}
			else
			{
				NextState = AttackCloseState;
				NextLabel = TakeHitLabel;
			}
			GotoState( TakeHitState ); 
		}
		else if( StrafeFromDamage( damage, DamageType, true ) )
			return; 
		else 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 SharedTimerEvent()
	{
		//DMTNS( "SharedTimerEvent" );

		bReadyToAttack = true;
		if( ControllerEnemy == None )
		{
			GotoState( AttackingState );
			return;
		}

		// mdf-tbd: ick
		if( !SpecialAttackTransition() )
		{
			//DMTNS( "not special attack transition" );

			if( IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) )
			{
				//DMTNS( "is prepared for ranged attack (checking rand vs 0.4 + 0.6*GetSkill())" );

				if((FRand() > 0.4 + 0.6 * GetSkill()) )
				{
					//DMTNS( "going attacking" );
					#debug DMAI( "going to AttackStationaryState " $ GetContext() );
					GotoState( AttackStationaryState );
				}
			}
		}
		else
		{
			//DMTNS( "not attacking" );
		}
	}

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

	//!!mdf(tbd) don't predict through floor under target		
	function vector GetPredictedChargeLocation( Pawn TargetPawn )
	{
		local vector PredictedLocation;

		class'UtilGame'.static.GetBestPredictedLocation( Pawn, ControllerEnemy, Pawn.GroundSpeed, 0.0, PredictedLocation );
			
		PredictedLocation = Pawn.Location + Pawn.CollisionRadius*2.0*Normal( PredictedLocation - Pawn.Location );

		return PredictedLocation;
	}

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

	function bool CanPredict( Actor TargetActor )
	{
		// tbd: do an extent trace and/or full reachability check?
		// reachability could be optional, e.g. dumb creatures might blindly attack enemy?
		return ( U2PBasic.bPredictChargeLocation && Pawn.FastTrace( Pawn.Location, TargetActor.Location ) );
	}

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

	function eventEnemyNotVisible()
	{
		GotoState( AttackHuntState ); 
	}

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

	function ETacticalMoveType GetTacticalMoveType()
	{
		if( GetSkill() >= 0.5 && !Level.Game.bTeamGame && IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) && FRand() < 0.75 )
			return TMT_Basic;
		else
			return TMT_None;
	}

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

	event EndState()
	{
		if( Pawn != None )
			Pawn.bCanJump = (Pawn.JumpZ > 0);
	}

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

@ LandedLabel:
	#debug DMAIL( LandedLabel );
	Goto( CloseLabel );

@ BeginLabel:
	#debug DMAIL( BeginLabel );

@ CloseLabel:
	#debug DMAIL( CloseLabel );
	
	if( !ValidEnemy( ControllerEnemy ) )
		GotoState( AttackingState );

	if( ControllerEnemy.PhysicsVolume.bWaterVolume )
	{
		if( !Pawn.bCanSwim )
			GotoState( AttackTacticalMoveState, DontCloseLabel );
	}
	else if( !Pawn.bCanFly && !Pawn.bCanWalk )
		GotoState( AttackTacticalMoveState, DontCloseLabel );

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

	if( CanPredict( ControllerEnemy ) || ActorReachable( ControllerEnemy ) )
	{
		if( IsMobile() )
		{
			if( U2PBasic.bPredictChargeLocation )
			{
				// note: MoveToPoint doesn't currently use advanced tactics
				// solutions: a) we don't care (default for now -- may be fine) 
				//            b) use a proxy actor for the destination 
				//			  c) (better than b) have MoveToPoint use same code as MoveToActor
				MoveToPoint( GetPredictedChargeLocation( ControllerEnemy ) );
			}
			else
			{
				MoveToActor( ControllerEnemy, GetTacticalMoveType() );
			}
		}
	}
	else
	{
@ CantReachLabel:
		#debug DMAIL( CantReachLabel );
		//!!mdf-tbd: shouldn't do this -- we could still be facing enemy? 
		//log( "route to enemy"@ControllerEnemy );
		if( !IsMobile() || !FindBestPathToward( ControllerEnemy, true ) )
		{
			Sleep( 0.0 );
			GotoState( AttackTacticalMoveState, DontCloseLabel );
		}
@ MoveActiveLabel:
		#debug DMAIL( MoveActiveLabel );
		if( IsMobile() )
		{
			if( VSize( MoveTarget.Location - Pawn.Location ) < (2.5 * Pawn.CollisionRadius) || FaceTarget( 1.5 ) )
				MoveToActor( MoveTarget, TMT_None, , , ControllerEnemy );	
			else
				MoveToActor( MoveTarget, TMT_None );
		}
	}

	GotoState( AttackingState );

@ TakeHitLabel:
	#debug DMAIL( TakeHitLabel );
	if( MoveTarget == ControllerEnemy )
		MoveToActor( MoveTarget, TMT_None );
	
	Goto( CloseLabel );

@ TurnLabel:
	if( ValidEnemy( ControllerEnemy ) )
	{
		#debug DMAI( "TurnLabel #1" );

		StopMovement( true, true );
		Focus = ControllerEnemy;
		FinishRotation( DefaultRotationThreshold );
		Goto( CloseLabel );
	}
	else
	{
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}
	Stop;

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

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

state @ AttackFallbackState extends @ MoveToGoalWithEnemyState
{
	ignores EnemyNotVisible;

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

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

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

	function eventEnemyNotVisible()
	{
		DMAssert( false , GetContext() );

		/* mdf-tbr: how can this ever get called if EnemyNotVisible is ignored in this state?
		local Pawn P;

		if( OldControllerEnemy != None && LineOfSightTo( OldControllerEnemy ) )
		{
			// swap current enemy (no longer visible) for old one (now visible)
			P = OldControllerEnemy;
			OldControllerEnemy = ControllerEnemy;
			#debug   SetControllerEnemy( P, GetContext() );
			#release SetControllerEnemy( P );
		}
		else if( !ControllerEnemy.IsMobile() )
		{
			// Enemy can't move
			#debug   SetControllerEnemy( OldControllerEnemy, GetContext() );
			#release SetControllerEnemy( OldControllerEnemy );
			OldControllerEnemy = None;
			if( ControllerEnemy == None )
				GS( DefaultState );
		}
		*/
	}

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

	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 ) )
		{
			HandleEnemyNoise( NoiseMaker );
			Pawn.MakeNoise( 1.0 );
		}
	}

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

	function PickDestination()
	{
		local byte TeamPriority;

		if( GetTimeSinceEnemyLastDetected() > 9 )
		{
			#debug   SetControllerEnemy( None, GetContext() );
			#release SetControllerEnemy( None );
		}
			
		if( ControllerEnemy == None )
		{
    		#debug   WhatToDoNext( GetContext() );
    		#release WhatToDoNext();
			return;
		}
		LastAttractCheck = Level.TimeSeconds - 0.1;

		if( FindSpecialAttraction() )
		{
			TeamPriority = PriorityObjective();
   			if( TeamPriority > 16 )
   			{
   				PickLocalInventoryDestination( 160, 1.8 );
   				return;
   			}
   			else if( TeamPriority > 1 )
   			{
   				PickLocalInventoryDestination( 200, 1.0 );
   				return;
   			}
   			else if( TeamPriority > 0 )
   			{
   				PickLocalInventoryDestination( 200, 0.55 );
   				return;
   			}
   			PickLocalInventoryDestination( 400, 0.5 );
   			if( MoveTarget == None )
   			{
   				#debug DMAI( " no destination in fallback!" );
   				Orders = OrdersNone;
   				GotoState( AttackingState );
			}
			return;
		}
		else if( Orders == OrdersAttack || OrdersObject == None )
		{
			#debug DMAI( " attack fallback turned to freelance" );
			Orders = OrdersNone;
			GotoState( AttackingState );
		}
		else if( (VSize( Pawn.Location - OrdersObject.Location ) < 20)
			|| ( (VSize( Pawn.Location - OrdersObject.Location ) < 600) && LineOfSightTo( OrdersObject )) )
		{
			if( StationaryPawn(ControllerEnemy) != None || (GetTimeSinceEnemyLastDetected() > 5 && Orders == OrdersHold) )
			{
				#debug   SetControllerEnemy( OldControllerEnemy, GetContext() );
				#release SetControllerEnemy( OldControllerEnemy );
				OldControllerEnemy = None;
			}
			GotoState( AttackingState );
		}
		else
		{
			FindPathToActor( OrdersObject, MoveTarget );
			if( MoveTarget == None )
			{
				#debug DMAI( "fallback turned to freelance (no Path to " $ OrdersObject $ " )" );
				Orders = OrdersNone;
				GotoState( AttackingState );
			}
		}
	}

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

	function eventBumpEnemy( Pawn Other )
	{
		#debug DMAI( "eventBumpEnemy -- calling MaybeSetEnemy" );
		MaybeSetEnemy( Other );
		if( ControllerEnemy == Other )
			bReadyToAttack = true;
	}

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

	function ETacticalMoveType GetTacticalMoveType()
	{
		if( GetTimeSinceEnemyLastSeen() < 1.0 && GetSkill() > (1.25*FRand()-1) )
			return TMT_Basic;
		else
			return TMT_None;
	}
	
	//-------------------------------------------------------------------------

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

@ MoveSpecialLabel:

@ MoveActiveLabel:
	if( MoveTarget == None )
	{
		Sleep( 0.0 );
		Goto( MovePickDestLabel );
	}
	if( FaceTarget( 1 ) )
	{
		bReadyToAttack = true;
		MoveToActor( MoveTarget, GetTacticalMoveType(), , , ControllerEnemy );
	}
	else
	{
		MoveToActor( MoveTarget, GetTacticalMoveType() );
	}
	Goto( MovePickDestLabel );
} // AttackFallbackState

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

state @ AttackHuntState
{
	ignores EnemyNotVisible; 

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

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

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

	function eventBumpEnemy( Pawn Other )
	{
		#debug DMAI( "eventBumpEnemy -- calling MaybeSetEnemy" );
		MaybeSetEnemy( Other );
		if( ControllerEnemy == Other )
		{
			bReadyToAttack = true;
			EnemyDetected( ControllerEnemy.Location );
			GotoState( AttackingState );
		}
	}

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

	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;
		GotoState( AttackHuntState, MoveSpecialLabel );
	}

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

	function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
	{
		if( Pawn.Health > 0 )
		{
			bFrustrated = true;
			if( NextState == TakeHitState )
			{
				if( GetReactionToEnemy( ControllerEnemy ) == REACTION_Fear )
				{
					NextState = AttackRetreatState;
					NextLabel = BeginLabel;
				}
				else
				{
					NextState = AttackHuntState;
					NextLabel = LandedLabel;
				}
				GotoState( TakeHitState ); 
			}
		}
	}

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

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

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

	function bool MaybeSetEnemy( Pawn NewEnemy, optional bool bAlertingOthers )
	{
		if( Global.MaybeSetEnemy( NewEnemy, bAlertingOthers ) )
		{
			BlockedPath = None;
			bReadyToAttack = true;
			Focus = ControllerEnemy;
			if( U2PBasic.CombatStyle > FRand() )
				GotoState( AttackCloseState ); 
			else
				GotoState( AttackingState );
			return true;
		}
		return false;
	} 

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

	function bool NonRangedFireCheck()
	{
		bReadyToAttack = true;
		return true;
	}

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

	function MaybeClearHuntingEnemy()
	{
		// If no enemy, or I should see him but don't, then give up		
		if( GetTimeSinceEnemyLastDetected() > MaxHuntTime )
		{
			#debug DMAI( "MaybeClearHuntingEnemy clearing enemy" );
			#debug   SetControllerEnemy( None, GetContext() );
			#release SetControllerEnemy( None );
		}
	}

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

	function PickDestination()
	{
		local float MaxDist;
		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 ) )
		{
			#debug   WhatToDoNext( GetContext() );
			#release WhatToDoNext();
			return;
		}
	
		Pawn.bAvoidLedges = false;
		Pawn.bCanJump = (Pawn.JumpZ > 0);
		
		if( ActorReachable( ControllerEnemy ) )
		{
			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
			{
				#debug   WhatToDoNext( GetContext() );
				#release WhatToDoNext();
			}
			return;
		}
		if( Level.TimeSeconds - LastInvFind > 4 - 0.4 * 8*GetSkill() )
		{
			LastInvFind = Level.TimeSeconds;
			MaxDist = 600 + 320 * GetSkill();
			if( PickLocalInventoryDestination( MaxDist, 0.6/MaxDist ) )
				return;
		}

		NumMoveAttempts++;

		ViewSpot = Pawn.Location + Pawn.BaseEyeHeight * vect(0,0,1);
		bCanSeeLastSeen = Pawn.FastTrace( GetLastEnemySeenLocation(), ViewSpot );
		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( FindPathToActor( ControllerEnemy, MoveTarget, 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() )
				{
					GotoState( AttackStakeOutState );
					return;
				}
				else
				{
					#debug   WhatToDoNext( GetContext() );
					#release WhatToDoNext();
					return;
				}
			}
			// control Path weights
			ClearPaths();
			if( BlockedPath != None )
				BlockedPath.Cost = 1500;
			if( FindBestPathToward( ControllerEnemy, false ) )
				return;
		}
		else if( FindBestPathToward( ControllerEnemy, true ) )
			return;

		MoveTarget = None;
		
		if( (NumMoveAttempts > 60) && ShouldGiveUpHunting() )
		{
			U2P.AssetsHelperClass.static.HandleLostEnemy( U2P );
			#debug   WhatToDoNext( GetContext() );
			#release WhatToDoNext();
			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;
				}
				return;
			}
		}

		Pawn.bAvoidLedges = ( Pawn.CollisionRadius > 42 );
		posZ = GetLastEnemyDetectedLocation().Z + Pawn.CollisionHeight - ControllerEnemy.CollisionHeight;
		nextSpot = GetLastEnemyDetectedLocation() - Normal( ControllerEnemy.Velocity ) * Pawn.CollisionRadius;
		nextSpot.Z = posZ;
		if( Pawn.FastTrace( nextSpot, ViewSpot ) )
		{
			Destination = nextSpot;
		}
		else if( bCanSeeLastSeen )
		{
			Destination = GetLastEnemyDetectedLocation();
		}
		else
		{
			Destination = GetLastEnemyDetectedLocation();
			if( !Pawn.FastTrace( GetLastEnemyDetectedLocation(), ViewSpot ) )
			{
				// check if could adjust and see it
				if( PickWallAdjust( Normal( GetLastEnemyDetectedLocation() - ViewSpot ) ) || FindViewSpot() )
				{
					if( Pawn.Physics == PHYS_Falling )
						SetFall();
					else
						GotoState( AttackHuntState, AdjustFromWallLabel );
				}
				else if( VSize( ControllerEnemy.Location - Pawn.Location ) < 1200 )
				{
					GotoState( AttackStakeOutState );
					return;
				}
				else
				{
					#debug   WhatToDoNext( GetContext() );
					#release WhatToDoNext();
					return;
				}
			}
		}
		
		// cheat...
		SetLastEnemyDetectedLocation( ControllerEnemy.Location );
	}	

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

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

		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;
			return true;
		}

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

		return false;
	}

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

	event BeginState()
	{
		//log( Self$" hunting" );
		SetAlertness( 0.5 );
		bTriedLastDetectedLocation = false;
		bDeviousHunting = GetShouldUseDeviousTactics( 0.50,  0.50 );
	}

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

	event EndState()
	{
		bHunting = false;
		RestoreAlertness();

		// mdf-tbd: yet another fix for stupid accessed None because Pawn destroyed
		if( Pawn != None )
		{
			Pawn.bAvoidLedges = Pawn.default.bAvoidLedges;
			Pawn.bCanJump = (Pawn.JumpZ > 0);
		}
	}

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

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

@ BeginLabel:
	ClearMoveAttempts();

@ LandedLabel:

@ HuntLabel:
	FindSpecialAttraction();

	if( bSniping )
		GotoState( AttackStakeOutState );

	if( Orders == OrdersFollow ) 
	{
		if( !LineOfSightTo( Controller(OrdersObject).Pawn ) )
			GotoState( AttackFallbackState );
	}
	else if( Orders == OrdersHold ) 
	{
		if( !LineOfSightTo( OrdersObject ) )
			GotoState( AttackFallbackState );
	}
	else if( Orders == OrdersDefend )
	{
		if( AmbushSpot != None )
		{
			if( !LineOfSightTo( AmbushSpot ) )
				GotoState( AttackFallbackState );
		}
		else if( !LineOfSightTo( OrdersObject ) )
			GotoState( AttackFallbackState );
	}
	WaitForLanding();
	if( CanSee( ControllerEnemy ) )
	{
		#debug DMAI( "AttackHuntState (CanSee) -- calling MaybeSetEnemy" );
		MaybeSetEnemy( ControllerEnemy );
	}
	PickDestination();

@ MoveSpecialLabel:
	if( MoveTarget == None )
		MoveToPoint( Destination );
	else
		MoveToActor( MoveTarget, TMT_None ); 

	Goto( HuntLabel );
} // AttackHuntState

/*-----------------------------------------------------------------------------
Retreating for a bot 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;

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

	event MayFall()
	{
		if( IsFacingTarget( ControllerEnemy, CosMinFacingTargetAngle ) ) // MoveTarget is player, 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 );
			GotoState( AttackingState );
		}
	}

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

	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 );
			GotoState( AttackingState );
		}
	}

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

	function PickDestination()
	{
		local float MaxDist, BestWeight;
		local Actor BestPath;

		if( !bReadyToAttack && TimerRate == 0.0 )
			SetSharedTimer( 0.7, false );

		// do I still fear my enemy?
		if( (GetTimeSinceEnemyLastDetected() > 12 ) || (Level.Game.bTeamGame && (GetTimeSinceEnemyLastDetected() > 8)) )
		{
			#debug   SetControllerEnemy( None, GetContext() );
			#release SetControllerEnemy( None );
		}
		if( ( ControllerEnemy == None ) || ( GetReactionToEnemy( ControllerEnemy ) > REACTION_Fear ) )
		{
			GotoState( AttackingState );
			return;
		}

		//first look at nearby inventory < 500 Dist
		MaxDist = 500 + 320 * GetSkill();
		if( PickLocalInventoryDestination( MaxDist, 0.001 ) )
			return;

		 // look for long distance inventory 
		BestWeight = FindBestInventoryPath( BestPath, 0.0, false );
		if( Level.Game.bTeamGame && BestWeight < 0.0002 )
		{
			if( StationaryPawn(ControllerEnemy) == None && (ControllerEnemy.Location.Z < Pawn.Location.Z + 500) )
			{
				bKamikaze = true;
				if( LineOfSightTo( ControllerEnemy ) )
				{
					LastInvFind = Level.TimeSeconds;
					GotoState( AttackTacticalMoveState, DontCloseLabel );
					return;
				}
			}
		}
		if( BestPath != None )
		{
			MoveTarget = BestPath;
			return;
		}

		#debug DMAI( " give up retreat" );

		// if nothing, then tactical move
		if( LineOfSightTo( ControllerEnemy ) )
		{
			LastInvFind = Level.TimeSeconds;
			bKamikaze = true;
			GotoState( AttackTacticalMoveState, DontCloseLabel );
			return;
		}

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

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

	function ChangeDestination()
	{
		local Actor OldTarget;
		local Actor Path;
		
		OldTarget = Home;
		PickDestination();
		if( Home == OldTarget )
		{
			bKamikaze = true;
			//log( "same old target" );
			GotoState( AttackTacticalMoveState, TacticalTickLabel );
		}
		else
		{
			FindPathToActor( Home, Path );
			if( Path == None )
			{
				//log( "no new target" );
				bKamikaze = true;
				GotoState( AttackTacticalMoveState, TacticalTickLabel );
			}
			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, true, U2Weapon.RatingIneffective ) )
		{
			bReadyToAttack = true;
			GotoState( AttackStationaryState );
		}
	}
	
	//-------------------------------------------------------------------------

	function ReachedHome()
	{
		if( LineOfSightTo( ControllerEnemy ) )
			ChangeDestination();
		else
		{
			bKamikaze = true;
			GotoState( AttackingState );
		}
	}

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

	function PickNextSpot()
	{
		local Actor Path;

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

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

@ BeginLabel:
	if( bReadyToAttack && ( FRand() < 0.8 - 0.8 * GetSkill() ) )
		bReadyToAttack = false;
	if( TimerRate == 0.0 || !bReadyToAttack )
		SetSharedTimer( TimeBetweenAttacks, false );

@ MovePickDestLabel:
	WaitForLanding();
	PickDestination();

@ MoveActiveLabel:
	if( MoveTarget == None )
	{
		Sleep( 0.0 );
		Goto( MovePickDestLabel );
	}
	if( InventorySpot(MoveTarget) != None && 
		InventorySpot(MoveTarget).markedItem != None && 
		InventorySpot(MoveTarget).markedItem.ReadyToPickup( 0.0 ) && 
		Desireability( InventorySpot(MoveTarget).markedItem ) > 0 )
	{
			MoveTarget = InventorySpot( MoveTarget ).markedItem;
	}
	if( FaceTarget( 2 ) )
		MoveToActor( MoveTarget, GetTacticalMoveType(), , , ControllerEnemy );
	else
		MoveToActor( MoveTarget, GetTacticalMoveType() );
	Goto( MovePickDestLabel );
} // AttackRetreatState

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

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

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

	function bool ContinueAttackStationary()
	{
		if( AttackStationaryStopTime <= Level.TimeSeconds )
			return false;

		if( NeedToTurn( ControllerEnemy.Location, NeedToTurnAngleCos ) )
			return false;

		return ( CanFire( false ) && IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) );
	}

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

	function DoRangedAttack()
	{
		Global.DoRangedAttack();

		//!!mdf-tbd: support non-weapon using NPCs
		if( Pawn != None && U2Weapon(Pawn.Weapon) != None )
		{
			if( (bFire == 1 && U2Weapon(Pawn.Weapon).FireTime > 0.5 ) ||
				(bAltFire == 1 && U2Weapon(Pawn.Weapon).AltFireTime > 0.5) )
			{
				bReadyToAttack = false;
				GotoState( AttackTacticalMoveState );
			}
		}
	}

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

	function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
	{
		if( Pawn.Health > 0 )
		{
			if( NextState == TakeHitState )
			{
				NextState = AttackStationaryState;
				NextLabel = BeginLabel;
			}
		}
	}

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

	#debug   function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo, string ContextStr )
	#release function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo )
    {
		#debug DMAIA( "StopFiring -- going to attacking" );
		#debug   Global.StopFiring( SuggestedFireAgainDelay, SFInfo, ContextStr );
		#release Global.StopFiring( SuggestedFireAgainDelay, SFInfo );
		GotoState( AttackingState );
	}

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

	function eventEnemyNotVisible()
	{
		////log( "enemy not visible" );
		//let attack animation complete
		if( bFiringPaused )
			return;

		if( !IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) || (FRand() < 0.13) )
		{
			bReadyToAttack = true;
			//DMTNS( "eventEnemyNotVisible -- going to attacking" );
			GotoState( AttackingState );
			return;
		}
	}

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

	function KeepAttacking()
	{
		local int BaseSkill;

		if( bFiringPaused )
		{
			//DMTNS( "KeepAttacking - bFiringPaused" );
			if( TimerRate <= 0.0 )
				GotoState( NextState, NextLabel );

			if( !ValidEnemy( ControllerEnemy  ) || !LineOfSightTo( ControllerEnemy ) )
			{
				bFire = 0;
				bAltFire = 0; 
				GotoState( NextState, NextLabel );
			}
		}

		if( !ValidEnemy( ControllerEnemy ) || !LineOfSightTo( ControllerEnemy ) || !IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) )
		{
			//DMTNS( "KeepAttacking - enemy not valid or lost LOS" );

			bFire = 0;
			bAltFire = 0; 
			GotoState( AttackingState );
			return;
		}

		bReadyToAttack = FDecision( AttackReadyToAttackOdds );

		if( ContinueAttackStationary() && bReadyToAttack )
		{
			return; // enemy is valid and can still see him so keep attacking
		}
		else 
		{
			#debug   StopFiring( 0.0, SFI_Behavior, GetContext() );
			#release StopFiring( 0.0, SFI_Behavior );
		}
		
		if( IsPreparedToMelee( true ) )
		{
			bReadyToAttack = true;
			//DMTNS( "KeepAttacking - IsPreparedToMelee( true )" );
			GotoState( AttackTacticalMoveState );
			return;
		}

		BaseSkill = 8*GetSkill();
		if( ControllerEnemy.Controller.IsPreparedToMelee( false ) && VSize( ControllerEnemy.Location - Pawn.Location ) < 500 )
			BaseSkill += 3;

		if( (BaseSkill > 3*FRand() + 2) || ((bFire + bAltFire == 0) && (BaseSkill > 6*FRand() - 1)) )
		{
			bReadyToAttack = true;
			//DMTNS( "KeepAttacking - going to tactical based on skill" );
			GotoState( AttackTacticalMoveState );
		}
	}

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

	function SharedTimerEvent()
	{
		//DMTNS( "SharedTimerEvent" );
		
		if( bFiringPaused )
		{
			//DMTNS( "SharedTimerEvent jumping to " $ NextState );
			GotoState( NextState, NextLabel );
		}
	}

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

	function CheckAttackStatus()
	{
		//!!mdf-refactor this crap

		if( !ValidEnemy( ControllerEnemy ) )
		{
			bFire = 0;
			bAltFire = 0; 
			GotoState( AttackingState );
			return;
		}

		if( ContinueAttackStationary() )
		{
			DoRangedAttack();
			return; // enemy is valid and can still see him (no eventEnemyNotVisible) so keep attacking
		}

		if( !IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) || !IsFiring() )
		{
			//DMTNS( "CheckAttackStatus - !IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) || !IsFiring()" );
			GotoState( AttackingState );
			return;
		}
		else
		{
			GotoLabel( AttackDoneLabel );
			return;
		}
		
		// mib-tbd temporarily bypassed this code to force npcs to leave this state
		if( FRand() - 1.2*GetSkill() < 0 )
		{
			//DMTNS( "CheckAttackStatus - goint to AttackStationaryState based on skill" $ GetContext() );
			GotoLabel( AttackDoneLabel );
		}
		else
		{
			DoRangedAttack();
		}
	}
	
	//-------------------------------------------------------------------------

	function SpecialFire()
	{
		if( ControllerEnemy == None )
			return;
		bFiringPaused = true;
		SetSharedTimer( 0.75 + VSize( ControllerEnemy.Location - Pawn.Location )/Pawn.Weapon.GetProjSpeed( true ), false );
		NextState = AttackingState;
		NextLabel = BeginLabel; 
	}

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

	function bool NonRangedFireCheck()
	{
		return false;
	}

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

	event BeginState()
	{
		local byte IncomingStance;

		if( bFiringPaused )
			SetSharedTimer( 0.75 + VSize( ControllerTarget.Location - Pawn.Location )/Pawn.Weapon.GetProjSpeed( true ), false );

		if( AttackStationaryStopTime > Level.TimeSeconds )
		{
			if( SelectStance( false ) )
				GotoLabel( StanceChangeDelayLabel );
		}
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		bFiringPaused = false;
		#debug   SetControllerTarget( None, GetContext() );
		#release SetControllerTarget( None );
		bFire = 0;
		bAltFire = 0;
		AttackStationaryStopTime = -1.0;

		// mdf-tbd: odds of keeping stance for movement (crouching only)
		if( StationaryStance == ST_None && !LPawn.IsStanding() && FDecision( U2PBasic.StationaryStandOdds ) )
			UpdateStance( ST_Standing ); //!!mdf-tbd: animation issues
	}

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

@ ChallengeLabel:
	#debug DMAIL( ChallengeLabel );
	StopMovement( true, false );
	Pawn.DesiredRotation = rotator( ControllerEnemy.Location - Pawn.Location );
	//TBD (servo) Pawn.PlayChallenge();
	//TBD (servo) #debug DMAIL( "FinishAnim #1 -- begin" );
	//TBD (servo) FinishAnim();
	//TBD (servo) #debug DMAIL( "FinishAnim #1 -- end" );
	//TBD (servo) Pawn.TweenToFighter( 0.1 );
	Goto( FaceTargetLabel );

@ BeginLabel:
	#debug DMAIL( BeginLabel );
	if( GetTarget() == None )
	{
		//DMTNS( "no target -- going to attacking" );
		GotoState( AttackingState );
	}
	StopMovement( true, false );
	
@ FaceTargetLabel:
	#debug DMAIL( FaceTargetLabel );
	Focus = GetTarget();
	if( NeedToTurn( Focus.Location, NeedToTurnAngleCos ) )
	{
		//DMTNS( "turn to target: " $ Target );
		#debug DMAIL( "FinishRotation -- begin" );
		FinishRotation( DefaultRotationThreshold );
		#debug DMAIL( "FinishRotation -- end" );
	}
	//TBD (servo) #debug DMAIL( "FinishAnim #2 -- begin" );
	//TBD (servo) FinishAnim();
	//TBD (servo) #debug DMAIL( "FinishAnim #2 -- end" );

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

	#debug DMAIA( "do ranged attack: " $ Focus );
	DoRangedAttack();

	if( IsPreparedToMelee( true ) )
	{
		//DMTNS( "IsPreparedToMelee( true )" );
		GotoState( AttackingState );
	}
@ AttackOngoingLabel:
	#debug DMAIL( AttackOngoingLabel );
	//DMTNS( "AttackOngoingLabel AnimSequence=" $ Pawn.AnimSequence $ " frame = " $ Pawn.AnimFrame $ "/" $ Pawn.GetAnimFrames( Pawn.AnimSequence ) );
	if( GetTarget() == None )
	{
		//DMTNS( "no target #2 -- going to attacking" );
		GotoState( AttackingState );
	}
	Focus = GetTarget();
	CheckAttackStatus();

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

@ AttackDoneLabel:
	#debug DMAIL( AttackDoneLabel );
	KeepAttacking();
	Goto( FaceTargetLabel );

@ StanceChangeDelayLabel:
	FinishAnim();
	Goto( ChallengeLabel );
} // AttackStationaryState

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

state @ AttackStakeOutState
{
	ignores EnemyNotVisible; 

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

	function bool RandomizeStakeOutDir()
	{
		return Level.Game.bTeamgame;
	}
	
	//-------------------------------------------------------------------------

	function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
	{
		if( Pawn.Health > 0 )
		{
			bFrustrated = true;
			EnemyDetected( ControllerEnemy.Location );
			if( NextState == TakeHitState )
			{
				if( GetReactionToEnemy( ControllerEnemy ) == REACTION_Fear )
				{
					NextState = AttackRetreatState;
					NextLabel = BeginLabel;
				}
				else
				{
					NextState = AttackingState;
					NextLabel = BeginLabel;
				}
				GotoState( TakeHitState ); 
			}
			else
				GotoState( AttackingState );
		}
	}

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

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

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

	function SetFall()
	{
		NextState = AttackStakeOutState; 
		NextLabel = BeginLabel;
		GotoState( FallingState ); 
	}

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

	function bool MaybeSetEnemy( Pawn NewEnemy, optional bool bAlertingOthers )
	{
		if( Global.MaybeSetEnemy( NewEnemy, bAlertingOthers ) )
		{
			bReadyToAttack = true;
			Focus = ControllerEnemy;
			GotoState( AttackingState );
			return true;
		}
		return false;
	} 
	
	//-------------------------------------------------------------------------

	function SharedTimerEvent()
	{
		bReadyToAttack = true;
		Enable( Event_NotifyBump );
		SetSharedTimer( 1.0, false );
	}

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

	function bool AdjustAim( class<Projectile> ProjectileClass, float ProjSpeed, vector ProjStart, float WeaponFireSpread, bool bLeadTarget, bool bWarnTarget, bool bTossed, bool bTrySplash )
	{
		local vector FireSpot, X, Y, Z;
		local Actor HitActor;
		local vector HitLocation, HitNormal;

		#debug DMAIA( "AdjustAim" );				
		FireSpot = GetLastEnemySeenLocation();
			 
		HitActor = Pawn.Trace( HitLocation, HitNormal, FireSpot, ProjStart, false );
		if( HitActor != None ) 
		{
			FireSpot += 2 * ControllerEnemy.CollisionHeight * HitNormal;
			bClearShot = Pawn.FastTrace( FireSpot, ProjStart );
			if( !bClearShot )
			{
				#debug   StopFiring( 0.2, SFI_NoLOS, GetContext() );
				#release StopFiring( 0.2, SFI_NoLOS );
				return false;
			}
		}

		//!!mdf-tbd: 
		//	Perfect aim here for most weapons (tossed projectiles not included) --
		//  -- should we be calling Global.AdjustAim to aim at FireSpot (use a 
		// proxy actor to set as target)?
		SetRotation( rotator( FireSpot - ProjStart ) );
		return true;
	}
	
	//-------------------------------------------------------------------------

	function bool ClearShot()
	{
		local bool bResult;
		local vector LastSeenLocation;
		
		//!!mdf-tbd: NPCs seem to be trying to shoot through walls with pistol etc. when in stakeout?

		LastSeenLocation = GetLastEnemySeenLocation();
		if( Pawn.Weapon == None ||
			(Pawn.Weapon.bSplashDamage && VSize( Pawn.Location - LastSeenLocation ) < 300) ||
			!Pawn.FastTrace( LastSeenLocation + vect(0,0,0.9)*ControllerEnemy.CollisionHeight, Pawn.Location ) )
		{
			bFire = 0;
			bAltFire = 0;
			bResult = false;
		}
		else
		{
			bResult = true;
		}

		return bResult;
	}
	
	//-------------------------------------------------------------------------

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

		if( bStationary )
		{
		 	// tend to stake out longer if stationary (singleplayer)
			bResult = (GetTimeSinceEnemyLastSeen() <= 8.0 && ClearShot() && CanStakeOut());
		}
		else if( ControllerEnemy != None )
		{
			StrengthDelta = RelativeStrength( ControllerEnemy );
			bResult = ( (VSize( ControllerEnemy.Location - Pawn.Location ) <= 300 + (FRand() * StrengthDelta - U2PBasic.CombatStyle)*350) &&
						(GetTimeSinceEnemyLastSeen() <= 2.5 + FMax( -1, 3*(FRand() + 2*(StrengthDelta - U2PBasic.CombatStyle)))) &&
						ClearShot() &&
						CanStakeOut() );
		}

		return bResult;
	}

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

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

	//-------------------------------------------------------------------------
	
	event EndState()
	{
		RestoreAlertness();
		SetLastEnemyDetectedLocation( RealLastDetectedLocation );
		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   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}
	StopMovement( true, false );
//TBD (servo) Pawn.PlayChallenge();
	Focus = None;
	FocalPoint = GetLastEnemyDetectedLocation();
	FinishRotation( DefaultRotationThreshold );
	if( ControllerEnemy == None )
	{
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}
	
	if( IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) && FRand() < 0.5 && VSize( ControllerEnemy.Location - GetLastEnemyDetectedLocation() ) < 150 && ClearShot() && CanStakeOut() )
	{
		DoRangedAttack();
	}
	else
	{
		bFire = 0;
		bAltFire = 0;
	}
//TBD (servo) if( ( 8*GetSkill() <= 4 ) && ( FRand() >= 0.65 ) )
//TBD (servo) 		Pawn.PlayChallenge();
	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( IsMobile() )
	{
		if( bSniping )
		{
			#debug   WhatToDoNext( GetContext() );
			#release WhatToDoNext();
		}
		BlockedPath = None;	
		GotoState( AttackHuntState, LandedLabel );
	}
	else
	{
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}
} // AttackStakeOutState

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

state @ AttackTacticalMoveState
{
	// mdf-tbd: ignore bumps also? If nothing else, swarming araknids are generating tons of friendly bumps
	// borks dealing with clustering...
	//ignores NotifyBump, Bump, SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise;
	ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise;

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

	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 SetFall()
	{
		StopMovement( true, false );
		Destination = Pawn.Location;
		NextState = AttackingState;
		NextLabel = BeginLabel;
		GotoState( FallingState );
	}

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

	function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
	{
		if( Pawn.Health > 0 )
		{
			if( NextState == TakeHitState )
			{
				NextState = AttackTacticalMoveState;
				NextLabel = TakeHitLabel;
				GotoState( TakeHitState ); 
			}
		}
	}

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

	event bool NotifyHitWall( vector HitNormal, Actor Wall )
	{
		if( Pawn.Physics == PHYS_Falling )
			return false;

		if( ControllerEnemy == None )
		{
			GotoState( AttackingState );
			return false;
		}
		if( bChangeDir || FRand() < 0.5 || ((ControllerEnemy.Location - Pawn.Location) dot HitNormal) < 0 )
		{
			Focus = ControllerEnemy;
			GiveUpTactical( IsMobile() );
		}
		else
		{
			bChangeDir = true;
			Destination = Pawn.Location - HitNormal * FRand() * 500;
		}
		return false;
	}

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

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

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

	function SharedTimerEvent()
	{	
		//DMTNS( "SharedTimerEvent" );

		bReadyToAttack = true;
		Enable( Event_NotifyBump );
		if( ControllerEnemy == None )
			return;

		// mdf-tbd: ick
		if( !SpecialAttackTransition() )
		{
			if( IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) && !ControllerEnemy.Controller.IsPreparedToMelee( false ) && (FRand() > 0.3 + 0.8 * GetSkill() ) )
			{
				GotoState( AttackStationaryState );
			}
		}
	}

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

	function eventEnemyNotVisible()
	{
		if( !bGathering && Aggressiveness > RelativeStrength( ControllerEnemy ) )
		{
			if( Pawn.FastTrace( ControllerEnemy.Location, GetLastEnemySeenLocation( ) ) && IsMobile() )
				GotoLabel( RecoverEnemyLabel );
			else
				GotoState( AttackingState );
		}
		Disable( 'EnemyNotVisible' );
	}
		
	//-------------------------------------------------------------------------

	function GiveUpTactical( bool bCanCharge )
	{	
		if( bCanCharge && (IsPreparedToMelee( true ) || (2 * U2PBasic.CombatStyle + 0.8 * GetSkill() > FRand())) )
		{
			GotoState( AttackCloseState );
		}
		else if( IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) )
		{
			if( bReadyToAttack && IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) && GetSkill() >= 0.5 )
			{
				GotoState( AttackStationaryState );
			}
			else
			{
				GotoState( AttackStationaryState, ChallengeLabel ); 
			}
		}
		else
		{
			GotoState( AttackingState );
		}
	}		

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

	function PawnIsInPain( PhysicsVolume PainVolume )
	{
		GotoState( AttackRetreatState );
	}

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

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

		#debug DMAI( "TacticalMove.PickRegDestination: " $ bCanCharge );

		if( !ValidEnemy( ControllerEnemy ) )
		{
			GotoState( AttackingState );
			return;
		}

		bGathering = false;
		if( Orders == OrdersHold || !IsMobile() )
			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;
		}
		if( ControllerEnemy.PhysicsVolume.bWaterVolume )
			bCanCharge = bCanCharge && Pawn.bCanSwim;
		else 
			bCanCharge = bCanCharge && (Pawn.bCanFly || Pawn.bCanWalk);
		
		if( bCanCharge && IsPreparedToMelee( true ) )
		{
			GotoState( AttackCloseState );
			return;
		}
		EnemyDist = VSize( Pawn.Location - ControllerEnemy.Location );
		if( (!IsMobile() || (FRand() > 0.3 + 1.2 * GetSkill())) && 
			(EnemyDist > 900 || !ControllerEnemy.Controller.IsPreparedToMelee( false ) ) && 
			(PriorityObjective() == 0) )
		{
			#debug DMAI( "calling GiveUpTactical #1" );
			GiveUpTactical( false );
		}

		bSuccess = false;
		if( ( bSniping || ( Orders == OrdersHold ) )  
			&& ( PriorityObjective() == 0 ) )
			bCanCharge = false;

		if( bSniping && Pawn.Weapon.bInstantHit )
		{
			bReadyToAttack = true;
			GotoState( AttackStationaryState );
			return;
		}
						
		Aggression = 2 * ( U2PBasic.CombatStyle + FRand() ) - 1.1;
		if( ControllerEnemy != None && ControllerEnemy.IsPlayerPawn() && ( GetReactionToEnemy( ControllerEnemy ) == REACTION_Fear ) && ( U2PBasic.CombatStyle > 0 ) )
			Aggression = Aggression - 2 - 2 * U2PBasic.CombatStyle;

		// adjust Aggression based on attack capabilities (weapon or animation-based attack)
		if( !IsPreparedToAttack( true ) )
		{
			Aggression += 2 * StyleRunAway;
		}
		else
		{
			// mdf-tbd: 2nd parameter should be passed the likely use (fire/altfire) for the weapon.
			// but we pbly don't want to call RateSelf here (slow & might not get same result as
			// when weapon 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( ControllerEnemy );
		}

		//!!mdf-handle enemy which doesn't use weapons (animation-based attacks)
		if( ControllerEnemy != None && ControllerEnemy.Weapon != None )
		{
			// adjust Aggression based on enemy's weapon
			Aggression += 2 * ControllerEnemy.Weapon.SuggestDefenseStyle( Pawn );
		}

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

		if( EnemyDist > 1000 )
			Aggression += 1;
		if( bCanCharge )
			bCanCharge = ( Aggression >= FRand() );

		if( ( Pawn.Physics == PHYS_Walking ) || ( Pawn.Physics == PHYS_Falling ) )
		{
			if( Pawn.Location.Z > ControllerEnemy.Location.Z + 150 ) //tactical height advantage
				Aggression = FMax( 0.0, Aggression - 1.0 + U2PBasic.CombatStyle );
			else if( Pawn.Location.Z < ControllerEnemy.Location.Z - Pawn.CollisionHeight ) // below enemy
			{
				if( bCanCharge && Aggression > 0 &&  FRand() < 0.6 )
				{
					GotoState( AttackCloseState );
					return;
				}
				else if( ( EnemyDist < 1.1 * ( ControllerEnemy.Location.Z - Pawn.Location.Z ) ) 
						&& !ActorReachable( ControllerEnemy ) ) 
				{
					bNoReach = true;
					Aggression = -1.5 * FRand();
				}
			}
		}
	
		if( bCanCharge && Aggression > (2 * FRand()) )
		{
			if( bNoReach && (Pawn.Physics != PHYS_Falling) )
				GotoState( AttackCloseState, CantReachLabel );
			else
				GotoState( AttackCloseState );
			return;
		}

		if( UseTacticalJumps() && (U2PBasic.bJumpy || (FRand()*8*GetSkill() > 2.3)) )
		{
			GetAxes( Rotation, X, Y, Z );

			if( FRand() < 0.5 )
			{
				Y *= -1;
				TryToDodge( Y, false );
			}
			else
				TryToDodge( Y, true );
		}
			
		if( ( ( ControllerEnemy.Velocity - Pawn.Velocity ) dot ( ControllerEnemy.Location - Pawn.Location ) ) > 0 )
			Aggression += 0.4 * FRand();
			 
		EnemyDir = ( ControllerEnemy.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 ) || ( ControllerEnemy.IsPlayerPawn() && ( GetReactionToEnemy( ControllerEnemy ) == 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 )
		{
			#debug DMAI( "calling GiveUpTactical #2" );
			GiveUpTactical( bCanCharge );
		}
		else 
		{
			// mdf-tbd: added Pawn.Weapon != None for basic NPC use -- could go away if this code moved to Advanced
			// mdf-tbd: should !NeedToTurn test go into || (has X || Y && Z currently)?
			if( U2PBasic.bJumpy || 
				(Pawn.Weapon != None &&
				 Pawn.Weapon.bRecommendSplashDamage && 
				 (FRand() < 0.1 + 0.8 * GetSkill()) && 
				 (ControllerEnemy.Location.Z - ControllerEnemy.CollisionHeight <= Pawn.Location.Z + Pawn.MaxStepHeight - Pawn.CollisionHeight)) && 
				!NeedToTurn( ControllerEnemy.Location, NeedToTurnAngleCos ) )
			{
				FireAt( ControllerEnemy );
				if( ( U2PBasic.bJumpy && ( FRand() < 0.75 ) ) || Pawn.Weapon.SplashJump() )
				{
					// try jump move
					Pawn.SetPhysics( PHYS_Falling );
					StopMovement( true, false );
					Destination = MinDest;
					NextState = AttackingState; 
					NextLabel = BeginLabel;
					GotoState( FallingState );
					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;
			}
		}
	}

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

	function PickDestination( bool bCanCharge )
	{
		local float MaxDist;

		#debug DMAI( "TacticalMove.PickDestination: " $ bCanCharge );
		// possibly Pick nearby inventory
		// higher skill bots will always strafe, lower skill
		// both do this less, and strafe less

		if( !bReadyToAttack && TimerRate == 0.0 )
			SetSharedTimer( 0.7, false );

		if( !IsMobile() || (Level.TimeSeconds - LastInvFind < 5 - 4 * GetSkill()) )
		{
			PickRegDestination( bCanCharge );
		}
		else
		{
			LastInvFind = Level.TimeSeconds;
			bGathering = false;
			MaxDist = 700 + 240 * GetSkill();
			if( PickLocalInventoryDestination( MaxDist, 0.5/MaxDist ) )
				bGathering = true;
			else
				PickRegDestination( bCanCharge );
		}
	}

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

	event BeginState()
	{
		MinHitWall += 0.15;
		bAdjustFromWalls = false;
		if( Pawn != None )
		{
			Pawn.bAvoidLedges = true;
			Pawn.bStopAtLedges = true;
			Pawn.bCanWalkOffLedges = false;
			Pawn.bCanJump = false;
		}
	}
	
	//-------------------------------------------------------------------------

	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);
		}
	}

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

@ TacticalTickLabel:
	Sleep( 0.02 );

@ BeginLabel:
	Focus = ControllerEnemy;
	Destination = ControllerEnemy.Location;
	WaitForLanding();

	PickDestination( IsMobile() );

@ MoveActiveLabel:
	if( IsMobile() )
	{
		if( !Pawn.bCanStrafe )
		{ 
			MoveToPoint( Destination );
		}
		else
		{
@ MoveActiveStrafeLabel:
			MoveToPoint( Destination, , ControllerEnemy );	
		}
	}

	if( ControllerEnemy != None && !LineOfSightTo( ControllerEnemy ) && Pawn.FastTrace( ControllerEnemy.Location, GetLastEnemySeenLocation() ) && IsMobile() )
	{
		Goto( RecoverEnemyLabel );
	}
	else
	{
		bReadyToAttack = true;
		GotoState( AttackingState );
	}
	
@ DontCloseLabel:
	Focus = ControllerEnemy;
	Destination = ControllerEnemy.Location;
	WaitForLanding();

	PickDestination( false );

@ TakeHitLabel:
	Goto( MoveActiveLabel );

@ RecoverEnemyLabel:
	bReadyToAttack = true;
	HidingSpot = Pawn.Location;
	if( IsMobile() )
	{
		Destination = GetLastEnemySeenLocation() + 4 * Pawn.CollisionRadius * Normal( GetLastEnemySeenLocation() - Pawn.Location );
		MoveToPoint( Destination, , ControllerEnemy );
	}

	if( CanFire( false ) && IsPreparedToFire( true, true, U2Weapon.RatingIneffective ) && LineOfSightTo( ControllerEnemy ) )
	{
		// mdf-tbd: cleanup this mess -- Focus should be handled already in FireAt -- look at all cases like this
		Focus = ControllerEnemy;
		FireAt( ControllerEnemy );
		StopMovement( true, false );
		if( Pawn.Weapon.bSplashDamage )
		{
			bFire = 0;
			bAltFire = 0;
			bReadyToAttack = true;
			Sleep( 0.2 );
		}
		else
			Sleep( 0.35 + 0.3 * FRand() );

		if( ( FRand() + 0.1 > U2PBasic.CombatStyle ) )
		{
			bFire = 0;
			bAltFire = 0;
			bReadyToAttack = true;
			Enable( 'EnemyNotVisible' );
			Destination = HidingSpot + 4 * Pawn.CollisionRadius * Normal( HidingSpot - Pawn.Location );
			Goto( MoveActiveLabel );
		}
	}

	GotoState( AttackingState );
} // AttackTacticalMoveState

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

state @ DeadState
{
	ignores EnemyNotVisible, HearNoise, NotifyBump, SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend; // sensory input
	ignores BeginFalling, NotifyLanded, NotifyHitWall, NotifyHeadVolumeChange, NotifyPhysicsVolumeChange; // physics
	ignores eventTakeDamage, eventTookDamage, ShotFiredNotification, SetTestMoveTarget; // other

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

	event BeginState()
	{
		Super.BeginState();
		ClearHoldSpots();
	}
}

//-----------------------------------------------------------------------------
// Used when NPC's head is in a waterzone & he needs to get to the surface to
// breathe.

//mdf-tbd: nothing uses this currently, used to be handled through PainTimer in UT436 code
state @ FindAirState
{
	ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise, NotifyBump;

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

	event bool NotifyHeadVolumeChange(PhysicsVolume NewHeadVolume)
	{
		Global.NotifyHeadVolumeChange(newHeadVolume);
		if ( !newHeadVolume.bWaterVolume )
			GotoState( AttackingState );
		return false;
	}

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

	event bool NotifyHitWall( vector HitNormal, actor Wall )
	{
		// change direction
		Destination = 200 * (Normal(Destination - Pawn.Location) + HitNormal);
		return false;
	}

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

	function SharedTimerEvent()
	{
		bReadyToAttack = true;
		SetSharedTimer( 0.5, false );
	}

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

	function eventEnemyNotVisible()
	{
		////log("enemy not visible");
		bReadyToAttack = false;
	}

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

	function PickDestination()
	{
		Destination = VRand();
		Destination.Z = 1;
		Destination = Pawn.Location + 200 * Destination;				
	}

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

	event BeginState()
	{
		bAdjustFromWalls = false;
	}

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

	event EndState()
	{
		bAdjustFromWalls = true;
	}

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

@ BeginLabel:
	PickDestination();

@ MoveActiveLabel:	
	if( ControllerEnemy == None )
		MoveToPoint( Destination );
	else
		MoveToPoint( Destination, , ControllerEnemy );
	GotoState( AttackingState );

@ TakeHitLabel:
	Goto( MoveActiveLabel );
} // FindAirState

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

state @ FallingState
{
	ignores NotifyBump, NotifyHitWall, ShotFiredNotification;

/* FIXME
	//-------------------------------------------------------------------------

	singular event BaseChange()
	{
		local Actor HitActor;
		local vector HitNormal, HitLocation;

		if( Pawn.Base != None && Mover(Pawn.Base) != None )
			&& ((MoveTarget == Pawn.Base) 
				|| ((MoveTarget != None) && (MoveTarget == Mover(Pawn.Base).myMarker))) )
		{
			MoveTimer = -1.0;
			MoveTarget = None;
			StopMovement( true, false );
		}
		else
			Super.BaseChange();
	}
*/

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

	event bool NotifyPhysicsVolumeChange( PhysicsVolume NewVolume )
	{
		Global.NotifyPhysicsVolumeChange(NewVolume);
		if ( NewVolume.bWaterVolume )
			GotoLabel( SplashLabel );
		return false;
	}
	
	//-------------------------------------------------------------------------
	//choose a jump velocity

	function AdjustJump()
	{
		// mdf-tbr:
		local float velZ;
		local vector FullVel;
		local float JumpDownSlope;

		#debug DMAIM( "AdjustJump MoveTarget= " $ MoveTarget $ " Destination= " $ Destination );

		if( Pawn.bCanFly )
		{
			Pawn.SetPhysics( PHYS_Flying );
		}			
		else if( Pawn.bBlockAdjustJump ) // this is set in the engine and is more or less equivalent to the check done below
		{
			//DM( "no jump -- velocity: " $ Pawn.Velocity );
			Pawn.bBlockAdjustJump = false;
		}
		else
		{
			StopMovement( true, false );
			//DM( "velocity prior to calling EAdjustJump: " $ Pawn.Velocity );
			Pawn.Velocity = EAdjustJump( Destination, Pawn.Velocity.Z, Pawn.GroundSpeed );
			//DM( "velocity after calling EAdjustJump: " $ Pawn.Velocity );
		}

		// play jumping sounds etc.
		Pawn.HandleJumpSound();

		/*
    	mdf-tbd: approach changed in UW & its pbly best to go that way now
		this means figuring out how to incorporate my slope checks into 
		the engine code that sets bBlockAdjustJump. Steve seems to have 
		replaced much of the falling state approach for this and instead
		puts the above code directly into SetFall.

		#debug DMAIM( "AdjustJump MoveTarget= " $ MoveTarget $ " Destination= " $ Destination );

		// mdf -- this is useless now one way or another
		// mdf-tbd: fix for NPCs jumping down to location that can be reached with air control
		// this isn't perfect -- if slope test fails, NPCs can still get stuck in some cases
		// -- ideally we'd be able to detect them getting stuck and/or determine that the
		// jump won't help in order to disable the jump
		#debug DMAIM( "AdjustJump jump delta Z is " $ Pawn.Location.Z - Destination.Z );

		if( Pawn.Location.Z > Destination.Z )
		{
			JumpDownSlope = (Pawn.Location.Z - Destination.Z) / VSize2D(Pawn.Location - Destination);
			#debug DMAIM( "AdjustJump jump down slope is " $ JumpDownSlope );
		}

		// mdf-tbd: this and/or code in EAdjustJump is borked for jumping down
		// I suppose that in some cases NPCs can try to jump down towards their destination
		// but if NPC is flagged as !bCanJumpDown (tbd) or if selected jump will cause
		// NPC to land above destination, just have NPC walk off the ledge
		velZ = Pawn.Velocity.Z;
		FullVel = Normal( Pawn.Velocity ) * Pawn.GroundSpeed;
		StopMovement( true, false );

		if( (Pawn.Location.Z > Destination.Z + Pawn.CollisionHeight + 2*Pawn.MaxStepHeight) || JumpDownSlope > 1.0 )
		{
			Pawn.Velocity = FullVel;
			Pawn.Velocity.Z = velZ;
			Pawn.Velocity = EAdjustJump( Destination, Pawn.Velocity.Z, Pawn.GroundSpeed );
    		Pawn.Velocity.Z = 0;
			if( VSize( Pawn.Velocity ) < 0.9*Pawn.GroundSpeed || JumpDownSlope > 1.0 )
			{
				#debug DMAIM( "Not jumping" );
				Pawn.Velocity.Z = velZ;
				return;
			}
		}

		if( Pawn.bCanFly )
		{
			Pawn.SetPhysics( PHYS_Flying );
		}			
		else if( Pawn.bBlockAdjustJump ) // this is set in the engine and is more or less equivalent to the check done below
		{
			Pawn.bBlockAdjustJump = false;
		}
		else
		{
			#debug DMAIM( "Jumping" );
	
			Pawn.Velocity = FullVel;
			Pawn.Velocity.Z = Pawn.default.JumpZ + velZ;
			DM( "Velocity prior to calling EAdjustJump: " $ Pawn.Velocity );
			Pawn.Velocity = EAdjustJump( Destination, Pawn.Velocity.Z, Pawn.GroundSpeed );
			DM( "Velocity after calling EAdjustJump: " $ Pawn.Velocity );
			Pawn.HandleJumpSound();
		}
		*/
	}

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

	function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
	{
		Global.DamageAttitudeTo( Other, Damage, DamageType );

		if( ControllerEnemy != None )
		{
			NextState = AttackingState; 
			NextLabel = BeginLabel;
		}
		if( ControllerEnemy != None && Other == ControllerEnemy )
		{
			EnemyDetected( ControllerEnemy.Location );
		}
		if( NextState == TakeHitState )
		{
			NextState = AttackingState; 
			NextLabel = BeginLabel;
			GotoState( TakeHitState ); 
		}
	}

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

	function bool MaybeSetEnemy( Pawn NewEnemy, optional bool bAlertingOthers )
	{
		local bool bResult;
		bResult = false;
		if( Global.MaybeSetEnemy( NewEnemy, bAlertingOthers ) )
		{
			bResult = true;
			NextState = AttackingState; 
			NextLabel = BeginLabel;
		}
		return bResult;
	} 

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

	function SharedTimerEvent()
	{
		if( ControllerEnemy != None )
		{
			bReadyToAttack = true;
			if( CanFire( false ) )
				GotoLabel( FireWhileFallingLabel );
		}
	}

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

	event bool NotifyLanded( vector HitNormal )
	{
		local vector Vel2D;

		if( MoveTarget != None )
		{
			Vel2D = Pawn.Velocity;
			Vel2D.Z = 0;
			if( ( Vel2D dot ( MoveTarget.Location - Pawn.Location ) ) < 0 )
				StopMovement( true, false );
		}
		//Note - physics changes type to PHYS_Walking by default for landed pawns
		//Pawn.TakeFallingDamage();
		if ( Pawn != None )
		{
			/*if( LPawn.IsHardLanding( Pawn.Velocity.Z ) )
			{
				GS( LandedHardState );
			}
			else*/ if (Pawn.Velocity.Z < -1.4 * Pawn.JumpZ)
			{
				if ( Pawn.Health > 0 )
					GotoLabel( LandedLabel );
			}
			else 
				GotoLabel( DoneLabel );
		}

		// mdf-tbd: return false so Pawn.Landed() called (handles landed sounds, damage, hard landings etc.)
		return false;
	}
	
	//-------------------------------------------------------------------------

	function eventSeeEnemy( Pawn Seen )
	{
		Global.eventSeeEnemy( Seen );
		#debug DMAI( "DisableSenses(false) in FallingState.eventSeeEnemy" );
		DisableSenses( false );
	}

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

	function eventEnemyNotVisible()
	{
		#debug DMAI( "EnableSenses(false) in FallingState.eventSeeEnemy" );
		EnableSenses( false );
	}

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

	function SetFall()
	{
		if( !Pawn.bUpAndOut )
			GotoState( FallingState );
	}
	
	//-------------------------------------------------------------------------

	function EnemyAcquired()
	{
		NextState = AcquisitionState;
		NextLabel = BeginLabel;
	}

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

	function FindNewJumpDest()
	{
		local NavigationPoint N, Best;
		local float BestRating, Rating;
		local vector Dist;

		// look for pathnode below current location and visible
		BestRating = 1;
		for ( N=Level.NavigationPointList; N!=None; N=N.NextNavigationPoint )
			if( N.Location.Z + 100 < Pawn.Location.Z )
			{
				Dist = Pawn.Location - N.Location;
				Rating = Dist.Z * Dist.Z/( Dist.X * Dist.X + Dist.Y * Dist.Y ); 
				if( ( Rating > BestRating ) && Pawn.FastTrace( N.Location, Pawn.Location ) )
				{
					BestRating = Rating;
					Best = N;
				}
			}
				

		if( Best != None )
			Destination = Best.Location;
	}

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

	event BeginState()
	{
		if( ControllerEnemy == None )
			Disable( 'EnemyNotVisible' );
		else
		{
			#debug DMAI( "DisableSenses(falses) in FallingState.BeginState #2" );
			DisableSenses( false );
		}
		if( (bFire + bAltFire > 0) || GetSkill() == 1.0 )
			SetSharedTimer( 0.01, false );
	}

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

	event EndState()
	{
		//log( Self$" left falling state " );
		if( Pawn == None )
			return;
		Pawn.bUpAndOut = false;
		bSpecialJump = false;
		bBigJump = false;
		if( ( MoveTarget != None ) && ( MoveTarget.Location.Z - Pawn.Location.Z > 256 ) )
			MoveTarget = None;
	}

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

@ FireWhileFallingLabel:
	#debug DMAI( "DisableSenses(false) in FallingState #3" );
	DisableSenses( false );
	if( Pawn.Physics != PHYS_Falling )
		Goto( DoneLabel );
	if( ControllerEnemy == None )
		Goto( FallLongLabel );
	Focus = ControllerEnemy;
	FinishRotation( DefaultRotationThreshold );
	if( CanFire( false ) )
		FireAt( ControllerEnemy );
	if ( Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z )
	{
		if ( (Pawn.Velocity.Z < 0) && (Destination.Z > Pawn.Location.Z + Pawn.MaxStepHeight + Pawn.CollisionHeight) )
			FindNewJumpDest();			
		MoveToPoint( Destination, , ControllerEnemy );
	}
	else
		Sleep( 0.5 + 0.2 * FRand() );
	if( LineOfSightTo( ControllerEnemy ) )
		Goto( FireWhileFallingLabel );
 			
@ FallLongLabel:
	if ( (Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z)
		&& (Pawn.Velocity.Z < 0) && (Destination.Z > Pawn.Location.Z + Pawn.MaxStepHeight + Pawn.CollisionHeight) )
	{
		FindNewJumpDest();
		MoveToPoint( Destination );
	}			
	if( Pawn.bCanFly )
	{
		Pawn.SetPhysics( PHYS_Flying );
		Goto( DoneLabel );
	}
	Sleep( 0.7 );
	if( ControllerEnemy != None )
	{
		Focus = ControllerEnemy;
		FinishRotation( DefaultRotationThreshold );
		if( CanFire( false ) )
			DoRangedAttack();
	}

	if ( (Pawn.Velocity.Z > -150) && (Pawn.PhysicsVolume.Gravity.Z <= Pawn.PhysicsVolume.default.Gravity.Z) ) //stuck
	{
		Pawn.SetPhysics( PHYS_Falling );
		if( ControllerEnemy != None )
			Pawn.Velocity = Pawn.groundspeed * normal( ControllerEnemy.Location - Pawn.Location );
		else
			Pawn.Velocity = Pawn.groundspeed * VRand();

		Pawn.Velocity.Z = FMax( Pawn.JumpZ, 250 );
	}
	Goto( FallLongLabel );

@ LandedLabel:
@ DoneLabel:
@ SplashLabel:
	//log( "After fall"@NextState@NextLabel );
	Pawn.bUpAndOut = false;
	if( NextState != NoState && NextState != FallingState )
		GotoState( NextState, NextLabel );
	else 
		GotoState( AttackingState );

@ BeginLabel:
	#debug DMAIL( BeginLabel );

	if( ControllerEnemy == None )
		Disable( 'EnemyNotVisible' );
	else
	{
		#debug DMAI( "DisableSenses(false) in FallingState #4" );
		DisableSenses( false );
	}
	if( !Pawn.bUpAndOut ) // not water jump
	{	
		if( Pawn.PhysicsVolume.bWaterVolume )
		{
			Pawn.SetPhysics( PHYS_Swimming );
			GotoState( NextState, NextLabel );
		}	
		if( !bSpecialJump )
		{
			AdjustJump();
			#debug DMAIM( "Physics after AdjustJump: " $ class'Util'.static.GetPhysicsString( Pawn ) );
		}
 		if( ( Pawn.Velocity.Z > 300 ) && ( MoveTarget != None )
 			&& ((FRand() < 0.13) || ((Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z) && (FRand() < 0.2)))
 			&& ( VSize( Destination - Pawn.Location ) > 160 )
 			&& ( ( vector( Pawn.Rotation ) dot ( Destination - Pawn.Location ) ) > 0 ) )
		{
 			U2PBase.PlayDodge( DCLICK_Forward );
		}
	}
	if( Pawn.Physics != PHYS_Falling )
		Goto( DoneLabel );

	if ( (GetSkill() >= 0.5) && (ControllerEnemy != None) && (Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z) )
	{
		Pawn.Acceleration = Pawn.AccelRate * Normal( Destination - Pawn.Location );
		Goto( FireWhileFallingLabel );
	}

	if( bSpecialJump )
	{
		if( bBigJump )
		{
			while( bBigJump )
			{
				Sleep( 0.25 );
				Pawn.Acceleration = Pawn.AccelRate * Normal( Destination - Pawn.Location );
			}
		}
		else
		{
			Sleep( 0.2 );
			while ( ( Abs( Pawn.Velocity.X ) < 60 ) && ( Abs( Pawn.Velocity.Y ) < 60 ) )
				Sleep( 0.1 );
			StopMovement( true, false );
			Sleep( 1.5 );
		}
		bBigJump = false;
		bSpecialJump = false;
	}
	else
		Sleep( 2 );

	Goto( FallLongLabel );

@ DuckingLabel:
	if( Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z )
	{
		Pawn.Acceleration = Pawn.AccelRate * Normal( Destination - Pawn.Location );
		if( GetSkill() < 0.5 )
			Sleep( 0.4 );
		if( ControllerEnemy != None )
			Goto( FireWhileFallingLabel );
	}
} // FallingState

//-----------------------------------------------------------------------------
// Can't move, can't shoot, can't rotate, not moved by damage.

state @ FrozenState
{
	//-------------------------------------------------------------------------

	function bool IsFrozen()			{ return true; }
	function bool IsMobile()			{ return false; }
	function bool CanFire( bool bTest )	{ return false; }

	//-------------------------------------------------------------------------
	// Allow enemy to be acquired but nothing else?

	function eventBumpEnemy( Pawn Other )
	{
		MaybeSetEnemy( Other );
	}

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

	function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
	{
		if( ValidEnemy( Other )	)
			MaybeSetEnemy( Other );

		//NextState = FrozenState; 
		//NextLabel = BeginLabel;

		//GS( TakeHitState ); 
	}

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

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

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

	function eventTakeDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		Global.eventTakeDamage( Damage, Instigator, HitLocation, vect(0,0,0), DamageType );
	}

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

	event BeginState()
	{
		Focus = None;
	}

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

@ BeginLabel:
	WaitForLanding();
	StopMovement( true, true );
	Stop;
}

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

state @ GameEndedState
{
	//-------------------------------------------------------------------------
	// 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 );
}

//-----------------------------------------------------------------------------
// 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 )
	{
		Destination = Pawn.Location + 120 * Normal( Pawn.Location - aSpot.Location ); 
		GotoState( WanderingState, MoveActiveLabel );
	}
	
	//-------------------------------------------------------------------------

	function PickDestination()
	{
		//local vector DestinationDelta;

		if( HoldSpot(OrdersObject) == None )
		{
			#debug DMAI( "PickDestination -- OrdersObject isn't a HoldSpot -- might go freelancing???" );
			#debug DMAI( "SetOrders " $ GetContext() );
			SetOrders( OrdersNone );
			GotoState( DefaultState );
		} 
		else if( AtDestinationActor( OrdersObject ) )
		{
			#debug DMAI( "PickDestination -- close to OrdersObject go to HoldingState" );
			SendMessageInPosition( 45.0 );

			if( !bInitLifeMessage )
				bInitLifeMessage = true;
			GotoState( HoldingState, WavingLabel );
		}
		else
		{
			#debug DMAI( "PickDestination -- finding a path to OrdersObject" );
			FindPathToActor( OrdersObject, MoveTarget );
			if( MoveTarget == None ) 
			{
				#debug DMAI( "SetOrders " $ GetContext() );
				SetOrders( OrdersNone );
				GotoState( DefaultState );
			} 
		}
	}

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

@ 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
{
	//-------------------------------------------------------------------------

	function SharedTimerEvent()
	{
		Enable( Event_NotifyBump );
	}
	
	//-------------------------------------------------------------------------

	function EnemyAcquired()
	{
		#debug DMAIA( "EnemyAcquired!" );
		GotoState( AcquisitionState, PlayOutLabel );
	}
	
	//-------------------------------------------------------------------------

	event bool NotifyLanded( vector HitNormal )
	{
		SetPhysics( PHYS_None );
		return true;
	}

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

	event BeginState()
	{
		#debug   SetControllerEnemy( None, GetContext() );
		#release SetControllerEnemy( None );
		StopMovement( true, false );
		RestoreAlertness();
	}

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

	event EndState()
	{
		if( HoldSpot(OrdersObject) != None )
			HoldSpot(OrdersObject).Holder = None;
	}

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

@ BeginLabel:
	//if( HoldSpot(OrdersObject) == None )
	if( OrdersObject == None )
	{
		#debug DMAI( "give up hold" );
		#debug DMAI( "SetOrders " $ GetContext() );
		SetOrders( OrdersNone );
		GotoState( DefaultState );
	} 
	else if( HoldSpot(OrdersObject) != None )
	{
		HoldSpot(OrdersObject).Holder = Pawn;
	}

@ WavingLabel:
	#debug DMAIL( WavingLabel );
	bReadyToAttack = false;

	// mdf-tbd:
	if( bStationary && LPawn.GetStance() != StationaryStance )
	{
		#debug DMAIM( "Setting stance to:" $ StationaryStance );
		LPawn.SetStance( StationaryStance );
	}

	//if( Orders == OrdersHold )
	//{
		// 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?
		Focus = None;
		MoveTarget = None;
		FocalPoint = OrdersObject.Location + 1000 * vector(OrdersObject.Rotation);
		//AddArrow( Pawn.Location, FocalPoint, ColorMagenta() );
		Sleep( 2.5 );
	//}

	if( IsMobile() )	
		GotoState( DefaultState );

	#debug DMAI( "Stop!" );
	Stop;	
} // HoldingState

//-----------------------------------------------------------------------------
// Used when NPC lands "hard". When this occurs a landed animation is played
// (rather than tweening to a landed frame) and the NPC can't move briefly.

state @ LandedHardState
{
	ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, EnemyNotVisible, BeginFalling, NotifyLanded, HearNoise, NotifyBump, NotifyHitWall, ShotFiredNotification, Trigger, NotifyHeadVolumeChange, NotifyPhysicsVolumeChange;

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

	function LandedHardDone()
	{
		if( NextState != NoState && NextState != FallingState )
		{
			GotoState( NextState, NextLabel );
		}
		else
		{
			#debug   WhatToDoNext( GetContext() );
			#release WhatToDoNext();
		}
	}

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

	event BeginState()
	{
		Super.BeginState();

		// keep NPC from moving or changing rotation until hard landing ends
		// mdf-tbd: disable aiming?
		StopMovement( true, true );
		SetRotation( Pawn.Rotation );
		FocalPoint = Pawn.Location + 512*vector(Pawn.Rotation);
		Focus = None;
	}
} // LandedHardState

//-----------------------------------------------------------------------------
// Move to a specific destination in the level, e.g. to pick up inventory or to
// carry out orders. NPC will not be in this state if there is an enemy.

// mdf-tbd: there's a strong case to be made for moving this into the Advanced
// Controller as almost all of the behavior in here implies advanced 
// intelligence.

state @ RoamingState
{
	ignores EnemyNotVisible;

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

	/*!!mdf-tbd: -- maybe just wait for new code -- ideally should use wandering to move away from friendly pawn
	function eventBumpFriend( Pawn Other )
	{
		GS( GetStateName(), 'SleepABit' );
	}
	*/

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

	function SetRoamTarget( Actor NewRoamTarget )
	{
		RoamTarget = NewRoamTarget;
	}

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

	function FearThisSpot( Actor aSpot )
	{
		Destination = Pawn.Location + 120 * Normal( Pawn.Location - aSpot.Location ); 
		GotoState( WanderingState, MoveActiveLabel );
	}

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

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

		#debug DMAI( "SetOrders " $ GetContext() );
		bResult = Global.SetOrders( NewOrders, NewOrdersObject, NewOrdersThreshold, NewOrderGiver, bAcknowledge );
		if( bCamping && (Orders == OrdersHold || Orders == OrdersFollow) )
			GotoLabel( PreBeginLabel );
		return bResult;
	}

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

	event MayFall()
	{
		Pawn.bCanJump = TestCanJump();
	}
	
	//-------------------------------------------------------------------------
	// Return true to indicate special attraction destination set.

	function bool PickSpecialDestination()
	{
		return false;
	}

	//-------------------------------------------------------------------------
	// Return true to indicate that orders related destination set.

	function bool PickOrdersDestination()
	{
		local bool bTriedToPickFar;		// flag whether we tried for far (600 unit?) local inventory so we don't do it a 2nd time later
		local bool bNearPoint;
		local Pawn Leader;
		local bool bReadyForOrders;

		#debug DMAIM( "PickOrdersDestination #1  Orders: " $ Orders );

		//DMTNS( "PickOrdersDestination #1  Orders: " $ Orders );
		bReadyForOrders = ReadyForOrders();

		if( bStationary )
		{
			#debug DMAIM( "PickOrdersDestination -- NPC is stationary -- going to HoldState" );
			GotoState( HoldState );
			return true;
		}

		if( Orders == OrdersFollow )
		{
			#debug DMAIM( "PickOrdersDestination #2 -- OrdersFollow" );
			if( Controller(OrdersObject) == None )
			{
				#debug DMAI( "SetOrders " $ GetContext() );
				SetOrders( OrdersNone );
			}
			else
			{
				Leader = Controller(OrdersObject).Pawn;
				if( Leader != None )
				{
					bNearPoint = IsCloseToDynamicGoal( Leader );
					if( !bNearPoint )
					{
						if( !bReadyForOrders )
						{
							// not ready -- pick inventory if possible
							bTriedToPickFar = true;
							//!!mdf advanced+ only
							if( PickLocalInventoryDestination( 600, 0.0 ) )
								return true;

							if( PlayerController(OrdersObject) != None )
							{
								if( FindBestInventoryPath( MoveTarget, 0.0, (GetSkill() >= 0.75) ) > 0.0 )
									return true;
							}
						}

						FindPathToActor( Leader, MoveTarget );

						if( AtDestinationActor( MoveTarget ) )
							return true;

						if( VSize( Leader.Location - Pawn.Location ) < 1600 && LineOfSightTo( Leader ) )
							bNearPoint = true;
						#debug DMAIM( " found no Path to " $ Leader );
					}
					else 
						SendMessageNearPoint( Leader, 10.0 );
				}
			}
		}

		#debug DMAIM( "PickOrdersDestination #3" );

		if( Orders == OrdersDefend && bReadyForOrders )
		{
			#debug DMAIM( "PickOrdersDestination #4 -- OrdersDefend" );

			//!!mdf advanced+ only
			if( PickLocalInventoryDestination( 300, 0.55 ) )
				return true;


			if( AmbushFindSpot() ) 
				return true;
			if( !LineOfSightTo( OrdersObject ) )
			{
				FindPathToActor( OrdersObject, MoveTarget );
				if( MoveTarget != None )
					return true;
			}
			else
				SendMessageInPosition( 10.0 );
		}

		#debug DMAIM( "PickOrdersDestination #5" );

		if( Orders == OrdersHold && bReadyForOrders && !LineOfSightTo( OrdersObject ) )
		{
			#debug DMAIM( "PickOrdersDestination #6" );
			#debug DMAI( "No LOS to OrdersObject -- going to HoldState" );
			GotoState( HoldState );
			return true;
		}

		#debug DMAIM( "PickOrdersDestination #7" );
		//!!mdf advanced+ only
		if( !bTriedToPickFar && PickLocalInventoryDestination( 600, 0.0 ) )
			return true;

		#debug DMAIM( "PickOrdersDestination #8" );
		if( Orders == OrdersHold && bReadyForOrders )
		{
			#debug DMAIM( "PickOrdersDestination #9" );
			if( VSize( Pawn.Location - OrdersObject.Location ) < 20 )
			{
				#debug DMAI( "going to HoldingState" );
				GotoState( HoldingState );
			}
			else
				GotoState( HoldState );
			return true;
		}

		#debug DMAIM( "PickOrdersDestination #10" );
		if( (Orders == OrdersFollow && bNearPoint) || 
			(Orders == OrdersDefend && bReadyForOrders && LineOfSightTo( OrdersObject )) )
		{
			#debug DMAIM( "PickOrdersDestination #11" );
			if( FRand() < 0.35 )
				GotoState( WanderingState );
			else
			{
				CampTime = 0.8;
				GotoLabel( CampLabel );
			}
			return true;
		}

		#debug DMAIM( "PickOrdersDestination #12 -- return false" );
		return false;
	}

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

	function bool HandleDecorationStuff()
	{
		local Decoration TargetDecoration;

		// if none found, check for decorations with inventory
		if( !bNoShootDecor )
		{
			//!!mdf-tbd: VCA seems to be really slow -- should it be avoided/fixed?
			foreach VisibleCollidingActors( class'Decoration', TargetDecoration, 500, Pawn.Location, true )
			{
				if( TargetDecoration.Contents != None )
				{
					bNoShootDecor = true;
					#debug   SetControllerTarget( TargetDecoration, GetContext() );
					#release SetControllerTarget( TargetDecoration );
					GotoLabel( ShootDecorationLabel );
					return true;
				}
			}
		}

		return false;
	}

	//-------------------------------------------------------------------------
	// Decide whether to hunt player. This isn't the same as going into the 
	// hunting state -- this function is used in the Roaming state to send the
	// NPC to the location of one of the players in the level and only really
	// applies to freelancing bots in dm. The hunting state on the other hand
	// is used to try to locate a current enemy which is no longer visible.

	function bool PickHuntDestination()
	{
		return false;
	}

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

	function bool PickFarInventoryDestination()
	{
		return false;
	}

	//-------------------------------------------------------------------------
	// mdf-tbd: this was a complete mess -- its a bit better now but still 
	// needs work.

	function PickDestination()
	{
		#debug DMAIM( "PickDestination #1 Orders: " $ Orders $ " Pawn Physics: " $ EnumStr( enum'EPhysics', Pawn.Physics ) );
		if( Pawn == None )
			return;

		// check for a special destination
		if( PickSpecialDestination() )
			return;

		#debug DMAIM( "PickDestination #2" );
		// check for destination due to orders
		if( PickOrdersDestination() )
			return;

		if( OrdersObject != None && AmbushPoint(OrdersObject) == None )
			bWantsToCamp = false;
		else if( Pawn.Weapon != None && Pawn.Weapon.AIRating > 0.5 && Pawn.Health > 90 && !Pawn.PhysicsVolume.bWaterVolume )
		{
			bWantsToCamp = (bWantsToCamp || (FRand() < U2PBasic.CampingRate * FMin( 1.0, Level.TimeSeconds - LastCampCheck )));
			LastCampCheck = Level.TimeSeconds;
		}
		else 
			bWantsToCamp = false;

		if( bWantsToCamp && AmbushFindSpot() )
			return;

		#debug DMAIM( "PickDestination #3" );

		// shoot decoration to get stuff?
		if( HandleDecorationStuff() )
			return;

		if( PickFarInventoryDestination() )
			return;

		// nothing around - maybe just wait a little
		if( ( FRand() < 0.35 ) && ( GetSkill() < 0.5 ) 
			&& ( Level.Game.NumPlayers + Level.Game.NumBots > 2 )  )
		{
			CampTime = 3.5 + FRand() - 8*GetSkill();
			GotoLabel( CampLabel );
		}

		// if roamed to ambush point, stay there maybe
		if( (AmbushPoint( RoamTarget ) != None) && 
			(VSize( Pawn.Location - RoamTarget.Location ) < 2*Pawn.CollisionRadius) && 
			(FRand() < 0.4) )
		{
			CampTime = 4.0;
			GotoLabel( CampLongLabel );
			return;
		}

		// maybe pick a player to hunt?
		if( PickHuntDestination() )
			return;
    	
		// look for ambush spot if didn't already try
		if( !bWantsToCamp && AmbushFindSpot() )
		{
			RoamTarget = AmbushSpot;
			return;
		}
		
		#debug DMAIM( "PickDestination #5 RoamTarget=" $ RoamTarget );

		// find a roamtarget
		if( RoamTarget == None )
			RoamTarget = SelectInventorySpotDestination();
			
		if( RoamTarget != None  )
		{
			// roam around
			if( RoamTarget != None )
			{
				#debug DMAIM( "PickDestination #7 -- calling FindPathToActor " $ RoamTarget );
				FindPathToActor( RoamTarget, MoveTarget );
				#debug DMAIM( "PickDestination #7 -- done Path= " $ MoveTarget );
				if( MoveTarget != None )
				{
					return;
				}
				else
				{
					//DMTNS( "Can't build path from current location to " $ RoamTarget );
					//AddActor( Pawn, ColorCyan() );
					//AddArrow( Pawn.Location, RoamTarget.Location, ColorWhite() );
					//AddActorAt( Pawn, RoamTarget.Location, ColorRed() );
					RoamTarget = None;
				}
			}
		}
													
		// wander or camp
		if( FRand() < 0.35 )
		{
			#debug DMAIM( "PickDestination #8" );
			GotoState( WanderingState );
		}
		else
		{
			CampTime = 3.5 + FRand() - 4 * GetSkill();
			GotoLabel( CampLabel );
		}

		#debug DMAIM( "PickDestination End: " $ MoveTarget );
	}

	//-------------------------------------------------------------------------
	/* mdf-tbd - use a timer (was going of of end of animation)
	 
	function SomeTimer() 
	{
 		if( bCamping )
 			SetPeripheralVision();
	}
	*/

	//-------------------------------------------------------------------------
	
	function bool ShouldRecamp()
	{
		return false;
	}

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

	function ModifyMoveTarget();
						 
	//-------------------------------------------------------------------------

	event BeginState()
	{
		#debug DMAIM( "BeginState" );
		bCamping = false;
	}

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

	event EndState()
	{
		#debug   SetControllerTarget( None, GetContext() );
		#release SetControllerTarget( None );
		SetPeripheralVision();
		if( !bSniping && ( AmbushSpot != None ) )
		{
			AmbushSpot.Taken = false;
			AmbushSpot = None;
		}
		bCamping = false;
	}

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

@ CampLongLabel:
	bCamping = true;
	StopMovement( true, false );
	Focus = None;
	FocalPoint = Pawn.Location + Ambushspot.LookDir;
	Sleep( CampTime );
	Goto( PreBeginLabel );

@ GiveWayLabel:
	//log( "sharing" );	
	bCamping = true;
	StopMovement( true, false );
	if( ViewObstructed( 200 ) )
		FinishRotation( DefaultRotationThreshold );
	Sleep( CampTime );
	Goto( PreBeginLabel );

@ CampLabel:
	#debug DMAIL( CampLabel );
	bCamping = true;
	StopMovement( true, false );

@ CampAgainLabel:
	if( ViewObstructed( 200 ) )
		FinishRotation( DefaultRotationThreshold );
	#debug DMAI( "Sleeping for CampTime=" $ CampTime );
	Sleep( CampTime );
	#debug DMAI( "Done sleeping" );

	if( bLeading || bCampOnlyOnce )
	{
		#debug DMAI( "goto PreBegin" );
		bCampOnlyOnce = false;
		Goto( PreBeginLabel );
	}
	#debug DMAI( "checking recamp" );
	if( ShouldReCamp() )
	{
		#debug DMAI( "camp again" );
		Goto( CampAgainLabel );
	}
	#debug DMAI( "done checking recamp" );

@ PreBeginLabel:
	SetPeripheralVision();
	bCamping = false;

@ BeginLabel:
@ MovePickDestLabel:
	WaitForLanding();
	OldMoveTarget = MoveTarget; // hack because refactoring PickDestination would be painful
	PickDestination();
	ModifyMoveTarget();
	if( MoveTarget != OldMoveTarget )
		NumMoveAttempts = 0;

@ MoveSpecialLabel:
@ MoveActiveLabel:
	#debug DMAIM( "MoveTarget: " $ MoveTarget );

	if( MoveTarget == None )
	{
		#debug DMAIM( "MoveTarget is None" );
		StopMovement( true, false );
		Sleep( 0.0 );
		Goto( MovePickDestLabel );
	}

	bCamping = false;
	#debug DMAIM( "Calling MoveToActor  MoveTarget: " $ MoveTarget $ "  NumMoveAttempts: " $ NumMoveAttempts );
	MoveToActor( MoveTarget, TMT_None );
	NumMoveAttempts++;
	#debug DMAIM( "Called MoveToActor  MoveTarget: " $ MoveTarget $ "  MoveResult: " $ EnumStr( enum'EMoveResult', MoveResult ) );
	
	//!!mdf-tbd: hack fix for bots getting stuck against obstacles in some cases
	//see task list / email -- I don't know why this is happening at this point.
	if( MoveResult != MR_DestinationReached && NumMoveAttempts > MaxMoveToActorAttemptsRoaming )
	{
		NumMoveAttempts = 0;
		GotoState( WanderingState );
	}
		
	Goto( MovePickDestLabel );

@ ShootDecorationLabel:
	Focus = ControllerTarget;
	FinishRotation( DefaultRotationThreshold );
	if( ControllerTarget != None )
	{
		FireAt( ControllerTarget );
		bAltFire = 0;
		bFire = 0;
		#debug   SetControllerTarget( None, GetContext() );
		#release SetControllerTarget( None );
	}
	Goto( MovePickDestLabel );

	/*!!mdf-tbd: -- maybe just wait for new code -- ideally should use wandering to move away from friendly pawn
SleepABit:
	StopMovement( true, true );
	Sleep( 2.0 );
	Goto( MovePickDestLabel );
*/
} // RoamingState

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

state @ ScriptedState extends @ MoveToGoalBaseState
{
	event final AnimEnd( int Channel ) 
		{ ScriptController.eventSCAnimEnd( Self, Channel ); }

	event final FinishedRotation()
		{ ScriptController.eventSCFinishedRotation( Self ); }
	
	//-------------------------------------------------------------------------

	function bool AllowFriendlyBumpStateChanges()
	{
		return false;
	}

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

	function EnableProbeEvent( name EventName, bool bVal )
	{
		if( bVal )
			Enable( EventName );
		else
			Disable( EventName );
	}

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

	event bool NotifyLanded( vector HitNormal )
	{
		ScriptedLanding();
		return false;
	}

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

	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 StateTransition( name DestinationState, optional name DestinationLabel )
	{
		// tell script we want to go autonomous -- if script eats the event, we'll stay scripted
		AutoBegin( DestinationState, DestinationLabel );
	}

	//-------------------------------------------------------------------------
	// Script is allowing us to go autonomous.

	function eventAutoBegin( name DestinationState, name DestinationLabel )
	{
		ClearScriptTarget();
    	GotoState( DestinationState, DestinationLabel );
	}

	//-------------------------------------------------------------------------
	// If bLock is true, target not cleared so NPC will periodically turn 
	// towards target.

	function TurnToActor( Actor A, optional bool bLock )
	{
		#debug DMAIA( "TurnToActor: " $ A $ " bLock: " $ bLock );
		#debug   SetControllerTarget( A, GetContext() );
		#release SetControllerTarget( A );
		bScriptLockedTarget = bLock;
		GotoLabel( TurnLabel );
	}

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

	function Actor GetTarget()
	{
		// special target takes priority when under script control
		if( ControllerTarget != None )
			return ControllerTarget;
		else
			return ControllerEnemy;
	}

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

	function bool IsRepeatFire( bool bPrimary )
	{
		return ( GetSpecifiedFireRate( bPrimary ) <= U2Weapon.MaxRapidFireRate );
	}

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

	function MaybeFire( byte bUseAltMode )
	{
		bScriptPendingFire = false;
		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: 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( "Pawn.Weapon.bMeleeWeapon: " $ Pawn.Weapon.bMeleeWeapon );
			#debug DMAIA( "Pawn.Weapon.CanFire(): " $ Pawn.Weapon.CanFire() );
			#debug DMAIA( "Pawn.Weapon.HasEnoughAmmo(1): " $ Pawn.Weapon.HasEnoughAmmo(1) );
		}
	}

	//-------------------------------------------------------------------------
	// If firing in Scripted state, must be doing so under script control so
	// let the script end it.

	// mdf-tbd: but what if weapon is telling NPC to stop firing because out
	// of ammo or reloading?
	//function StopFiring( float SuggestedFireAgainDelay, EStopFiringInfo SFInfo );

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

	function bool AdjustAim( class<Projectile> ProjectileClass, float ProjSpeed, vector ProjStart, float WeaponFireSpread, bool bLeadTarget, bool bWarnTarget, bool bTossed, bool bTrySplash )
	{
		#debug DMAIA( "AdjustAim: " $ ControllerTarget );
		if( ControllerTarget != None )
			return Global.AdjustAim( ProjectileClass, ProjSpeed, ProjStart, WeaponFireSpread, bLeadTarget, bWarnTarget, bTossed, bTrySplash );
		else		
			return true; // use current rotation
	}

	//-------------------------------------------------------------------------
	// mdf-tbd: how to handle blocking destinations like other Pawns etc.
	// If we Bump the final destination generate a "destinationreached" event?

	function eventBumpAll( Actor Other )
	{
		Super.eventBumpAll( Other );
		
		if( SpecialGoal != None && Other == SpecialGoal )
		{
			#debug DMAIM( GetStateName() $ ": eventNotifyBump bumped SpecialGoal -- jumping to ReachedDestination label: " $ Other );
			GotoLabel( ReachedDestinationLabel );
		}
	}

	//-------------------------------------------------------------------------
	
	function eventTookDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		TookDamageBase( Damage, Instigator, HitLocation, Momentum, DamageType );
	}

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

	function EnemyAcquired()
	{
		StateTransition( AcquisitionState, NoLabel );
	}

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

	function SetSpecialGoal( Actor NewSpecialGoal, optional float NewSpecialGoalDistance, optional bool bFaceSpecialGoalNew )
	{
		#debug DMAIE( "SetSpecialGoal: " $ NewSpecialGoal );
		Super.SetSpecialGoal( NewSpecialGoal, NewSpecialGoalDistance, bFaceSpecialGoalNew );
		GotoLabel( BeginLabel );
	}

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

	function HandleDestinationReached()
	{
		Super.HandleDestinationReached();
		SetSpecialGoal( None );
		DestinationReached();
	}
	
	//-------------------------------------------------------------------------

	function SetFall()
	{
		NextState = ScriptedState; 
		NextLabel = ResumePatrolLabel;
		GotoState( FallingState ); 
	}

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

	function float GetMoveSpeed( optional vector TargetLocation )
	{
		return GetScriptedMoveSpeed();
	}

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

	function UseActor( Actor A )	
	{
		class'U2UseManager'.static.UseTarget( U2PBase, A );
	}

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

	function UnuseActor( optional Actor A )
	{
		class'U2UseManager'.static.UnuseTarget( U2PBase );
	}				

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

	function NotifyUnuse( Actor A )
	{
		// trigger myself with UnuseEvent so that script controller can react to this
		Trigger( A, Pawn, UnuseEvent );
	}

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

	event BeginState()
	{
		#debug DMAI( "BeginState: " $ ScriptController );

		// hack:
		if( !bDidStartup )
		{
			DisableSenses( true );
			bDidStartup = true;
		}

		if( U2Pawn(ScriptedFocus) != None && !ValidPawn( Pawn(ScriptedFocus) ) )
			ScriptedFocus = None;

		// let script controller know to make sure EC is enabled so it starts doing its thing (only done once)
		AutoEnd();

		//mdf-ENE
		#debug   SetControllerEnemy( None, GetContext() );
		#release SetControllerEnemy( None );
	}

	//-------------------------------------------------------------------------
	
	event EndState()
	{
		// if scripted to use something -- can no longer be using it
		UnuseActor();
		EnableSenses( true );
	}

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

@ AdjustFromWallLabel:
	#debug DMAIL( AdjustFromWallLabel );
	MoveToPoint( Destination, , Focus ); 
	Destination = Focus.Location; 
	MoveToPoint( Destination, , None, GetMoveSpeed() );
	Goto( MovePickDestLabel );

@ BeginLabel:
	//DM( "BeginLabel" );
	if( !bInitializedForScripting )
		Goto( StartupDelayLabel );

	#debug DMAIL( BeginLabel );

	// See comment in SetMoveTarget. I believe this should be cleared here also.
	ClearMoveAttempts();

	if( SpecialGoal == None && Orders != OrdersFollow )
	{
  		#debug DMAIM( "No current SpecialGoal -- going idle" );
		Goto( IdleLabel );
	}

@ ResumePatrolLabel:
@ MovePickDestLabel:
	#debug DMAIL( MovePickDestLabel );
	WaitForLanding();
	
	// mdf-tbd: 01/09/23 -- handle destination being cleared at any time
	// mdf-tbd: check if the goal (or ordersobject) is falling and wait for it to land?
	if( SpecialGoal == None && Orders != OrdersFollow )
		Goto( IdleLabel );

	// figure out where to go
	#debug DMAIM( "Calling SetMoveTarget SpecialGoal=" $ SpecialGoal );

	// mdf-tbd: if previous move simply timed out could probably just reuse old destination
	GMoveType = SetMoveTarget( GetSpecialGoal(), GetSpecialGoalDistance() ); 
	if( GMoveType <= MT_None )
	{
  		#debug DMAIM( "!SetMoveTarget -- Abort" );
		Goto( ErrorLabel );
	}

	if( GMoveType == MT_Near || GMoveType == MT_Wait )
	{
  		#debug DMAIM( "SetMoveTarget -- at/near destination" );
		Goto( ReachedDestinationLabel );
	}

@ MoveActiveLabel:
	#debug DMAIM( "MoveToActor BEGIN MoveTarget=" $ MoveTarget $ " SpecialGoal=" $ SpecialGoal $ " SpecialGoalDistance=" $ SpecialGoalDistance $ " ScriptedFocus=" $ ScriptedFocus );
	#debug DMAIM( " (GroundSpeed=" $ Pawn.GroundSpeed $ " DesiredSpeed=" $ Pawn.DesiredSpeed $ " MoveSpeed=" $ GetMoveSpeed() $ ")" );
	//DM( "MoveToActor BEGIN MoveTarget=" $ MoveTarget $ " SpecialGoal=" $ SpecialGoal $ " SpecialGoalDistance=" $ SpecialGoalDistance $ " ScriptedFocus=" $ ScriptedFocus );
	//DM( " (GroundSpeed=" $ Pawn.GroundSpeed $ " DesiredSpeed=" $ Pawn.DesiredSpeed $ " MoveSpeed=" $ GetMoveSpeed() $ ")" );
	MoveToActor( MoveTarget, TMT_None, SpecialGoal, SpecialGoalDistance, ScriptedFocus, GetMoveSpeed() );
	#debug DMAIM( "MoveToActor END " $ MoveTarget $ " returned MoveResult: " $ EnumStr( enum'EMoveResult', MoveResult ) );
	//DM( "MoveToActor END " $ MoveTarget $ " returned MoveResult: " $ EnumStr( enum'EMoveResult', MoveResult ) );

	// at this point we may or may not have reached the MoveTarget
	// loop back up to try again (see if final destination now
	// directly reachable, otherwise build a Path which can possibly
	// return the NP that we were just moving to if we haven't 
	// reached it yet (but if we have reached it, then it better
	// not be used again?).

	if( MoveResult != MR_DestinationReachedFinal )
	{
		// mdf-tbd: if not a timeout -- give up immediately (blocked?)
		// after more than N tries give up
	 	if( NumMoveAttempts++ < MaxMoveToActorAttempts )
		{
			Goto( MovePickDestLabel );
	 	}
		else
	 	{
			#debug DMAIM( "Goto GiveUpLabel!" ) ;
			SpecialGoalDistance = default.SpecialGoalDistance;
			Goto( GiveUpLabel );
	 	}
	}

@ ReachedDestinationLabel:
	#debug DMAIL( ReachedDestinationLabel );

	SpecialGoalDistance = default.SpecialGoalDistance;
	if( bDirectionalPatrol && SpecialGoal.bDirectional )
	{
		#debug DMAI( "executing bDirectionalPatrol code" );

		FocalPoint = SpecialGoal.Location + 200*vector(SpecialGoal.Rotation);
		if( NeedToTurn( FocalPoint, NeedToTurnAngleCos ) )
		{	
			Focus = None;
			FinishRotation( DefaultRotationThreshold );
		}
	}
	else
	{
		if( ScriptedFocus == None )
			Focus = None; // clear NPC looking at goal?
		SetRotation( Pawn.Rotation );
		FocalPoint = Pawn.Location + 512*vector(Pawn.Rotation);
	}

	// tell script controller that we made it (mdf-tbd: is it redundent to pass back the final destination -- where else could we be?)
	HandleDestinationReached();

	#debug DMAIM( "reached destination!" );
	Goto( IdleLabel );

@ IdleLabel:
	#debug DMAI( "IdleLabel: " $ bScriptedIdleAnims );
	// NPC isn't moving -- play idle animations
	Pawn.StopMovement( true, false );				// make sure NPC not moving

@ TurnLabel:
	#debug DMAI( "TurnLabel -- ControllerTarget: " $ ControllerTarget );
	// script has given us a target to rotate towards
	if( ControllerTarget != None )
	{
		if( NeedToTurn( ControllerTarget.Location, NeedToTurnAngleCos ) )
		{	
			#debug DMAI( "Need to turn towards target: " $ ControllerTarget );
	
			// need to rotate towards it
			Focus = None;
			FocalPoint = ControllerTarget.Location;
			FinishRotation( DefaultRotationThreshold );
			#debug DMAI( "Sending FinishedRotation" );
		}

		// let script controller know rotation is complete
		FinishedRotation();
	}

	if( !bScriptLockedTarget )
	{
		#debug   SetControllerTarget( None, GetContext() );
		#release SetControllerTarget( None );
	}
	
@ 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(SpecialGoal) != None )
	{
		Sleep( 1.5 );
		Goto( BeginLabel );
	}

	Stop;

@ StartupDelayLabel:
	#debug DMAssert( !bInitializedForScripting , GetContext() );
	#debug DMAIL( "StartupDelayLabel" );
	// Wait until Pawn/Controller initialized then initialize script controller (which
	// could immediately start controlling the NPC so NPC better be ready).
	#debug DMAI( "DisableSenses" );
	DisableSenses( true );
	Sleep( 0.2 );
	bInitializedForScripting = true;
	EnableSenses( true ); // have to do before call to Initialize -- might never get to line after that
	ScriptController.InitializeScriptController( Self );
	Goto( BeginLabel );
} // ScriptedState

//-----------------------------------------------------------------------------
// NOTE: seems this has to go after the state that is being extended?

state @ ScriptedDialogState extends @ ScriptedState
{
	function eventTookDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		// take damage = conversation over
		TookDamageBase( Damage, Instigator, HitLocation, Momentum, DamageType );
	}

	//-------------------------------------------------------------------------
	
	function EnemyAcquired()
	{
		GotoState( AcquisitionState, PlayOutLabel );
	}

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

	function DialogSetFocus( Actor FocusActor )
	{
		DialogFocus = FocusActor;
		if( FocusActor != None )
			GotoLabel( DialogFocusSetLabel );
		else
			GotoLabel( DialogFocusRestoreLabel );
	}
	
	//-------------------------------------------------------------------------

	function bool IsDialogPaused() 
	{
		return bIsPaused;
	}

	//-------------------------------------------------------------------------
	
	function DialogPause()
	{
		bIsPaused = true;
		StopMovement( true, true );
		// shouldn't need to inform script (if any) next latent call will
		// complete but resumption of execution will be prevented
	}

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

	function DialogUnPause()
	{
		bIsPaused = false;
		// notify the script that we're unpausing it.
		ScriptController.eventSCDialogUnPause( Self );
	}
		
	//-------------------------------------------------------------------------

	event DialogEnd()
	{
		GotoLabel( DialogEndLabel );
	}

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

	event BeginState()
	{
		SetAlertness( 0.5 );
		OldFocus = Focus;
		OldFocalPoint = FocalPoint;
		DialogPause();
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		RestoreAlertness();
		DialogUnPause();
	}

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

@ DialogBeginLabel:
	// Turn to dialog focus
	if( DialogFocus != None )
		Goto( DialogFocusSetLabel );
	Stop;

@ DialogEndLabel:

	// Restore Focus
	DialogFocus = None;
	if( OldFocus != None )
	{
		Focus = OldFocus;
		FocalPoint = OldFocus.Location;
		if( NeedToTurn( Focus.Location, NeedToTurnAngleCos ) )
			FinishRotation( DefaultRotationThreshold );
	}

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

@ DialogFocusSetLabel:
	if( NeedToTurn( DialogFocus.Location, NeedToTurnDialogAngleCos ) )
	{
		Focus = DialogFocus;
		FocalPoint = DialogFocus.Location;
		if( U2Pawn(DialogFocus) != None )
			FocalPoint += vect(0,0,1)* U2Pawn(DialogFocus).BaseEyeHeight;
		FinishRotation( DefaultRotationThreshold );
		Focus = None;
		FocalPoint = Pawn.Location +256*vector(Pawn.Rotation);
    	Sleep( 1.0 );
    }
	else
	{
		Sleep( 1.0 );
	}
	Goto( DialogFocusSetLabel );

@ DialogFocusRestoreLabel:
	Focus = OldFocus;
	FocalPoint = OldFocus.Location;
	if( NeedToTurn( Focus.Location, NeedToTurnAngleCos ) )
		FinishRotation( DefaultRotationThreshold );
	Stop;

} // ScriptedDialogState

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

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

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

	event bool NotifyLanded( vector HitNormal )
	{
		if( Pawn.Velocity.Z < -1.4 * Pawn.JumpZ )
			Pawn.MakeNoise( -0.5 * Pawn.Velocity.Z/( FMax( Pawn.JumpZ, 150.0 ) ) );
		Pawn.bJustLanded = true;
		return true;
	}

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

	function SharedTimerEvent()
	{
		//DMTNS( "SharedTimerEvent" );
		bReadyToAttack = true;
	}

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

	event BeginState()
	{
		Pawn.LastPainAnimTime = Level.TimeSeconds;
		LastPainAnim = Pawn.AnimSequence;
		if( ( NextState == AttackTacticalMoveState ) && ( Pawn.PhysicsVolume.Gravity.Z > Pawn.PhysicsVolume.default.Gravity.Z ) )
			Destination = Pawn.Location;
	}
		
	//-------------------------------------------------------------------------

@ BeginLabel:
	if( bFireFalling )
	{
		bFireFalling = false;
		GotoState( FallingState, DuckingLabel );
	}
	if( GetSkill() < 0.75 )
		Sleep( 0.05 );
	if ( (Pawn.Physics == PHYS_Falling) && !Pawn.PhysicsVolume.bWaterVolume )
		GotoState( FallingState, DuckingLabel );
	else if( NextState != NoState )
		GotoState( NextState, NextLabel );
	else
		GotoState( AttackingState );
} // TakeHitState

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

state @ TestMoveState extends @ MoveToGoalBaseState
{
	ignores EnemyNotVisible;

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

/*
@ CampLabel:
	StopMovement( true, false );
	Stop;

@ PreBeginLabel:
	bCamping = false;
*/
	
@ BeginLabel:
@ MovePickDestLabel:
	#debug DMAIL( MovePickDestLabel );
	WaitForLanding();
	
	// figure out where to go
	#debug DMAIM( "Calling SetMoveTarget" $ TestMoveTarget );
	if( SetMoveTarget( TestMoveTarget ) <= MT_None )
	{
		#debug DMAIM( "Error calling SetMoveTarget" );
		Goto( ErrorLabel );
	}

@ MoveActiveLabel:
	#debug DMAIL( MoveActiveLabel );

	#debug DMAIM( "MoveToActor BEGIN MoveTarget=" $ MoveTarget $ " NumMoveAttempts=" $ NumMoveAttempts );
	#debug DMAIM( " (GroundSpeed=" $ Pawn.GroundSpeed $ " DesiredSpeed=" $ Pawn.DesiredSpeed );
	MoveToActor( MoveTarget, TMT_None, TestMoveTarget );
	#debug DMAIM( "MoveToActor END " $ MoveTarget $ " returned MoveResult: " $ EnumStr( enum'EMoveResult', MoveResult ) );

	if( MoveResult != MR_DestinationReachedFinal )
	{
		// after more than N tries give up
	 	if( NumMoveAttempts++ < MaxMoveToActorAttempts )
			Goto( MovePickDestLabel );
		else
	 		Goto( GiveUpLabel );
	}

@ ReachedDestinationLabel:
	#debug DMAI( ReachedDestinationLabel );

	// made it
	Focus = None; // clear NPC looking at goal?
	MoveTarget = None;
	SetRotation( Pawn.Rotation );
	FocalPoint = Pawn.Location + 512*vector(Pawn.Rotation);
	StopMovement( true, false );
	if( HasScript() )
		GotoState( ScriptedState ); // return to scripted state
	Stop;
} // TestMoveState

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

state @ UsingState
{
	//-------------------------------------------------------------------------

	function UseActor( Actor A )
	{
		// sanity check
		DMAssert( false, GetContext() );
	}				

	//-------------------------------------------------------------------------
	
	function UnuseActor( optional Actor A )
	{
		class'U2UseManager'.static.UnuseTarget( U2PBase );
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}				

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

	function NotifyUnuse( Actor A )
	{
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}

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

	event EndState()
	{
		UnuseActor();
	}
} // UsingState

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

state @ VictoryDanceState extends @ EnemyKilledState
{
	ignores EnemyNotVisible; 

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

	event EndState()
	{
		#debug   SetControllerTarget( None, GetContext() );
		#release SetControllerTarget( None );
	}

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

@ BeginLabel:
	StopMovement( true, false );
	Focus = ControllerTarget;
	FinishRotation( DefaultRotationThreshold );
	Focus = None;
	FocalPoint.Z = Pawn.Location.Z;
	U2P.AnimationController.SpecialAnimationVictoryDance();
	FinishAnim();
	#debug   WhatToDoNext( GetContext() );
	#release WhatToDoNext();
} // VictoryDanceState

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

state @ WanderingState
{
	ignores EnemyNotVisible;

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

	/*!!mdf-tbd: -- maybe just wait for new code -- ideally should use wandering to move away from friendly pawn
	function eventBumpFriend( Pawn Other )
	{
		GotoLabel( 'SleepABit' );
	}
	*/

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

	function bool DeferTo( Controller Other )
	{
		if( Pawn.Acceleration == vect(0,0,0) )
			return Global.DeferTo( Other );

		return false;
	}

/* FIXME
	//-------------------------------------------------------------------------

	singular event BaseChange()
	{
		if( ( Pawn.Base != None ) && Mover(Pawn.Base) != None )
			Destination = Pawn.Location - 300 * Normal( Pawn.Velocity );
		else
			Super.BaseChange();
	}
*/

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

	function SharedTimerEvent()
	{
		//DMTNS( "SharedTimerEvent" );
		Enable( Event_NotifyBump );
	}

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

	function SetFall()
	{
		NextState = WanderingState; 
		NextLabel = ContinueWanderLabel;
		GotoState( FallingState ); 
	}

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

	function bool TestDirection( vector Dir, out vector Pick )
	{	
		local vector HitLocation, HitNormal, Dist;
		local float MinDist;
		local Actor HitActor;

		#debug DMAIM( "TestDirection -- begin" );
		MinDist = FMin( 150.0, 4*Pawn.CollisionRadius );
		if( ( Orders == OrdersFollow ) && ( VSize( Pawn.Location - Controller( OrdersObject ).Pawn.Location ) < 500 ) )
			Pick = Dir * ( MinDist + ( 200 + 6*Pawn.CollisionRadius ) * FRand() );
		else
			Pick = Dir * ( MinDist + ( 450 + 12*Pawn.CollisionRadius ) * FRand() );

		HitActor = Pawn.Trace( HitLocation, HitNormal, Pawn.Location + Pick + 1.5 * Pawn.CollisionRadius * Dir , Pawn.Location, false );
		if( HitActor != None )
		{
			Pick = HitLocation + ( HitNormal - Dir ) * 2 * Pawn.CollisionRadius;
			if( !Pawn.FastTrace( Pick, Pawn.Location ) )
			{
				#debug DMAIM( "TestDirection -- end #1" );
				return false;
			}
		}
		else
			Pick = Pawn.Location + Pick;
		 
		Dist = Pick - Pawn.Location;
		if( Pawn.Physics == PHYS_Walking )
			Dist.Z = 0;
		
		#debug DMAIM( "TestDirection -- end #2" );
		return ( VSize( Dist ) > MinDist ); 
	}
			
	//-------------------------------------------------------------------------

	function PickDestination()
	{
		local vector Pick, PickDir;
		local bool bSuccess, bMustWander;
		local float XY;

		#debug DMAIM( "PickDestination -- begin" );

		//Favor XY alignment
		XY = FRand();
		if( WanderDirectionExternal != vect(0,0,0) )
		{
			PickDir = WanderDirectionExternal;
			XY = 1;
			bMustWander = true;
		}
		else if( XY < 0.3 )
		{
			PickDir.X = 1;
			PickDir.Y = 0;
		}
		else if( XY < 0.6 )
		{
			PickDir.X = 0;
			PickDir.Y = 1;
		}
		else
		{
			PickDir.X = 2 * FRand() - 1;
			PickDir.Y = 2 * FRand() - 1;
		}
		if( Pawn.Physics != PHYS_Walking )
		{
			PickDir.Z = 2 * FRand() - 1;
			PickDir = Normal( PickDir );
		}
		else
		{
			PickDir.Z = 0;
			if( XY >= 0.6 )
				PickDir = Normal( PickDir );
		}	

		bSuccess = TestDirection( PickDir, Pick );
		if( !bSuccess )
			bSuccess = TestDirection( -1 * PickDir, Pick );
		
		if( bSuccess )	
			Destination = Pick;
		else if( bMustWander )
		{
			WanderDirectionExternal = Normal( WanderDirectionExternal + VRand() );
			WanderDirectionExternal.Z = 0;
			Destination = Pawn.Location + 100 * WanderDirectionExternal;
		}
		else
			GotoLabel( TurnLabel );

		WanderDirectionExternal = vect(0,0,0);

		#debug DMAIM( "PickDestination -- end: " $ WanderDirectionExternal*100 );
	}

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

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

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

	event BeginState()
	{
		#debug DMAIM( "BeginState" );
		#debug   SetControllerEnemy( None, GetContext() );
		#release SetControllerEnemy( None );
		SetAlertness( 0.2 );
		bReadyToAttack = false;
		MinHitWall += 0.15;
		if( Pawn != None )
		{
			Pawn.bCanJump = false;
			Pawn.bAvoidLedges = true;
			Pawn.bStopAtLedges = true;
			Pawn.bCanWalkOffLedges = U2PBase.bCanWanderOffLedges;
		}
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		MinHitWall -= 0.15;
		RestoreAlertness();
		if( Pawn != None )
		{
			Pawn.bStopAtLedges = Pawn.default.bStopAtLedges;
			Pawn.bAvoidLedges = Pawn.default.bAvoidLedges;
			Pawn.bCanJump = (Pawn.JumpZ > 0);
			Pawn.bCanWalkOffLedges = Pawn.default.bCanWalkOffLedges;
		}
	}

@ BeginLabel:
@ MovePickDestLabel:
	#debug DMAIM( "MovePickDestLabel" );
	WaitForLanding();
	PickDestination();
	
@ MoveActiveLabel:
	#debug DMAIM( "calling MoveToPoint -- begin" );
	MoveToPoint( Destination, , None, Pawn.WalkingPct );
	#debug DMAIM( "calling MoveToPoint -- end" );

@ PausingLabel:
	if( Level.Game.bTeamGame && (bLeading || (Orders == OrdersFollow && !IsCloseToDynamicGoal( Controller(OrdersObject).Pawn ))) )
		GotoState( RoamingState );
	StopMovement( true, false );
	if( ViewObstructed( 200 ) )
	{
		#debug DMAIM( "ViewObstructed -- calling FinishRotation #1 -- begin" );
		FinishRotation( DefaultRotationThreshold );
		#debug DMAIM( "calling FinishRotation #1 -- end" );
	}
	Sleep( 1.0 );

	GotoState( RoamingState );

@ ContinueWanderLabel:
	if( FRand() < 0.2 )
		Goto( TurnLabel );
	Goto( MovePickDestLabel );

@ TurnLabel:
	StopMovement( true, false );
	Focus = None;
	FocalPoint = Pawn.Location + 20 * VRand();
	#debug DMAIM( "calling FinishRotation #2 -- begin" );
	FinishRotation( DefaultRotationThreshold );
	#debug DMAIM( "calling FinishRotation #2 -- end" );
	Goto( PausingLabel );

/*!!mdf-tbd: -- maybe just wait for new code -- ideally should use wandering to move away from friendly pawn
SleepABit:
	StopMovement( true, true );
	Sleep( 2.0 );
	Goto( MovePickDestLabel );
*/
} // WanderingState

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

defaultproperties
{
	DefaultMeleeAttackState='AttackMelee'
	MaxHuntTime=30.000000
	MaxMoveToActorAttemptsRoaming=2
	Aggressiveness=0.300000
	AttackNonRangedCheckRate=1.000000
	AttackNonRangedFailedRate=1.000000
	AttackReadyToAttackOdds=0.150000
	TimeBetweenAttacks=0.600000
	DefaultState='Roaming'
	DefaultScriptControllerClass=Class'U2AI.ScriptControllerInterf'
	ScriptedScriptControllerClass=Class'U2AI.ScriptControllerBase'
	CrouchingMoveSpeedMultiplier=1.000000
	ProneMoveSpeedMultiplier=1.000000
	StandingMoveSpeedMultiplier=1.000000
	FovAngle=85.000000
	PlayerReplicationInfoClass=None
	RemoteRole=ROLE_None
     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.916 - Created with UnCodeX