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

U2AI.U2NPCControllerBase


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
//=============================================================================
// U2NPCControllerBase.uc
// Created By: Mike Fox
// Created On: 8/01/00
// $Author: Mfox $
// $Date: 1/06/03 2:59p $
// $Revision: 183 $
//=============================================================================

class U2NPCControllerBase extends U2NPCControllerShared
	config(User);

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

This is the AI Controller class for "base" NPCs. These are generally "ambient"
NPCs which mainly just wander around and won't react to seeing/hearing enemies
etc., although they can be scripted and can engage in "dialog" (e.g. to
support "orders").

The overhead for "base" NPCs should be much lower than that for "basic" or 
"advanced" NPCs. Rendering issues aside, you should be able to have dozens,
perhaps 100+ "base" NPCs in a level without seriously degrading the framerate.

In general, if an NPC is going to be "less than ambient" it will use a "basic"
(NPC doesn't use weapons) or "advanced" (NPC uses weapons) controller so that
it can leverage the "standard" code for handling enemies and attacks etc. But,
in some cases, e.g. for NPCs with very special attacks, "base" can be used and
the input/attack handling code can be implemented in a special controller for
that NPC. 

e.g. the killer sprout and spores are "base" NPCs which have special
attacks handled through their own controllers (the killer sprout grabs enemies
which pass within reach of its tentacles and the sporers simply move towards
enemies, exploding when they bump them and the usual "basic" controller isn't
applicable in these cases.

As another example, it would also be overkill to use a basic+ AI controller to 
simply have a base NPC react to seeing the player -- support for this will
either be added to "base" or a special controller can be used to handle seeing
and reacting (e.g. fly away) to various inputs.

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

MISC NOTES:

==> 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
	+used to not use R_PLAYERONLY paths (obsolete now?)
	+have lower net priority (ok?)
	+can't be outside of the game world in some cases (ok?)

==> misc

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.

==> todo

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?

=== Thoughts ===

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

+base controller supports dialog so pretty much any NPCs (e.g. the seagoat) can
use the dialog system, e.g. for "orders".
*/

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

/* standard ignores events list (for cutting and pasting !!mdf -tbr)
	ignores EnemyNotVisible, HearNoise, NotifyBump, SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend; // sensory input
	ignores BeginFalling, NotifyLanded, NotifyHitWall, NotifyHeadVolumeChange, NotifyPhysicsVolumeChange; // physics
	ignores KilledBy, ShotFiredNotification, TakeDamage, Trigger; // other

Notes:

Hmm, ignores being used to override global functions in many cases -- I guess
this makes sense...

The following should never have to use ignores with this -- if its implemented
globabally or in some state it will be enabled for that state (I can't imagine
why we'd want to ignore it in these cases -- if we don't want the global
behavior -- its pbly clearer to override it). In some cases we might want to use 
disable/enable to turn these off/on.

	AnimEnd
	Tick
	Timer
	Trigger
*/

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

const HoldReachedDistance2D				=  16.0;
const HoldReachedDistanceSquared2D		= 256.0;
const AvoidedBumpWaitTime				=   1.0;
const AdjustAgainDelay					=   1.0;

const RandomSoundTimerName				= 'RandomSoundTimer'; // used by some NPCs for random idle/attack sounds

//-----------------------------------------------------------------------------
									
// AI flags
var bool bIsPaused;				// is the script paused? (i.e. by dialog)

// AI internal
var name LastPainAnim;
//mdf-tbe: moved to "shared" for now var	float	LastAcquireTime;
var vector WanderDirection;		// most recently selected wander direction
var float WanderMoveSpeed;		// move speed to use with next call to MoveToPoint when wandering

var name BaseAcquisitionState;	// base controllers which might acquire / attack enemies can set this as needed
var name BaseAcquisitionLabel;	// base controllers which might acquire / attack enemies can set this as needed

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

var float NextAdjustPositionTime;
var float NextScriptedMoveTime;

var bool bSavedWanderingParameters;
var float WanderMinAdjustedSizeSaved;
var bool bDistressedWanderingSaved;
var float WanderPauseOddsSaved;
var float WanderSpeedMaxSaved;
var float WanderSpeedMinSaved;
var float WanderTurnToDestinationOddsSaved;
var float WanderSpreadAngleSaved;
//!!mdf-tbd: pbly a bad idea to let panicked NPCs wander off ledges
//var bool bCanWanderOffLedgesSaved;
var float WalkingPctSaved;

var bool bWanderFixed;
var int MaxWanderAttempts;
var int MaxWanderFallbackTypes;

var vector PotentialFocalPoint;

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

var float TimeSinceBeginState;				// used with some states to track how long NPC in that state

// random idle/attack sounds
var float LastRandomSoundTime;

// probes
//var bool bProbeAnimEnd;
var bool bProbeEnemyNotVisible;
var bool bProbeHearNoise;
var bool bProbeNotifyBump;
var bool bProbeEnemyInvalid;
var bool bProbeEnemyInLeapRange;
var bool bProbeEnemyInMeleeRange;
var bool bProbeEnemyNotInMeleeRange;
var bool bProbeEnemyRangeTransition;
var bool bProbeSeeAlertFriend;
var bool bProbeSeeEnemy;
var bool bProbeSeeFriend;
var bool bProbeSeeOther;
var bool bProbeActorRangeTransition;
//var bool bProbeTick;
//var bool bProbeTimer;
//var bool bProbeTrigger;

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

// Implemented in some states if they can be re-initialized when reselecting
// the state without changing to it from a different state (no call to BeginState)

function InitializeState();

/*-----------------------------------------------------------------------------
Master "what should I do now?" function. Performs basic evaluation of the NPC's 
current situation and determines the best course of action. Can be overridden 
to add subclass-specific tests, destination states etc.

Situations where this function is typically called include at startup and when
the NPC's enemy is killed or becomes invalid.
*/

#debug   function WhatToDoNext( string ContextStr )
#release function WhatToDoNext()
{
	#debug DMAI( "U2NPCControllerBase.WTDN (" $ ContextStr $ ") ScriptController=" $ ScriptController $ " Enemy=" $ ControllerEnemy );

	UpdateEnemy();

	if( HasScript() )
	{
		if( GetStateName() != ScriptedState )
		{
			#debug DMAI( "WTDN (Base) selecting " $ ScriptedState $ " (default label)" );
			if( IsInState( ScriptedDialogState ) )
				GotoState( ScriptedState ); //GS-OK
			else
				GotoState( ScriptedState, AutoEndLabel ); //GS-OK
		}
	}
	else if( !IsInState( DefaultState ) )
	{
		#debug DMAI( "WTDN (Base) selecting " $ DefaultState $ " (default label)" );
		GotoState( DefaultState ); //GS-OK
	}

  #debug DMAI( "WTDN keeping current state" );
} // WhatToDoNext

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

function Freeze()
{
	GotoState( CantMoveState ); //GS-OK
}

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

function HandlePanic()
{
	GotoState( WanderingPanicState );
}

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

function EndPanic()
{
	#debug   WhatToDoNext( GetContext() );
	#release WhatToDoNext();
}

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

function SaveWanderingParameters()
{
	if( !bSavedWanderingParameters )
	{
		bDistressedWanderingSaved = U2PBase.bDistressedWandering;
		WanderMinAdjustedSizeSaved = U2PBase.WanderMinAdustedSize;
		WanderPauseOddsSaved = U2PBase.WanderPauseOdds;
		WanderSpeedMaxSaved = U2PBase.WanderSpeedMax;
		WanderSpeedMinSaved = U2PBase.WanderSpeedMin;
		WanderTurnToDestinationOddsSaved = U2PBase.WanderTurnToDestinationOdds;
		WanderSpreadAngleSaved = U2PBase.WanderSpreadAngle;
		//bCanWanderOffLedgesSaved = U2PBase.bCanWanderOffLedges;
		WalkingPctSaved = U2PBase.WalkingPct;
		
		bSavedWanderingParameters = true;
	}
}

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

function SetWanderingPanicParameters()
{
	U2PBase.bDistressedWandering = true;
	U2PBase.WanderMinAdustedSize = 0.0;
	U2PBase.WanderDistMax = FMin( Pawn.CollisionRadius * 3.0, 512.0 );
	U2PBase.WanderDistMin = FMin( Pawn.CollisionRadius * 1.0, 256.0 );
	U2PBase.WanderPauseOdds = 0.0;
	U2PBase.WanderSpeedMax = 1.0;
	U2PBase.WanderSpeedMin = 1.0;
	U2PBase.WanderTurnToDestinationOdds = 0.1;
	U2PBase.WanderSpreadAngle = 90.0;
	//U2PBase.bCanWanderOffLedges = true;
	U2PBase.WalkingPct = 1.0;
}

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

function RestoreWanderingParameters()
{
	U2PBase.bDistressedWandering = bDistressedWanderingSaved;
	U2PBase.WanderMinAdustedSize = WanderMinAdjustedSizeSaved;
 	U2PBase.WanderPauseOdds = WanderPauseOddsSaved;
	U2PBase.WanderSpeedMax = WanderSpeedMaxSaved;
	U2PBase.WanderSpeedMin = WanderSpeedMinSaved;
	U2PBase.WanderTurnToDestinationOdds = WanderTurnToDestinationOddsSaved;
	U2PBase.WanderSpreadAngle = WanderSpreadAngleSaved;
	//U2PBase.bCanWanderOffLedges = bCanWanderOffLedgesSaved;
	U2PBase.WalkingPct = WalkingPctSaved;
	bSavedWanderingParameters = false;
}

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

function RestoreCanStrafe()
{
	Pawn.bCanStrafe = Pawn.default.bCanStrafe;
}
	
//-----------------------------------------------------------------------------

static function float GetRecentAutoEndTime( Pawn SourcePawn )
{
	local Controller C;
	local float ReturnedTime;
	
	//Log.DMTNS( "GetSquadInfo for " $ SourcePawn );
	for( C=SourcePawn.Level.ControllerList; C!=None; C=C.NextController )
	{
		if( class'Pawn'.static.ValidPawn( C.Pawn ) && C.Pawn.SameTeam( SourcePawn ) )
			ReturnedTime = FMax( ReturnedTime, U2NPCControllerBase(C).LastAutoEndTime );
	}
	
	return ReturnedTime;
}

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

function float GetNextRandomSoundTime()
{
	local Controller C;
	local int NumBuddies;
	local float MinTime, MaxTime;

	// determine when next to play an idle sound based on number of active 
	// NPCs of the same class in the area
	for( C=Level.ControllerList; C!=None; C=C.NextController )
		if( !C.bStasis &&
			ValidPawn( C.Pawn ) && 
			C.Pawn.IsA( Pawn.Class.Name ) && 
			VSize( Pawn.Location - C.Pawn.Location ) < 4096.0 )
		{
			NumBuddies++;
		}

	MinTime = FMax( LastRandomSoundTime - Level.TimeSeconds + U2P.MinRandomSoundTime, 0.5 );
	MaxTime = U2P.MaxRandomSoundTime + 2.0*NumBuddies;
	
	//DMTNS( "NumBuddies: " $ NumBuddies );
	//DMTNS( "MinTime:     " $ MinTime );
	//DMTNS( "MaxTime:     " $ MaxTime );
	
	return RandRange( MinTime, MaxTime );
}

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

function SetRandomSoundTimer()
{
	local float NextRandomSoundTime;
	
	if( ValidPawn( Pawn ) )
	{
		NextRandomSoundTime = GetNextRandomSoundTime();
		//DMTNS( "RandomSoundTimer set to " $ NextRandomSoundTime );
		AddTimer( RandomSoundTimerName, NextRandomSoundTime, false );
	}
}

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

function PlayRandomSound()
{
	if( (Level.TimeSeconds - LastRandomSoundTime) <= U2P.MinTimeBetweenRandomSounds )
		return;
		
	if( ControllerEnemy != None )
	{
		//DMTNS( "  calling HandleRandomAttackSound" );
		U2P.HandleRandomAttackSound();
	}
	else
	{
		//DMTNS( "  calling HandleRandomIdleSound" );
		U2P.HandleRandomIdleSound();
	}
		
	LastRandomSoundTime = Level.TimeSeconds;
}

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

function HandleRandomSoundTimer()
{
	if( !ValidPawn( Pawn ) )
		return;

	//NOTE (mdf) currently idle sounds will spam leaping sounds (which we don't
	//want) since all SoundTable sounds are going through SLOT_Talk.
	if( !bStasis )
		PlayRandomSound();
		
	SetRandomSoundTimer();
}

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

function RandomSoundTimer()
{
	HandleRandomSoundTimer();
}

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

function DoPanicSounds()
{
	if( Pawn.SameTeam( U2P.PanicDamageInstigator ) )
		StartFriendlyPanicSound();
	else
		StartPanicSound();
}

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

function StartFriendlyPanicSound()
{
	local float SoundDuration;
	local sound PlayedSound;

	PlayedSound = U2PBase.AssetsHelperClass.static.HandleFriendlyPanicSound( U2PBase );
	if( PlayedSound != None )
	{
		SoundDuration = GetSoundDuration( PlayedSound );
		if( SoundDuration > 0 )
			AddTimer( 'StartPanicSound', SoundDuration );
		U2PBase.CurPanicSound = PlayedSound;	// used to stop sound when panic time is up
	}
}

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

function StartPanicSound()
{
	local float SoundDuration;
	local sound PlayedSound;

	PlayedSound = U2PBase.AssetsHelperClass.static.HandlePanicSound( U2PBase, U2PBase.PanicDamageType );
	if( PlayedSound != None )
	{
		SoundDuration = GetSoundDuration( PlayedSound );
		if( SoundDuration > 0 )
			AddTimer( 'StartPanicSound', SoundDuration + U2PBase.PanicSoundPauseSeconds );
		U2PBase.CurPanicSound = PlayedSound;	// used to stop sound when panic time is up
	}
}

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

function EndPanicSound()
{
	if( U2PBase.CurPanicSound != None )
	U2PBase.StopSound( U2PBase.CurPanicSound, 0.5 );
	U2PBase.AssetsHelperClass.static.HandlePanicSoundEnding( U2PBase, U2PBase.PanicDamageType );
}

/*-----------------------------------------------------------------------------
Sets global (non-state) probe status for various events. Note that 
enable/disable apply on a per-state basis so this will have no effect within 
any states. Does that make doing this pretty much useless?

Note:

event PrepareForMove:

	Called from execMoveToward if/when target reachspec is too small for NPC
	(and that reachspec would only be used if the path-finding code determined
	previously that the NPC is capable of using it -- i.e. can crouch etc. to
	fit within reachspec). Also called if destination navigation point has
	special move requirements (bSpecialMove)

event BreathTimer:

	Only called if BreathTime > 0.0.

function Trigger: 

	Not really an event but is a probe function.

Note: 
*/

function SetEvents()
{
	// shouldn't these all be enabled by default at this point?
	// mdf-tbd: yes, if functions are implemented, but for performance
	// reasons, we pbly don't want any of these enabled by default
	// (let subclasses enable these as needed or add flags to control
	// whether to leave these enabled here)?

	//SetProbing( Event_AnimEnd,		bProbeAnimEnd );
	SetProbing( Event_EnemyNotVisible,		bProbeEnemyNotVisible );
	SetProbing( Event_HearNoise,			bProbeHearNoise );
	SetProbing( Event_NotifyBump,			bProbeNotifyBump );
	SetProbing( Event_SeeEnemy,			bProbeSeeEnemy );
	//SetProbing( Event_SeeAlertFriend, 	bProbeSeeAlertFriend );
	//SetProbing( Event_SeeFriend, 		bProbeSeeFriend );
	//SetProbing( Event_SeeOther,			bProbeSeeOther );
	//SetProbing( Event_Tick,				bProbeTick );
	//SetProbing( Event_Timer,				bProbeTimer );
	//SetProbing( Event_Trigger,			bProbeTrigger );

}

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

function InitializeEvents()
{
	SetEvents();

#debugbegin
	//DMAssert( bProbeAnimEnd			|| !IsProbing( Event_AnimEnd ), GetContext() );
	DMAssert( bProbeEnemyNotVisible	|| !IsProbing( Event_EnemyNotVisible ), GetContext() );
	DMAssert( bProbeHearNoise			|| !IsProbing( Event_HearNoise ), GetContext() );
	DMAssert( bProbeNotifyBump		|| !IsProbing( Event_NotifyBump ), GetContext() );
	DMAssert( bProbeSeeEnemy			|| !IsProbing( Event_SeeEnemy ), GetContext() );
	//DMAssert( bProbeTick				|| !IsProbing( Event_Tick ), GetContext() );
	//DMAssert( bProbeTimer				|| !IsProbing( Event_Timer ), GetContext() );
	//DMAssert( bProbeTrigger			|| !IsProbing( Event_Trigger ), GetContext() );

	//!!mdf-tbd: currently is being handled globally...
	//DMAssert( !IsProbing( Event_AnimEnd ), GetContext() );

	//DumpAIEvents();
#debugend	
}

//-----------------------------------------------------------------------------
// mdf-tbr: testing...

function DumpAIEvents()
{
	DMTNS( "DumpAIEvents -- begin Pawn: " $ Pawn );
	ID();

	DM( "AnimEnd               " $ byte(IsProbing( Event_AnimEnd ))				$ " (X)" );
	DM( "EnemyNotVisible       " $ byte(IsProbing( Event_EnemyNotVisible ))		$ " (" $ byte(bProbeEnemyNotVisible)		$ ")" );
	DM( "HearNoise             " $ byte(IsProbing( Event_HearNoise ))				$ " (" $ byte(bProbeHearNoise)				$ ")" );
	DM( "NotifyBump            " $ byte(IsProbing( Event_NotifyBump ))				$ " (" $ byte(bProbeNotifyBump)				$ ")" );
	DM( "EnemyInvalid	       " $ byte(IsProbing( Event_EnemyInvalid ))           $ " (" $ byte(bProbeEnemyInvalid)           $ ")" );	
	DM( "EnemyInLeapRange      " $ byte(IsProbing( Event_EnemyInLeapRange ))       $ " (" $ byte(bProbeEnemyInLeapRange)       $ ")" );
	DM( "EnemyInMeleeRange     " $ byte(IsProbing( Event_EnemyInMeleeRange ))      $ " (" $ byte(bProbeEnemyInMeleeRange)      $ ")" );
	DM( "EnemyNotInMeleeRange  " $ byte(IsProbing( Event_EnemyNotInMeleeRange ))   $ " (" $ byte(bProbeEnemyNotInMeleeRange)   $ ")" );
	DM( "EnemyRangeTransition  " $ byte(IsProbing( Event_EnemyRangeTransition ))   $ " (" $ byte(bProbeEnemyRangeTransition)   $ ")" );
	DM( "SeeEnemy              " $ byte(IsProbing( Event_SeeEnemy ))				$ " (" $ byte(bProbeSeeEnemy)				$ ")" );
	DM( "SeeFriend             " $ byte(IsProbing( Event_SeeFriend ))				$ " (" $ byte(bProbeSeeFriend)				$ ")" );
	DM( "SeeAlertFriend        " $ byte(IsProbing( Event_SeeAlertFriend ))			$ " (" $ byte(bProbeSeeAlertFriend)			$ ")" );
	DM( "SeeOther              " $ byte(IsProbing( Event_SeeOther ))				$ " (" $ byte(bProbeSeeOther)				$ ")" );
	DM( "ActorRangeTransition  " $ byte(IsProbing( Event_ActorRangeTransition ))	$ " (" $ byte(bProbeActorRangeTransition)   $ ")" );
	DM( "Tick                  " $ byte(IsProbing( Event_Tick ))					$ " (X)" );
	DM( "Timer                 " $ byte(IsProbing( Event_Timer ))					$ " (X)" );
	DM( "Trigger               " $ byte(IsProbing( Event_Trigger ))				$ " (X)" );

	//DM( "All Probes:" );
	//DumpProbes();
	OD();
	DMTNS( "DumpAIEvents -- end Pawn: " $ Pawn );
}

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

event float Desireability( Pickup P )
{
	// mdf-tbr: make sure only called for bots!
	DMAssert( false, GetContext() );
	return 0.0;
}

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

function ETacticalMoveType GetTacticalMoveType()
{
	if( LPawn.GetAlert() )
		return Pawn.TacticalMoveType;
	else
		return Super.GetTacticalMoveType();
}
	
//-----------------------------------------------------------------------------

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

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

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

	Super.Possess( P );

	Pawn.SetMovementPhysics( true ); 

	SetPeripheralVision();

	// mdf-tbr in 829 (SteveP added this to AIController.uc)
	// preserve Pawn's rotation initially for placed Pawns
	FocalPoint = Pawn.Location + 512*vector(Pawn.Rotation);

	InitializeEvents();

	PossessStartup();
}

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

event Destroyed()
{
	RemoveAllTimers();
	ClearHoldSpots();
	Super.Destroyed();
}

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

/* not enough room for both state and script...
function string GetStateInfoString()
{
	if( HasScript() )
		return Super.GetStateInfoString() $ "/" $ ScriptController.GetCommandFile();
	else
		return Super.GetStateInfoString();
}
*/

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

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

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

	// NOTE: actual damage might be filtered out 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
	{
		// not called if NPC is dead
		TookDamage( Damage, Instigator, HitLocation, Momentum, DamageType );
	}
}

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

function DamageAttitudeTo( Pawn Other, float Damage, class<DamageType> DamageType )
{
	#debug DMAIA( "DamageAttitudeTo  Other: " $ Other $ " Damage: " $ Damage $ " DamageType: " $ DamageType );

	if( Pawn != None && Pawn.Health > 0 )
	{
		#debug DMAIA( "DamageAttitudeTo: " $ ControllerEnemy $ " ValidEnemy(Other): " $ ValidEnemy( Other ) );

		if( ValidEnemy( Other ) )
		{
			#debug DMAI( "DamageAttitudeTo -- calling MaybeSetEnemy" );
			MaybeSetEnemy( Other );
		}
	
		//NOTE (mdf) - don't necessarily have LOS to enemy...
		if( ControllerEnemy != None && ControllerEnemy == Other )
			EnemyDetected( ControllerEnemy.Location );
	}
}

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

function eventTookDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
{
	// mdf: don't react if dead (was resurrecting dead NPCs...)
	Super.eventTookDamage( Damage, Instigator, HitLocation, Momentum, DamageType );

	// let some NPCs become aggressive when they take damage (attack next enemy, not damage instigator)
	// do this before checking if dead because we might want to alert nearby NPCs
	//DMTNS( "eventTookDamage" );
	if( U2PBase.bAmbientCreature && (float(U2PBase.Health) / float(U2PBase.InitialHealth)) < U2PBase.BecomeAggressiveHealthRatio )
	{
		//DMTNS( "becoming aggressive" );
		U2PBase.bAmbientCreature = false;
	}
	
	if( Pawn.Health > 0 )
	{
		// maybe set Instigator as enemy -- in some states (e.g. attacktactical, instigator is ignored)
		DamageAttitudeTo( Instigator, Damage, DamageType );

		#debug DMAI( "eventTookDamage -- Pawn is valid (set and alive)");
	}
}

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

function NotifyInvalidLanding( CheckResult Hit )
{
	GotoState( HandleInvalidLandingState );
}

/*-----------------------------------------------------------------------------
MinZ support: save NPCs who cross the MinZ threshold iff:

A: NPC is friendly to the player and has a script (could be autonomous)

OR

B: NPC isn' t friendly to the player but is currently executing a script

The idea is that friendly NPCs with a script are often critical to the 
continuation of the game so that we need to save them. Non-friendly NPCs which 
are autonomous (even if the have a script to go back to) should never be
essential to the game -- the fact that they are autonomous means they are 
fighting and could die from that, let alone from falling out of the world.
*/

event FellOutOfWorld()
{
	local U2NPCControllerBase U2NPCB;
	local EAttitude AttitudeToPlayer;
	local Pawn PlayerPawn;

	if( Level.PlayerControllerList != None )
		PlayerPawn = Level.PlayerControllerList.Pawn;
	
	if( PlayerPawn != None )
		AttitudeToPlayer = GetAttitudeTo( PlayerPawn );
		
	if( (AttitudeToPlayer == ATTITUDE_Friend && HasScript()) ||
	    (AttitudeToPlayer != ATTITUDE_Friend && UnderScriptControl()) )
	{
		// save NPC
		#debug DMAIM( "FellOutOfWorld trying to save NPC" );
		NavigationError( ET_MinZ, "FellOutOfWorld" );
		
		if( !U2P.bDisableErrorColors )
			AddActor( Pawn, ColorCyan() );
			
		StopMovement( true, true );
		MoveTimer = -1.0;

		if( RecoverFromMinZError() && !U2P.bDisableErrorColors )
			AddCylinder( Pawn.Location, 4, 4, ColorCyan() );
	}
	else
	{
		// default handling
		Pawn.HandleFellOutOfWorld();
	}
}

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

function UpdateEnemy( optional bool bTryRadiusCheck )
{
	if( !ValidEnemy( ControllerEnemy ) )
	{
		#debug DMAI( "UpdateEnemy clearing enemy" );
		#debug   SetControllerEnemy( None, GetContext() );
		#release SetControllerEnemy( None );
	}
}

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

function EReaction GetReactionToEnemy( Pawn EnemyPawn )
{
	return REACTION_Fear;
}

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

function bool DeferTo( Controller Other )
{
	return false;
}

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

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

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

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

// 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( MoveFailedLabel );
	
@ ErrorLabel:
	#debug DMAIL( ErrorLabel );
	NavigationError( ET_InternalPath, "at move error label" );
	Goto( MoveFailedLabel );

@ MoveFailedLabel:
	StopMovement( true, true );
	Stop;

@ MoveFallingLabel:
	WaitForLanding();
	Goto( MovePickDestLabel );
	Stop;
} // MoveToGoalBaseState

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

//-----------------------------------------------------------------------------
// Pawn can't move or rotate but can still aim and shoot. Not moved by damage.

state @ CantMoveState
{
	//-------------------------------------------------------------------------

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

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

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

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

	function UnFreeze()
	{
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}

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

	event BeginState()
	{
		Super.BeginState();
		StopMovement( true, true );
	}
	
@ BeginLabel:
	Stop;
} // CantMoveState

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

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

	function PlayRandomSound();

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

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

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

	function PlayRandomSound();

	//-------------------------------------------------------------------------
	// NOTE: NotifyHeadVolumeChange appears to not be implemented currently --
	// its not being called anywhere. HeadVolumeChange *is* still being called 
	// (on the Pawn...)

	event bool NotifyHeadVolumeChange( PhysicsVolume NewHeadVolume )
	{
		Global.NotifyHeadVolumeChange( NewHeadVolume );
		if ( !NewHeadVolume.bWaterVolume )
		{
			#debug   WhatToDoNext( GetContext() );
			#release WhatToDoNext();
		}
		return false;
	}

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

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

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

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

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

	event BeginState()
	{
		bAdjustFromWalls = false;
	}

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

	event EndState()
	{
		bAdjustFromWalls = true;
	}

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

@ BeginLabel:
@ MovePickDestLabel:
	PickDestination();
	
@ MoveActiveLabel:	
	if( ControllerEnemy == None )
		MoveToPoint( Destination );
	else
		MoveToPoint( Destination, , ControllerEnemy );
		
	#debug   WhatToDoNext( GetContext() );
	#release WhatToDoNext();
	
	Goto( MovePickDestLabel );
} // FindAirState

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

state @ FrozenState extends @ CantMoveState
{
	ignores SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend, HearNoise, EnemyInLeapRange, EnemyInMeleeRange;
	
@ BeginLabel:
	StopMovement( true, true );
	Stop;
} // FrozenState

//-----------------------------------------------------------------------------
// NPC landed on a railing or something where it shouldn't be (mainly happens
// during leaps).

state @ HandleInvalidLandingState extends @ MoveToGoalBaseState
{
	ignores EnemyNotVisible, HearNoise, NotifyBump, SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend; // sensory input
	ignores BeginFalling, NotifyLanded, NotifyHitWall, NotifyHeadVolumeChange, NotifyPhysicsVolumeChange; // physics
	ignores ShotFiredNotification;
	ignores DamageAttitudeTo, EnemyInLeapRange, EnemyInMeleeRange;

	//-------------------------------------------------------------------------
	
	function NotifyInvalidLanding( CheckResult Hit );
	function EnemyAcquired();
	function HandlePanic();
	function bool CanDodge( optional bool bIgnoreFalling ) { return false; }

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

	function HandledInvalidLanding()
	{
		#debug   WhatToDoNext( GetContext() );
		#release WhatToDoNext();
	}
	
	//-------------------------------------------------------------------------

	function NotifyValidLanding( CheckResult Hit )
	{
		HandledInvalidLanding();
	}

	//-------------------------------------------------------------------------
	
	function Actor GetStepDownDestination( bool bForward )
	{
		local NavigationPoint Nav, BestNav;
		local vector NavVector;
		local float Distance, ClosestDistance;
		local float UnNormalizedCos;
		
		ClosestDistance = 999999.9;
		for( Nav=Level.NavigationPointList; Nav!=None; Nav=Nav.NextNavigationPoint )
		{
			NavVector = Nav.Location - Pawn.Location;
			UnNormalizedCos = NavVector dot vector(Pawn.Rotation);
			
			if( (bForward && UnNormalizedCos > 0.0 ) ||
				(!bForward && UnNormalizedCos <= 0.0 ) )
			{
				Distance = VSize( NavVector );
				if( Distance < 1200 && 
					Distance < ClosestDistance && 
					ActorReachable( Nav ) )
				{
					ClosestDistance = Distance;
					BestNav = Nav;
				}
			}
		}
		
		return BestNav;
	}
	
	//-------------------------------------------------------------------------
	// Try to pick a destination that will correct the problem asap.
	
	function bool PickDestination()
	{
		// find  the closest reachable navigation point within 1200 units and
		// in front of the NPC (pbly looks better and helps to avoid cycling
		// issues due to hitting something while moving forward, landing on it,
		// backing up, repeat)
		MoveTarget = GetStepDownDestination( true );

		if( MoveTarget == None )
		{
			// try again, but this time look for points behind the NPC
			MoveTarget = GetStepDownDestination( false);
		}

		//if( MoveTarget != None )
		//	AddActor( MoveTarget, ColorGreen() );
		
		//DMTNS( "MoveTarget: " $ MoveTarget );
		return ( MoveTarget !=  None );
	}

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

	event BeginState()
	{
		//DMTNS( "BeginState" );
		Super.BeginState();
		U2P.bCanKnockDown = false;
		U2P.bSpecialHardLandings = false;
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		//DMTNS( "EndState" );
		Super.EndState();
		if( U2P != None )
		{
			U2P.bCanKnockDown = U2P.default.bCanKnockDown;
			U2P.bSpecialHardLandings = U2P.default.bSpecialHardLandings;
		}
	}
	
	//-------------------------------------------------------------------------
	
@ BeginLabel:

@ MovePickDestLabel:
	WaitForLanding();
	
	if( !PickDestination() )
	{
		//DMTNS( "HandleInvalidLanding can't find a valid destination" );
		HandledInvalidLanding(); // can't find a suitable destination?!
	}
	
@ MoveActiveLabel:
	MoveToActor( MoveTarget, TMT_None, , , ControllerEnemy );
	if( MoveResult != MR_DestinationReached )
	{
		if( ++NumMoveAttempts <= 8 )
			Goto( MovePickDestLabel );
		//else
		//	DMTNS( "HandleInvalidLanding timed-out" );
	}

	HandledInvalidLanding();		
} // HandleInvalidLandingState

//-----------------------------------------------------------------------------
// 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
{
	//!!mdf allow NPC to acquire enemy without moving until state ends?
	ignores EnemyNotVisible, HearNoise, NotifyBump, SeeEnemy, SeeFriend, SeeOther, SeeAlertFriend; // sensory input
	ignores BeginFalling, NotifyLanded, NotifyHitWall, NotifyHeadVolumeChange, NotifyPhysicsVolumeChange; // physics
	ignores ShotFiredNotification; // other

	function PlayRandomSound();

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

	function LandedHardDone()
	{
		#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

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

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

	event final SeeAlertFriend( Pawn Seen )
		{ ScriptController.eventSCSeeAlertFriend( Self, Seen ); }

	event final SeeFriend( Pawn Seen )
		{ ScriptController.eventSCSeeFriend( Self, Seen ); }

	/* tbd	
	event final SeeOther( Actor Seen )
		{ ScriptController.eventSCSeeOther( Self, Seen ); }
	*/

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

	function string GetStateInfoString()
	{
		return ScriptController.GetCommandFile();
	}
	
	//-------------------------------------------------------------------------

	event final ActorRangeTransition( bool bInRange )
	{
		if( bInRange )
			ActorInRange();
		else
			ActorOutOfRange();	
	}

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

	function bool AllowFriendlyBumpStateChanges()
	{
		return false;
	}

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

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

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

	function HandleFinishedRotation()
	{
		FinishedRotation();
	}

	//-------------------------------------------------------------------------
	// NOTE: NPCs which use a base AI controller NPCs don't usually have 
	// attacks but this provides limited support for handling an acquired enemy 
	// while in the scripted state.
	
	function EnemyAcquired()
	{
		if( BaseAcquisitionState != '' )
		{
			// script might block reacting to enemy...
			AutoBegin( BaseAcquisitionState, BaseAcquisitionLabel );
		}
	}

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

	function bool AvoidFriendlyBump( Pawn Other )
	{
		if( !U2PBase.bAvoidFriendlyBumps )
			return false;
			
		if( Level.TimeSeconds < NextAdjustPositionTime )
		{
			//if( NextAdjustPositionTime - Level.TimeSeconds > 0.5 )
			//	DMTNS( "AvoidFriendlyBump " $ Other $ " still handling previous bump" );
			return false;
		}
		
		//!!mdf-tbd: only use with players?
		if( !Other.bIsRealPlayer )
		{
			//DMTNS( "AvoidFriendlyBump " $ Other $ " not a player" );
			return false;
		}
		
		//!!mdf-tbd:
		if( Pawn.Physics != PHYS_Walking )
		{
			//DMTNS( "AvoidFriendlyBump " $ Other $ " Physics: " $ Pawn.Physics );
			return false;
		}
			
		//!!mdf-tbd:
		//if( VSize( Pawn.Velocity ) > 0.0 )
		//	return false;

		//DMTNS( "AvoidFriendlyBump " $ Other $ "!" );
		return true;
	}

	//-------------------------------------------------------------------------
	
	function bool SetDestination( vector Direction, float Distance )
	{
		local vector TargetLocation;
		
		Direction.Z = 0; // assume walking
		TargetLocation = Pawn.Location + Distance * Direction;
		
		//AddCylinder( TargetLocation, 2, 2, ColorWhite() );
		
		class'UtilGame'.static.AdjustDestinationForPhysics( Pawn, TargetLocation );
		//AddCylinder( TargetLocation, 4, 4, ColorYellow() );
		//AddArrow( Pawn.Location, TargetLocation, ColorOrange() );
		
		if( Pawn.FitActorAt( TargetLocation ) == 0 )
		{
			//DMTNS( "!FitActorAt" );
			//AddActorAt( Pawn, TargetLocation, ColorPink() );
			return false;
		}

		if( !PointReachable( TargetLocation ) )
		{
			//DMTNS( "!PointReachable" );
			//AddActorAt( Pawn, TargetLocation, ColorOrange() );
			return false;
		}
		
		//DMTNS( "success" );
		Destination = TargetLocation;
		return true;
	}
	
	//-------------------------------------------------------------------------

	function MaybeAvoidFriendlyBump	( Pawn Other )
	{
		local bool bFoundAdjustedLocation;
		local vector AvoidVector2D, CheckVector2D;
		local vector TargetLocation;
		local float ShiftDistance;
		local CheckResult Hit;
		
		Global.MaybeAvoidFriendlyBump( Other );
		
		//!!mdf-tbd: use this in other states too?
		if( IsMobile() && AvoidFriendlyBump( Other ) )
		{
			ShiftDistance = 2.0 * FMax( Pawn.CollisionRadius, Other.CollisionRadius );

			// try to move right/left then back if necessary
			
			// try right/left
			AvoidVector2D = Normal( (Other.Location - Pawn.Location) cross vect(0,0,1) );
			if( (AvoidVector2D dot Other.Velocity) > 0 )
				AvoidVector2D *= -1.0;
			
			//!!mdf-tbd: try 8 compass pts? Seems to work well as-is
			//DMTNS( "try + 2 x ShiftDistance");
			bFoundAdjustedLocation = SetDestination( AvoidVector2D, 2*ShiftDistance );
			if( !bFoundAdjustedLocation )
			{
				//DMTNS( "try - 2 x ShiftDistance");
				bFoundAdjustedLocation = SetDestination( -AvoidVector2D, 2*ShiftDistance );
			}
			if( !bFoundAdjustedLocation )
			{
				//DMTNS( "try + 1 x ShiftDistance");
				bFoundAdjustedLocation = SetDestination( AvoidVector2D, ShiftDistance );
			}
			if( !bFoundAdjustedLocation )
			{
				//DMTNS( "try - 1 x ShiftDistance");
				bFoundAdjustedLocation = SetDestination( -AvoidVector2D, ShiftDistance );
			}

			if( !bFoundAdjustedLocation )
			{
				// if room for both Pawns, try left/right smaller amounts
				TargetLocation = Pawn.Location;
				if( Pawn.FitActorAt( TargetLocation, Pawn.CollisionHeight, Pawn.CollisionRadius + Other.CollisionRadius + 1.0 ) != 0 )
				{
					//DMTNS( "try + 0.5 x ShiftDistance");
					bFoundAdjustedLocation = SetDestination( AvoidVector2D, 0.5*ShiftDistance );
					
					if( !bFoundAdjustedLocation )
					{
						//DMTNS( "try - 0.5 x ShiftDistance");
						bFoundAdjustedLocation = SetDestination( -AvoidVector2D, 0.5*ShiftDistance );
					}
				}
				//else
				//{
				//	AddCylinder( TargetLocation, Pawn.CollisionHeight, Pawn.CollisionRadius + Other.CollisionRadius + 2.0, ColorMagenta() );
				//}
			}
			
			if( !bFoundAdjustedLocation )
			{
				// try back
				//DMTNS( "try back 2 x ShiftDistance");
				AvoidVector2D = Pawn.Location - Other.Location;
				AvoidVector2D.Z = 0;
				AvoidVector2D = Normal( AvoidVector2D );

				//AddArrow( Pawn.Location, Pawn.Location + 2*ShiftDistance*AvoidVector2D, ColorOrange() );				
				bFoundAdjustedLocation = SetDestination( AvoidVector2D, 2*ShiftDistance );
				if( !bFoundAdjustedLocation )
				{
					//AddArrow( Pawn.Location, Pawn.Location + ShiftDistance*AvoidVector2D, ColorOrange() );
					//DMTNS( "try back 1 x ShiftDistance");
					bFoundAdjustedLocation = SetDestination( AvoidVector2D, ShiftDistance );
				}
			}

			if( !bFoundAdjustedLocation )
			{
				// check for tight corridor (wall close to NPC on at least 1 
				// side) and use wall's hit normal to send the NPC directly 
				// back along the wall relative to other's location

				CheckVector2D = Normal( (Other.Location - Pawn.Location) cross vect(0,0,1) );

				if( !Pawn.SingleLineCheck( Hit, Pawn, Pawn.Location + 2*Pawn.CollisionRadius*CheckVector2D, Pawn.Location, TRACE_AllBlocking ) )
				{
					AvoidVector2D = Hit.Normal cross vect(0,0,1);
					if( (AvoidVector2D dot Normal( Other.Location - Pawn.Location )) > 0 )
						AvoidVector2D *= -1.0;
						
					//DMTNS( "try special back 2 x ShiftDistance");
					//AddArrow( Pawn.Location, Pawn.Location + 2*ShiftDistance*AvoidVector2D, ColorPink() );				
					bFoundAdjustedLocation = SetDestination( AvoidVector2D, 2*ShiftDistance );
					if( !bFoundAdjustedLocation )
					{
						//AddArrow( Pawn.Location, Pawn.Location + ShiftDistance*AvoidVector2D, ColorPink() );
						//DMTNS( "try back 1 x ShiftDistance");
						bFoundAdjustedLocation = SetDestination( AvoidVector2D, ShiftDistance );
					}
				}
			}

			if( bFoundAdjustedLocation )
			{
				//DMTNS( "will adjust position" );
				Focus = Other;
				NextAdjustPositionTime = Level.TimeSeconds + AdjustAgainDelay;
				NextScriptedMoveTime = Level.TimeSeconds + AvoidedBumpWaitTime; // make sure script doesn't move NPC during adjust
				MoveTimer = -1.0f; // kill off any existing MoveToPoint/Actor
				GotoLabel( AdjustPositionLabel );
			}
			else
			{
				// if NPC was unable to get out of the way, filter additional 
				// bumps for a bit to avoid trying to handle too many bumps?
				NextAdjustPositionTime = Level.TimeSeconds + 0.50;
			}
		}
	}

	//-------------------------------------------------------------------------
	// If above call to AutoBegin is reflected back to this function then the
	// script is allowing the NPC to go autonomous.

	function eventAutoBegin( name DestinationState, name DestinationLabel )
	{
		ClearScriptTarget();
    	GotoState( DestinationState, DestinationLabel ); //GS-OK
	}

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

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

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

	function SetSpecialGoal( Actor NewSpecialGoal, optional float NewSpecialGoalDistance, optional bool bFaceSpecialGoalNew )
	{
		#debug DMAIE( "SetSpecialGoal: " $ NewSpecialGoal );
		Super.SetSpecialGoal( NewSpecialGoal, NewSpecialGoalDistance, bFaceSpecialGoalNew );
		
		//DMTNS( "SetSpecialGoal time until ok to move: " $ NextScriptedMoveTime - Level.TimeSeconds );
		
		if( NewSpecialGoal != None )
		{
			//!!mdf-tbd: assume that with non-Pawn destinations, we don't ever need
			// to enable "get out of way" behavior since a) scripted NPCs can walk
			// through the player (enemies will attack him) and b) we should never
			// send an NPC to a location in which the player could be trapped unless
			// the NPC will move shortly. Otherwise the script can/should enable
			// bump handling for the NPC or the destination should be moved.
			if( Pawn(NewSpecialGoal) == None )
				U2PBase.bAvoidFriendlyBumps = false;
			else
				U2PBase.bAvoidFriendlyBumps = U2PBase.default.bAvoidFriendlyBumps;
		}
		
		// postpone move if doing a special move (e.g. avoid bump) -- that 
		// code will ensure that this move eventually happens
		if( Level.TimeSeconds >= NextScriptedMoveTime )
			GotoLabel( MovePickDestLabel );
	}

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

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

	//-------------------------------------------------------------------------
	// 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 ETacticalMoveType GetTacticalMoveType()
	{
		return ScriptedTacticalMoveType;
	}

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

	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();
			bDidStartup = true;
		}

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

		//mdf-ENE
		#debug   SetControllerEnemy( None, GetContext() );
		#release SetControllerEnemy( None );
		// SetAlertness( 0.0 );
		// DMN( GetStateName() $ " -- BeginState" );

		if( !U2PBase.bLookForAlertFriends )
			Disable( Event_SeeAlertFriend );

		// set even if not friendly to player in case this changes (e.g. via the script)
		Pawn.bCanEncroachPlayer = true;
		
		//!!mdf-tbd: this makes sense in theory (so that scripted Pawns will always
		//face along their direction of movement) but it may be messing with existing
		//behavior (causing NPCs to be oriented in slightly different ways).
		Pawn.bCanStrafe = U2PBase.bCanStrafeScripted;

		// this only gets enabled during / after "gotoactor somepawn"
		U2PBase.bAvoidFriendlyBumps = false;
	}

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

	event EndState()
	{
		if( Pawn != None )
		{
			Pawn.RotationRate.Yaw = Pawn.default.RotationRate.Yaw;
			Pawn.bCanEncroachPlayer = false;
			RestoreCanStrafe();
			U2PBase.bAvoidFriendlyBumps = U2PBase.default.bAvoidFriendlyBumps;
		}
		
		// if scripted to use something -- can no longer be using it
		UnuseActor();

		//!!mdf: this might be enabling senses which aren't needed for some NPCs 
		// should respect bProbeSeeMonster etc.
		#debug DMAI( "EnableSenses in EndState" );
		EnableSenses();
	}

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

@ 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();
	Sleep( 0.2 );
	bInitializedForScripting = true;
	EnableSenses(); // have to do before call to Initialize -- might never get to line after that
	ScriptController.InitializeScriptController( Self );
	Goto( BeginLabel );

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

@ AdjustPositionLabel:
	//DMTNS( "adjusting position" );
	#debug DMAIA( "adjusting position" );
	//AddActorAt( Pawn, Destination, ColorGreen() );
	//AddArrow( Pawn.Location, Destination, ColorGreen() );
	ClearMoveAttempts();
	
@ AdjustPositionAgainLabel:
	//DMTNS( "AdjustPositionAgainLabel" );
	FocalPoint = Focus.Location;
	
	//DMTNS( "MoveToPoint BEGIN  Destination: " $ Destination $ " Distance: " $ VSize( Pawn.Location - Destination ) );
	// allow strafing in this situation (if NPC supports it)
	Pawn.bCanStrafe = Pawn.default.bCanStrafe;
	//!!mdf-tbd: is using a threshold of 2.0 going to hold up under low framerates?
	MoveToPoint( Destination, 2.0, Focus, 2*Pawn.WalkingPct );
	//DMTNS( "MoveToPoint END returned MoveResult: " $ EnumStr( enum'EMoveResult', MoveResult ) );
	Pawn.bCanStrafe = U2PBase.bCanStrafeScripted;
	
	if( MoveResult != MR_DestinationReached && MoveResult != MR_DestinationReachedFinal )
	{
		// NPC isn't using full speed for this move so allow for a few timeouts
	 	if( NumMoveAttempts++ < 3 )
			Goto( AdjustPositionAgainLabel );
	}

	StopMovement( true, true );	
	NextAdjustPositionTime = 0.0; // re-enable bump handling?
	NextScriptedMoveTime = Level.TimeSeconds + AvoidedBumpWaitTime; // make sure script doesn't move NPC during adjust
	//DMTNS( "made it" );
	
@ AdjustRotationLabel:
	#debug DMAIA( "adjusting rotation" );
	//DMTNS( "adjusting rotation" );
	FocalPoint = Focus.Location;
	FinishRotation( DefaultRotationThreshold );
	Sleep( AvoidedBumpWaitTime );
	Goto( MovePickDestLabel );

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

	#debug DMAIL( BeginLabel );

@ MovePickDestLabel:
	//DMTNS( "MovePickDestLabel" );
	ClearMoveAttempts();
	
@ MovePickDestLoopLabel:
	//DMTNS( "calling WaitForLanding  Focus: " $ Focus );
	WaitForLanding();
	//DMTNS( "called WaitForLanding  Focus: " $ Focus );
	Pawn.RotationRate.Yaw = Pawn.default.RotationRate.Yaw;
	#debug DMAIL( MovePickDestLabel );

	// figure out where to go
	#debug DMAI( "Calling SetMoveTarget Goal=" $ GetSpecialGoal() );
	//DMTNS( "Calling SetMoveTarget Goal=" $ GetSpecialGoal() $ " Distance=" $ GetSpecialGoalDistance() $ " Focus: " $ Focus );

	// mdf-tbd: if previous move simply timed out could probably just reuse old destination
	GMoveType = SetMoveTarget( GetSpecialGoal(), GetSpecialGoalDistance() );

@ MoveCheckLabel:
	//DMTNS( "MoveCheckLabel GMoveType: " $ EnumStr( enum'EMoveType', GMoveType ) $ " Focus: " $ Focus );
	if( GMoveType == MT_Error )
	{
  		#debug DMAIM( "!SetMoveTarget -- Abort" );
		Goto( ErrorLabel );
	}

	if( GMoveType == MT_None )
	{
  		//#debug DMAIM( "no scripted destination -- going idle" );
  		//DMTNS( "no scripted destination -- going idle" );
		Goto( IdleLabel );
	}

	if( GMoveType == MT_Wait )
	{
  		#debug DMAIM( "SetMoveTarget -- waiting..." );
  		//DMTNS( "SetMoveTarget -- waiting..." );
  		StopMovement( true, true );
		if( Pawn(GetSpecialGoal()) != None )
		{
			// always face Pawn goal?
			//DMTNS( "facing Pawn goal" );
			Focus = GetSpecialGoal();
			FocalPoint = Focus.Location;
			if( NeedToTurn( FocalPoint, NeedToTurnAngleCos ) )
				FinishRotation( ScriptedRotationThreshold );
			SetRotation( Pawn.Rotation );
		}
  		Sleep( 0.5 ); //!! mdf-tbd: track distance to goal actor and break out of sleep if distance becomes > x?
		Goto( MovePickDestLoopLabel );
	}

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

@ MoveActiveLabel:
	//DMTNS( "MoveActiveLabel" );
	//DMTNS( "MoveToActor BEGIN MoveTarget:" $ MoveTarget $ " FinalTarget:" $ GetSpecialGoal() $ " FinalDistance:" $ SpecialGoalDistance $ " Focus:" $ ScriptedFocus );
	//DMTNS( " (GroundSpeed:" $ Pawn.GroundSpeed $ " DesiredSpeed:" $ Pawn.DesiredSpeed $ " MoveSpeed:" $ GetMoveSpeed() $ ")" );
	MoveToActor( MoveTarget, GetTacticalMoveType(), GetSpecialGoal(), GetSpecialGoalDistance(), ScriptedFocus, GetMoveSpeed() );
	//DMTNS( "MoveToActor END returned MoveResult: " $ EnumStr( enum'EMoveResult', MoveResult ) );

	if( MoveResult != MR_DestinationReachedFinal || U2P.bCauseScriptedNavError )
	{
		if( U2P.bCauseScriptedNavError )
		{
			#debug DMAIM( "testing navigation error recovery -- forcing a bad move result" );
			//DMTNS( "testing navigation error recovery -- forcing a bad move result" );
			StopMovement( true, true );
			NumMoveAttempts = MaxMoveToActorAttempts;
			NumMoveRecoverAttempts = MaxMoveRecoverAttempts;
		}

		// mdf-tbd: if not a timeout -- give up immediately (blocked?)
		// after more than N tries give up
	 	if( NumMoveAttempts++ < MaxMoveToActorAttempts )
		{
			Goto( MovePickDestLoopLabel );
	 	}
		else if( NumMoveRecoverAttempts++ < MaxMoveRecoverAttempts )
	 	{
			#debug DMAIM( "sleep, try moving again in a bit" ) ;
			//DMTNS( "sleep, try moving again in a bit" ) ;
	 		StopMovement( true, true );
			Sleep( 1.0 );
			NumMoveAttempts = 0;
			Goto( MovePickDestLoopLabel );
	 	}
		else
		{
			#debug DMAIM( "Trying to teleport to move target / nearby pathnode" );
			NavigationError( ET_Move, "scripted move to " $ GetSpecialGoal() $ " SpecialGoalDistance: " $ GetSpecialGoalDistance() );
			U2P.MakeErrorObvious( ET_Move );
			if( !U2P.bDisableErrorColors )
			{
				AddActor( Pawn, ColorMagenta() );
				AddActorAt( Pawn, GetSpecialGoal().Location, ColorMagenta() );
				AddArrow( Pawn.Location, GetSpecialGoal().Location, ColorMagenta() );
			}
			
@ MoveTestLabel:

			GMoveType = RecoverFromNavigationError( GetSpecialGoal(), GetSpecialGoalDistance(), true );
			
			if( GMoveType == MT_Success || GMoveType == MT_Near )
			{
				#debug DMAIM("Teleport succeeded");
				if( !U2P.bDisableErrorColors )
					AddCylinder( Pawn.Location, 4, 4, ColorMagenta() );
				U2P.bCauseScriptedNavError = false;
				ClearMoveAttempts();
				Goto( MoveCheckLabel );
			}
			else
			{
				#debug DMAIM("Teleport failed");
				//DMTNS("Teleport failed");
				Sleep( 1.0 );
				if( U2P.bCauseScriptedNavError )
					Goto( MoveTestLabel );
				else
					Goto( MovePickDestLoopLabel );
			}
		}
	}

@ ReachedDestinationLabel:
	#debug DMAIL( ReachedDestinationLabel );
	//DMTNS( ReachedDestinationLabel );

	//2002.11.23 !!mdf-tbd: if a specific distance was given make sure we stop?
	if( SpecialGoalDistance >= 0.0 )
		StopMovement( true, true );
		
	SpecialGoalDistance = default.SpecialGoalDistance;
	if( bDirectionalPatrol && GetSpecialGoal().bDirectional )
	{
		StopMovement( true, true );

		#debug DMAI( "executing bDirectionalPatrol code" );
		//DMTNS( "executing bDirectionalPatrol code Focus: " $ Focus );
		
		//AddArrow( Pawn.Location, Pawn.Location + 1024.0*vector(Pawn.Rotation), ColorPink() );
		PotentialFocalPoint = GetSpecialGoal().Location + 200*vector(GetSpecialGoal().Rotation);
		//AddCylinder( PotentialFocalPoint, 4, 4, ColorPink() );
		//DMTNS( "Calling NeedToTurn  Focus: " $ Focus );
		if( NeedToTurn( PotentialFocalPoint, NeedToTurnAngleCos ) )
		{	
			//DMTNS( "turning  Focus: " $ Focus );
			Focus = None;
			FocalPoint = PotentialFocalPoint;
			FinishRotation( ScriptedRotationThreshold );
		}
		else
		{
			//DMTNS( "not turning  Focus: " $ Focus );
			Focus = None;
			FocalPoint = Pawn.Location + 512*vector(Pawn.Rotation);
		}
		
		//AddArrow( Pawn.Location, Pawn.Location + 1024.0*vector(Pawn.Rotation), ColorGreen() );
		SetRotation( Pawn.Rotation );
	}
	else if( Pawn(GetSpecialGoal()) != None )
	{
		// always face Pawn goal?
		//DMTNS( "facing Pawn goal" );
		Focus = GetSpecialGoal();
		FocalPoint = Focus.Location;
		if( NeedToTurn( FocalPoint, NeedToTurnAngleCos ) )
			FinishRotation( ScriptedRotationThreshold );
		SetRotation( Pawn.Rotation );
	}
	else
	{
		//DMTNS( "looking straight ahead" );
		if( ScriptedFocus == None )
			Focus = None; // clear NPC looking at goal?
		FocalPoint = Pawn.Location + 512*vector(Pawn.Rotation);
		SetRotation( Pawn.Rotation );
	}

	Sleep( 0.01 ); // sleep for 1 tick to allow any locked animations to be cleared at this point

	#debug DMAIM( "reached destination -- calling HandleDestinationReached!" );
	//DMTNS( "reached destination -- calling HandleDestinationReached!" );
	HandleDestinationReached();

	//DMTNS( "after HandleDestinationReached" );
	// this line might not be executed if HandleDestinationReached causes script
	// to execute a command which changes the state / state code location
	
@ IdleLabel:
	#debug DMAI( "IdleLabel: " $ bScriptedIdleAnims );
	//DMTNS( "IdleLabel: " $ bScriptedIdleAnims );
	// NPC isn't moving -- play idle animations
@ TurnLabel:
	StopMovement( true, false );	// make sure NPC stops moving
	#debug DMAI( "TurnLabel -- ControllerTarget: " $ ControllerTarget );
	// script has given us a target to rotate towards
	if( ControllerTarget != None )
	{
		//DMTNS( "turn towards target: " $ ControllerTarget );
		if( NeedToTurn( ControllerTarget.Location, NeedToTurnAngleCos ) )
		{	
			#debug DMAI( "Need to turn towards target: " $ ControllerTarget );
	
			// need to rotate towards it
			StopMovement( true, true );
			Focus = None;
			FocalPoint = ControllerTarget.Location;
			Pawn.RotationRate.Yaw = U2PBase.RotationRateYawScripted;
			FinishRotation( ScriptedRotationThreshold );
			Pawn.RotationRate.Yaw = Pawn.default.RotationRate.Yaw;
		}
		SetRotation( Pawn.Rotation );

		// let script controller know rotation is complete
		#debug DMAI( "Sending FinishedRotation" );
		HandleFinishedRotation();
	}

	if( !bScriptLockedTarget )
	{
		#debug   SetControllerTarget( None, GetContext() );
		#release SetControllerTarget( None );
	}
	Stop;
	
@ AutoEndLabel:
	// let script controller know to make sure EC is enabled so it starts doing its thing (only done once)
	if( MaxScriptedAutoEndDelay > 0.0 && (Level.TimeSeconds - GetRecentAutoEndTime( Pawn )) < MaxScriptedAutoEndDelay )
		Sleep( RandRange( 0.0, MaxScriptedAutoEndDelay ) );
	AutoEnd();
	LastAutoEndTime = Level.TimeSeconds;
	Goto( BeginLabel );
} // ScriptedState

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

state @ ScriptedDialogState extends @ ScriptedState
{
	function PlayRandomSound();

	//-------------------------------------------------------------------------
	
	function eventTakeDamage( int Damage, Pawn Instigator, vector HitLocation, vector Momentum, class<DamageType> DamageType )
	{
		local float OldHealth;
		if( Pawn? ) OldHealth = Pawn.Health;
		Super.eventTakeDamage( Damage, Instigator, HitLocation, Momentum, DamageType );
		if( Pawn? && Pawn.Health < OldHealth )
			class'DialogEngine'.static.NotifyDialogSpeakerTookDamage( Pawn );
	}

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

	function bool AvoidFriendlyBump( Pawn Other )
	{
		// otherwise most dialogs could get hosed?
		return false;
	}
	
	//-------------------------------------------------------------------------

	function DialogSetFocus( Actor FocusActor )
	{
		//DMTNS( "DialogSetFocus -- Focus Actor Parameter:" @ FocusActor @ "Current Focus:" @ Focus @ "MoveTarget:" @ MoveTarget @ "Old Focus:" @ OldFocus );

		// cache the old focus
		if( OldFocus == None )
		{
			if( MoveTarget != None )
				OldFocus = MoveTarget;
			else
				OldFocus = Focus;
			OldFocalPoint = FocalPoint;
		}

		DialogFocus = FocusActor;

		if( FocusActor == None )
		{
			// look straight ahead
			Focus = None;
			FocalPoint = Pawn.Location + 256*vector(Pawn.Rotation);
		}

		//NEW
		// 2003.01.06 (mdf) fix for Meyer falling off ledges -- previous test was bogus?
		//if( bIsPaused || GetSpecialGoal() == None )
		if( bIsPaused && (GetSpecialGoal() == None || !IsHandlingLatentMove()) )
		{
			// not moving -- can rotate towards focus
			Focus = None; // CDH: without this, it's possible for NeedToTurn to continuously fail, due to physics handling the turning to an old focus (turret people)
			GotoLabel( DialogFocusSetLabel ); // otherwise just keep doing movement while turning to new focus??
		}
		else if( FocusActor != None )
		{
			// moving -- change focus for move without interrupting the latent move
			ScriptedFocus = FocusActor;
			FocalPoint = FocusActor.Location;
		}
		/* OLD
		GotoLabel( DialogFocusSetLabel );
		*/
	}

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

	function DialogSetEndingFocus( Actor FocusActor )
	{
		// stomp on cached focus actor
		OldFocus = FocusActor;
	}

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

	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()
	{
		U2P.bHeadtrackingEnabled = bScriptedHeadTrackingEnabled;   //!!Fix (mw): this is an ugly place for this
		GotoLabel( DialogEndLabel );
	}

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

	function bool PreparedForDialog() 
	{
		if( NeedToTurn( DialogFocus.Location, NeedToTurnAngleCos ) )
		{
			GotoLabel( TurnLabel );
			return false;
		}
		else
		{
			return true;
		}
	}

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

	event BeginState()
	{
		SetAlertness( 0.5 );
		DialogFocus = None;
		DialogPause();
		
		// set even if not friendly to player in case this changes (e.g. via the script)
		Pawn.bCanEncroachPlayer = true;
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		DialogUnPause();
		RestoreAlertness();
		Focus = None; // CDH: benign according to MDF, and should stop occasional stuck-focus problem caused by state yanking
		OldFocus = None;
		OldFocalPoint = vect(0,0,0);
		if( Pawn != None )
		{
			Pawn.RotationRate.Yaw = Pawn.default.RotationRate.Yaw;
			Pawn.bCanEncroachPlayer = false;
		}
	}

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

@ DialogBeginLabel:
	Stop;

@ DialogEndLabel:
	// Restore Focus
	if( OldFocus != None && ControllerTarget == None )
	{
		Focus = OldFocus;
		FocalPoint = OldFocus.Location;
		if( U2Pawn(OldFocus) != None )
			FocalPoint += vect(0,0,1)* U2Pawn(OldFocus).BaseEyeHeight;

		if( NeedToTurn( Focus.Location, 1.0 ) )
		{
			Pawn.RotationRate.Yaw = U2PBase.RotationRateYawScriptedDialog;
			FinishRotation( ScriptedRotationThreshold );
			Pawn.RotationRate.Yaw = Pawn.default.RotationRate.Yaw;
		}
	}

	//DMTNS("DialogEndLabel - End: Focus:" @ Focus @ "MoveTarget:" @ MoveTarget );
	#debug   WhatToDoNext( GetContext() );
	#release WhatToDoNext();
	Stop;

@ DialogFocusSetLabel:
	if( DialogFocus != None && NeedToTurn( DialogFocus.Location, NeedToTurnDialogAngleCos ) )
	{
		Focus = DialogFocus;
		FocalPoint = DialogFocus.Location;
		if( U2Pawn(DialogFocus) != None )
			FocalPoint += vect(0,0,1)* U2Pawn(DialogFocus).BaseEyeHeight;
		Pawn.RotationRate.Yaw = U2PBase.RotationRateYawScriptedDialog;
		FinishRotation( ScriptedRotationThreshold );
		Pawn.RotationRate.Yaw = Pawn.default.RotationRate.Yaw;
		Focus = None;
		FocalPoint = Pawn.Location + 256*vector(Pawn.Rotation);
    }
	Sleep( 1.0 );
	Goto( DialogFocusSetLabel );
	
@ DialogFocusRestoreLabel:
	Stop;
} // ScriptedDialogState

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

state @ TestMoveState extends @ MoveToGoalBaseState
{
	ignores EnemyNotVisible;

	//-------------------------------------------------------------------------
	
@ BeginLabel:
	#debug DMAIL( "BeginLabel" );
	ClearMoveAttempts();
	
@ MovePickDestLabel:
	#debug DMAIL( MovePickDestLabel @ TestMoveTarget);
	WaitForLanding();
	
	// figure out where to go
	#debug DMAIM( "Calling SetMoveTarget" );
	if( SetMoveTarget( TestMoveTarget ) <= MT_None )
	{
		#debug DMAIM( "Error calling SetMoveTarget" );
		Goto( ErrorLabel );
	}

@ MoveActiveLabel:
	#debug DMAIL( MoveActiveLabel );

	//DMTNS( "MoveToActor BEGIN MoveTarget:" $ MoveTarget $ " FinalTarget:" $ TestMoveTarget $ " NumMoveAttempts=" $ NumMoveAttempts );
	//DMTNS( " (GroundSpeed:" $ Pawn.GroundSpeed $ " DesiredSpeed:" $ Pawn.DesiredSpeed $ " MoveSpeed:" $ TestMoveSpeed $ ")" );
	MoveToActor( MoveTarget, TestTacticalMoveType, TestMoveTarget, , , TestMoveSpeed );
	//DMTNS( "MoveToActor END 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  //GS-OK
	Stop;
} // TestMoveState

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

state @ UsingState
{
	//-------------------------------------------------------------------------

	function UseActor( Actor A )
	{
		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 @ WanderingState
{
	ignores EnemyNotVisible;

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

	event final SeeAlertFriend( Pawn Seen )
		{ ScriptController.eventSCSeeAlertFriend( Self, Seen ); }

	/* tbd:	
	event final SeeFriend( Pawn Seen )
		{ ScriptController.eventSCSeeFriend( Self, Seen ); }

	event final SeeOther( Actor Seen )
		{ ScriptController.eventSCSeeOther( Self, Seen ); }
	*/

	/* mdf-tbd (stevep: FIXME)
	//-------------------------------------------------------------------------

	singular event BaseChange()
	{
		if( ( Pawn.Base != None ) && Mover(Pawn.Base) != None )
			Destination = Pawn.Location - 300 * Normal( Pawn.Velocity );
		else
			Super.BaseChange();
	}
	*/

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

	event bool NotifyPhysicsVolumeChange( PhysicsVolume NewVolume )
	{
		//DMTNS( "NotifyPhysicsVolumeChange: " $ NewVolume.bWaterVolume );

		if( Pawn.default.Physics == PHYS_Swimming && NewVolume.bWaterVolume && Pawn.bCanSwim && !Pawn.bCanFly ) // dive if left water or if entered water?
		{
			//DMTNS( "Setting WanderDirectionExternal" );
			WanderDirectionExternal = Pawn.CollisionRadius*4.0*vect(0,0,-1); // dive
		}
		
		return Global.NotifyPhysicSVolumeChange( NewVolume );
	}

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

	function bool DeferTo( Controller Other )
	{
		if( Pawn.Acceleration == vect(0,0,0) )
			return Global.DeferTo( Other );

		return false;
	}

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

	function float GetExtraWanderDistance()
	{
		return( U2PBase.WanderDistMax - U2PBase.WanderDistMin );
	}

	//-------------------------------------------------------------------------
	// Subclasses can implement walking-specific directions if they want.

	function vector GetWanderDirectionWalking( int FallbackType )
	{
		local vector ReturnedDirection;

		/*
		// show all possible fallback vectors:
    	ReturnedDirection = vector(Pawn.Rotation);
		ReturnedDirection.Z = 0.0;
		AddArrow( Pawn.Location, Pawn.Location + 256.0*vector(Pawn.Rotation), ColorMagenta() ); 
		AddArrow( Pawn.Location, Pawn.Location + 256.0*RotateAngleAxis( vector(Pawn.Rotation), vect(0,0,1),  0.5*U2PBase.WanderSpreadAngle*DegreesToRotationUnits ), ColorMagenta() ); 
		AddArrow( Pawn.Location, Pawn.Location + 256.0*RotateAngleAxis( vector(Pawn.Rotation), vect(0,0,1), -0.5*U2PBase.WanderSpreadAngle*DegreesToRotationUnits ), ColorMagenta() ); 
		AddArrow( Pawn.Location, Pawn.Location + 256.0*RotateAngleAxis( vector(Pawn.Rotation), vect(0,0,1),  U2PBase.WanderSpreadAngle*DegreesToRotationUnits ), ColorMagenta() ); 
		AddArrow( Pawn.Location, Pawn.Location + 256.0*RotateAngleAxis( vector(Pawn.Rotation), vect(0,0,1), -U2PBase.WanderSpreadAngle*DegreesToRotationUnits ), ColorMagenta() ); 
		*/
		
		if( WanderDirection == vect(0,0,0) )
	    	ReturnedDirection = vector(Pawn.Rotation);
		else if( FallbackType == 0 )
	    	ReturnedDirection = vector(rotator(WanderDirection) + rotator(RandomSpreadVector( U2PBase.WanderSpreadAngle )) );
		else
	    	ReturnedDirection = vector(Pawn.Rotation); // fallback directions wrt current rotation

		// eliminate Z component (if any)	    	
		ReturnedDirection.Z = 0.0;

		if( FallbackType == 2 )
			ReturnedDirection = RotateAngleAxis( ReturnedDirection, vect(0,0,1), 0.5*U2PBase.WanderSpreadAngle*DegreesToRotationUnits );
		else if( FallbackType == 3 )
			ReturnedDirection = RotateAngleAxis( ReturnedDirection, vect(0,0,1), -0.5*U2PBase.WanderSpreadAngle*DegreesToRotationUnits );
		else if( FallbackType == 4 )
			ReturnedDirection = RotateAngleAxis( ReturnedDirection, vect(0,0,1), U2PBase.WanderSpreadAngle*DegreesToRotationUnits );
		else if( FallbackType == 5 )
			ReturnedDirection = RotateAngleAxis( ReturnedDirection, vect(0,0,1), -U2PBase.WanderSpreadAngle*DegreesToRotationUnits );

		return Normal( ReturnedDirection );
	}

	//-------------------------------------------------------------------------
	// Subclasses can implement swimming-specific directions if they want.

	function vector GetWanderDirectionSwimming( int FallbackType )
	{
		local vector ReturnedDirection;

		if( WanderDirection == vect(0,0,0) )
	    	ReturnedDirection = vector(Pawn.Rotation);
		else if( FallbackType == 0 )
			ReturnedDirection = vector(rotator(WanderDirection) + rotator(RandomSpreadVector( U2PBase.WanderSpreadAngle )) );
		else
	    	ReturnedDirection = vector(Pawn.Rotation); // fallback directions wrt current rotation

		if( Pawn.default.Physics != PHYS_Swimming && Pawn.default.Physics != PHYS_Flying )
			ReturnedDirection.Z = 0;
			
		// NOTE: this could be improved (try vectors above and below as well as left/right)
		if( FallbackType == 2 )
			ReturnedDirection = RotateAngleAxis( ReturnedDirection, vect(0,0,1),  0.5*U2PBase.WanderSpreadAngle*DegreesToRotationUnits );
		else if( FallbackType == 3 )
			ReturnedDirection = RotateAngleAxis( ReturnedDirection, vect(0,0,1), -0.5*U2PBase.WanderSpreadAngle*DegreesToRotationUnits );
		else if( FallbackType == 4 )
			ReturnedDirection = RotateAngleAxis( ReturnedDirection, vect(0,0,1),  U2PBase.WanderSpreadAngle*DegreesToRotationUnits );
		else if( FallbackType == 5 )
			ReturnedDirection = RotateAngleAxis( ReturnedDirection, vect(0,0,1), -U2PBase.WanderSpreadAngle*DegreesToRotationUnits );
			
		ReturnedDirection = ClampVerticalComponent( Normal( ReturnedDirection ) );

		// pathological case?		
		if( ReturnedDirection == vect(0,0,0) )
	    	ReturnedDirection = vector(Pawn.Rotation);
		
		return Normal( ReturnedDirection );
	}

	//-------------------------------------------------------------------------
	// Subclasses can implement flying-specific directions if they want.
	// mdf-tbi: support circling birds etc.

	function vector GetWanderDirectionFlying( int FallbackType )
	{
		return GetWanderDirectionSwimming( FallbackType );
	}

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

	function vector GetWanderDirection( int FallbackType )
	{
		if( Pawn.Physics == PHYS_Walking )
			return GetWanderDirectionWalking( FallbackType );
		else if( Pawn.Physics == PHYS_Swimming )
			return GetWanderDirectionSwimming( FallbackType );
		else if( Pawn.Physics == PHYS_Flying )
			return GetWanderDirectionFlying( FallbackType );
		else
			return vect( 0,0,0 );
	}

	//-------------------------------------------------------------------------
	// Tend to wander shorter distances before selecting a new direction when 
	// hurt and/or alert?

	function float GetWanderDistanceModifier()
	{
		local float ReturnedMultiplier;

		ReturnedMultiplier = 1.0;

		if( U2PBase.bDistressedWandering )
		{
			if( LPawn.GetAlert() )
				ReturnedMultiplier *= 0.5;
			if( LPawn.GetHurt() )
				ReturnedMultiplier *= 0.5;
		}

		return ReturnedMultiplier;
	}

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

	function float GetModifiedMoveSpeed()
	{
		if( U2PBase.bDistressedWandering )
		{
			if( LPawn.GetHurt() )
				return RandRange( U2PBase.WanderSpeedMin, 1.5*U2PBase.WanderSpeedMax );		// move very erratically
			if( LPawn.GetAlert() )
				return RandRange( 0.5*U2PBase.WanderSpeedMax, 1.5*U2PBase.WanderSpeedMax ); // move quickly, changing speeds suddenly
		}
		
		return -1.0; // not hurt/alert
	}

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

	function float GetWalkingMoveSpeed()
	{
		return Pawn.WalkingPct; 
	}

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

	function float GetSwimmingMoveSpeed()
	{
		local float ReturnedSpeed;

		// smoothly increase/decrease speed between min and max
		ReturnedSpeed = WanderMoveSpeed;
		if( ReturnedSpeed > U2PBase.WanderSpeedMax - 0.10 )
			ReturnedSpeed -= FRand()*0.10;
		else if( ReturnedSpeed > U2PBase.WanderSpeedMin + 0.10 )
			ReturnedSpeed += FRand()*0.20 - 0.10;
		else
			ReturnedSpeed += FRand()*0.10;

		ReturnedSpeed = FClamp( ReturnedSpeed, U2PBase.WanderSpeedMin, U2PBase.WanderSpeedMax );

		return ReturnedSpeed;
	}

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

	function float GetFlyingMoveSpeed()
	{
		return GetSwimmingMoveSpeed();
	}

	//-------------------------------------------------------------------------
	// Simply returns the speed to use with the call to MoveToPoint when wandering,
	// e.g. a non-hurt/non-alert critter might wander around using his 
	// WalkingPct of 0.15 or so (the number scales the Ground/Air/WaterSpeed
	// in the engine implementation of MoveToPoint.

	function SetWanderMoveSpeed()
	{
		local float NewSpeed;

		NewSpeed = GetModifiedMoveSpeed();
		if( NewSpeed < 0.0 )
		{
			// not hurt/alert
			if( Pawn.Physics == PHYS_Walking )
				NewSpeed = GetWalkingMoveSpeed();
			else if( Pawn.Physics == PHYS_Swimming )
				NewSpeed = GetSwimmingMoveSpeed();
			else if( Pawn.Physics == PHYS_Flying )
				NewSpeed = GetFlyingMoveSpeed();
			else // probably shouldn't happen but is currently in water volumes...
				NewSpeed = FClamp( WanderMoveSpeed, U2PBase.WanderSpeedMin, U2PBase.WanderSpeedMax );
		}

		//DM( "GetWanderMoveSpeed: " $ NewSpeed );
		WanderMoveSpeed = NewSpeed;
	}

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

	function bool ShouldWanderPause()
	{
		return ( U2PBase.WanderPauseMax > 0.0 && FDecision( U2PBase.WanderPauseOdds ) );
	}

	//-------------------------------------------------------------------------
	// various hooks...

	function WanderDidMoveSpecialHandling();
	function WanderPauseSpecialHandling();
	function bool WanderPauseSpecialAnimation() { return false; }

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

	function vector ClampVerticalComponent( vector V )	
	{ 
		if( U2PBase.WanderMaxZComponent < 1.0 )
		{
			if( Abs(V.Z) > U2PBase.WanderMaxZComponent )
			{
				if( V.Z > 0 )
					V.Z =  U2PBase.WanderMaxZComponent;
				else
					V.Z = -U2PBase.WanderMaxZComponent;

				V = Normal( V );
			}
		}

		return V;
	}

	//-------------------------------------------------------------------------
	// Checks whether NPC can actually move in the given direction. Returns the
	// result vector in DestinationLocation and returns true/false to indicate
	// whether a result vector was obtained.

	function bool GetDestinationVector( vector Direction, float DesiredDistance, bool bRecovering, out vector DestinationLocation )
	{
		local Actor HitActor;
		local vector TraceExtents;
		local float SelectedDistance, DestinationDistance;
		local Color DrawColor;
		local float MaxJumpDownDistanceOld;
		local bool bResult;
		local CheckResult Hit;
		
		//AddCylinder( Pawn.Location, 8, 8, ColorPink() );
		//DMTNS( "GetDestinationVector" );
		
		#debug DMAIM( "  trying to move " $ DesiredDistance $ " units along " $ class'Util'.static.GetVectorString( Direction ) );
		//DMTNS( "  trying to move " $ DesiredDistance $ " units along " $ class'Util'.static.GetVectorString( Direction ) );

		if( VSize(Direction) ~= 0.0 )
		{
			DestinationLocation = Pawn.Location;
			return true;
		}
		
		#debug DMAssert( VSize(Direction) ~= 1.0, "Direction not normalized?  Direction: " $ Direction $ " Size: " $ VSize(Direction) $ " Physics: " $ Pawn.Physics );

		SelectedDistance = DesiredDistance;
		#debug DMAIM( "Initial SelectedDistance: " $ SelectedDistance );

		//---------------------------------------------------------------------
		// If any Pawns are in the way reduce the DesiredDistance 
		// (PointReachable won't detect actors in the way).
		//---------------------------------------------------------------------

		// slower check to avoid stepping over / hitting other pawns (could pbly make this stuff native if necessary)
		TraceExtents.X = Pawn.CollisionRadius;
		TraceExtents.Y = Pawn.CollisionRadius;
		TraceExtents.Z = 0.0;

		// anything blocking this move at ground level (allow for WanderMaxAvoidDistance)?
		DestinationDistance = (SelectedDistance + U2PBase.WanderMaxAvoidDistance);
		DestinationLocation = Pawn.Location + DestinationDistance*Direction;
		class'UtilGame'.static.AdjustDestinationForPhysics( Pawn, DestinationLocation );
		
		if( !Pawn.SingleLineCheck( Hit, Pawn, DestinationLocation, Pawn.Location, TRACE_AllBlocking, TraceExtents ) )
		{
			HitActor = Hit.Actor;
			
			if( Pawn(HitActor) != None )
			{
				// hit a pawn -- back off to respect NPC's "comfort zone"
				//SelectedDistance = VSize2D( Pawn.Location - HitActor.Location ) - Pawn.CollisionRadius - HitActor.CollisionRadius - 1.0;
				//SelectedDistance = VSize2D( Pawn.Location - HitActor.Location ) - HitActor.CollisionRadius - 1.0;
				SelectedDistance = class'Util'.static.GetDistanceBetweenActors( Pawn, HitActor ) - 1.0;
				if( ClassIsChildOf( HitActor.Class, Pawn.Class ) )
				{
					//DMTNS( "using same class pawn avoid distance" );
					SelectedDistance -= U2PBase.WanderAvoidPawnSameDistance;
				}
				else
				{
					//DMTNS( "using diff class pawn avoid distance" );
					SelectedDistance -= U2PBase.WanderAvoidPawnDiffDistance;
				}
			}			
			else
			{
				// hit geometry -- do nothing for now since this doesn't mean we can't 
				// reach that location -- the only way to be sure is with a call to
				// PointReachable which is done below.
				// !!mdf-tbd: if really blocked (can't reach) try again with a shorted
				// distance so that NPC walks up to blocking geometry (within some
				// MinAvoidGeometry distance).
				// SelectedDistance = Hit.Time * VSize( Pawn.Location - DestinationLocation );
			}
			
			#debug DMAIM( "==> Extent trace Hit " $ HitActor $ "  SelectedDistance reduced to: " $ SelectedDistance $ " Hit.Time: " $ Hit.Time );
			//DMTNS( "==> Extent trace Hit " $ HitActor $ "  SelectedDistance reduced to: " $ SelectedDistance $ " Hit.Time: " $ Hit.Time );
		}
		
		//---------------------------------------------------------------------
		// Now do the reachability check using the possibly adjusted 
		// DesiredDistance.
		// NOTE: even if we hit geometry above, the NPC may be able to step
		// over it (in PHYS_Walking/Swimming/Flying) and PointReachable should
		// take this into account (as well as the simulated physics can handle
		// this...).
		//---------------------------------------------------------------------
		
		if( SelectedDistance >= U2PBase.WanderMinAdustedSize )
		{
			DestinationLocation = Pawn.Location + SelectedDistance*Direction;
			class'UtilGame'.static.AdjustDestinationForPhysics( Pawn, DestinationLocation );
	
			MaxJumpDownDistanceOld = Pawn.MaxJumpDownDistance;
			if( Pawn.Physics == PHYS_Walking )
			{
				// limit height that wandering NPCs can jump down
			
				Pawn.MaxJumpDownDistance = Pawn.MaxStepHeight + Pawn.CollisionHeight*2.0;
				//Pawn.MaxJumpDownDistance = Pawn.MaxStepHeight; // otherwise we risk not being able to get back from where we jumped down to?
			}
			
			// should do FitActorAt first since this can change the destination location?
			if( Pawn.FitActorAt( DestinationLocation ) != 0 )
			{
				//DMTNS( "pawn fits at destination" );
				
				if( PointReachable( DestinationLocation ) )
				{
					//DMTNS( "destination is reachable" );
					bResult = true;
				}
				else
				{
					//DMTNS( "destination is not reachable" );
					//AddArrow( Pawn.Location, DestinationLocation, ColorRed() ); 
					//AddActor( Pawn, ColorCyan() );
					//AddActorAt( Pawn, DestinationLocation, ColorRed() );
				}
			}
			else
			{
				//DMTNS( "pawn does not fit at destination" );
			}

			Pawn.MaxJumpDownDistance = MaxJumpDownDistanceOld;
		}
/*		
#debugbegin
		if( bResult )
		{
			#debug DMAIM( "    SUCCESS: " $ DestinationLocation );
			if( bRecovering )
				DrawColor = ColorBlue();
			else
				DrawColor = ColorGreen();
			
			AddArrow( Pawn.Location, DestinationLocation, DrawColor ); 
			//AddActorAt( Pawn, DestinationLocation, DrawColor );
		}
		else
		{
			#debug DMAIM( "    FAILED: obstructed by " $ HitActor );
			if( bRecovering )
				DrawColor = ColorMagenta();
			else
				DrawColor = ColorRed();
			AddArrow( Pawn.Location, DestinationLocation, DrawColor ); 
			
			if( bVisibleAI )
				AddActorAt( Pawn, DestinationLocation, DrawColor );
		}
#debugend
		//AddCylinder( Pawn.Location, 4, 4, ColorOrange() );
*/		
		return bResult;
	}

	//-------------------------------------------------------------------------
	// Note that WanderDirectionExternal is global. In most cases it is only 
	// set/used in the wandering state PickDestination code but it can be set 
	// externally in order to have one NPC move out of the way of another.
	//
	// mdf-tbd: swimming/flying creatures should tend to maintain the same
	// rotation compared to walking creatures? Make this tweakable and also add
	// a "home" location + MaxWanderDistance to possibly encourage NPCs to stay
	// in that area. Should PawnFactories have optional property name + value
	// pairs for stuff like this so that Pawns can be spawned with any properties
	// set as desired by flipping these in the Pawn/Controller?
	//
	// mdf-tbd: code for determining the distance moved is a bit icky currently
	// but this is a combination of the minimum distance plus some additional
	// distance which can vary from 0.0 up to GetExtraWanderDistance depending
	// on the value of WanderDistanceModifier (which is normally 1.0 but is
	// less if the NPC is hurt and/or alert so as to cause the NPC to reevaluate
	// his direction more frequently).

	function bool PickDestination()
	{
		local int ii;
		local bool bResult;
		local vector SelectedDirection;
		local float DesiredDistance;

		//DMTNS( "PickDestination!" );

		// sanity check -- should never happen with current NPCs
    	if( WanderDirectionExternal != vect(0,0,0) )
		{
			//#debug DMAIM( "Wandering -- using WanderDirectionExternal" );
			//DMTNS( "Wandering -- using WanderDirectionExternal" );
			SelectedDirection = Normal( WanderDirectionExternal );

			// don't zero out Z if not walking
			if( Pawn.Physics == PHYS_Walking )
				SelectedDirection.Z = 0;
			Destination = Pawn.Location + SelectedDirection; // mdf-tbd: code that sets WanderDirectionExternal should use appropriate distance?
			WanderDirectionExternal = vect(0,0,0);
			bResult = true; // assume direction is ok?
		}
		else
		{
			DesiredDistance = U2PBase.WanderDistMin + GetWanderDistanceModifier() * GetExtraWanderDistance() * FRand();
			SelectedDirection = GetWanderDirection( 0 );

			#debug DMAIM( "BEGIN calling GetDestinationVector" );
			//DMTNS( "BEGIN calling GetDestinationVector" );
			bResult = GetDestinationVector( SelectedDirection, DesiredDistance, false, Destination );
			#debug DMAIM( "END calling GetDestinationVector" );
			//DMTNS( "END calling GetDestinationVector" );

			for( ii=1; !bResult && ii<=MaxWanderFallbackTypes; ii++ )
			{
				// try to resolve the problem within the desired spread angle
				// !!mdf-tbd: spread this out over several ticks?
				SelectedDirection = GetWanderDirection( ii );
				#debug DMAIM( "BEGIN calling GetDestinationVector" );
				bResult = GetDestinationVector( SelectedDirection, DesiredDistance, true, Destination );
				#debug DMAIM( "END calling GetDestinationVector" );
			}
			
			if( !bResult && FDecision( U2PBase.WanderAvoidObstructionOdds ) )
			{
				// try alternate directions in order to resolve the problem
				// !!mdf-tbd: spread this out over several ticks?
				
				// dumber NPCs will probably just sleep for a while then try again, maybe
				// butting up against the wall for a while, smarter NPCs should turn away
				
				// go with min distance when trying to deal with an obstruction
				DesiredDistance = U2PBase.WanderDistMin;

				// try left/right instead of forward		
				SelectedDirection = Normal( vector(Pawn.Rotation) cross vect(0,0,1) );
				if( FRand() < 0.5 )
					SelectedDirection *= -1;

				// !!mdf-tbd: try N/NW/NE/W/E/SW/SE/S (8 directions instead of 4)?
				if( GetDestinationVector( SelectedDirection, DesiredDistance, true, Destination ) ) // try right/left
				{
					bResult = true;
				}
				else if( GetDestinationVector( -SelectedDirection, DesiredDistance, true, Destination ) ) // try left/right
				{
					bResult = true;
				}
				else if( Pawn.Physics != PHYS_Walking )
				{
					// for flying/swimming creatures also try up/down
	    			SelectedDirection = Normal( vector(Pawn.Rotation) cross SelectedDirection );
					if( FRand() < 0.5 )
						SelectedDirection *= -1;

					if( GetDestinationVector( SelectedDirection, DesiredDistance, true, Destination ) ) // try up/down
					{
						bResult = true;
					}
					else if( GetDestinationVector( -SelectedDirection, DesiredDistance, true, Destination ) ) // try down/up
					{
						bResult = true;
					}
				}
				if( !bResult && GetDestinationVector( -vector(Pawn.Rotation), DesiredDistance, true, Destination ) ) // try back
				{
					bResult = true;
				}
				if( !bResult && GetDestinationVector(  RotateAngleAxis( -vector(Pawn.Rotation), vect(0,0,1), 45*DegreesToRotationUnits ), DesiredDistance, true, Destination ) ) // back-right
				{
					bResult = true;
				}
				if( !bResult && GetDestinationVector(  RotateAngleAxis( -vector(Pawn.Rotation), vect(0,0,1), -45*DegreesToRotationUnits ), DesiredDistance, true, Destination ) ) // back-left
				{
					bResult = true;
				}
				if( !bResult && GetDestinationVector(  RotateAngleAxis( vector(Pawn.Rotation), vect(0,0,1), 45*DegreesToRotationUnits ), DesiredDistance, true, Destination ) ) // forward-right
				{
					bResult = true;
				}
				if( !bResult && GetDestinationVector(  RotateAngleAxis( vector(Pawn.Rotation), vect(0,0,1), -45*DegreesToRotationUnits ), DesiredDistance, true, Destination ) ) // forward-left
				{
					bResult = true;
				}
			}
	
			if( !bResult )
			{
				// if blocked by and walking stop moving so won't step onto Pawn
				StopMovement( true, Pawn.Physics == PHYS_Walking ); 
				Destination = Pawn.Location;
			}
		}

		WanderDirection = Normal( Destination - Pawn.Location );

	    // mdf-tbr:
		#debugbegin
		if( bVisibleAI )
			AddArrow( Pawn.Location, Destination, ColorYellow() );
		#debugend
		return bResult;
	}

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

	function bool CanKillIfStuck() 
	{ 
		// 2002.12.09 (mdf) let most NPCs destroy themselves if stuck wandering
		// and fix fish in tanks in M01D so they don't do this by setting
		// bWanderCanKillIfStuck=false.
		return U2PBase.bWanderCanKillIfStuck;
		/*OLD
		if( U2PBase.Physics == PHYS_Swimming || U2PBase.Physics == PHYS_Flying )
			return false;
		
		return U2PBase.bWanderCanKillIfStuck;
		*/
	}
	
	//-------------------------------------------------------------------------

	function bool CanTeleportIfStuck() 
	{ 
		// 2002.12.09 (mdf) let most NPCs teleport themselves if stuck wandering
		// and fix fish in tanks in M01D so they don't do this by setting
		// bWanderCanTeleportIfStuck=false.
		return U2PBase.bWanderCanTeleportIfStuck;
		
		/*OLD
		if( U2PBase.Physics == PHYS_Swimming || U2PBase.Physics == PHYS_Flying )
			return false;
			
		return U2PBase.bWanderCanTeleportIfStuck; 
		*/
	}
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		//DM( "Wandering -- begin state" );
		//!!mdf: if we are entering this state to deal with an enemy (e.g. spores) 
		// we don't want to clear enemy -- assume that caller won't use this state
		// with a valid enemy unless this is intentional (states that deal with 
		// enemies should handle cleaning up that enemy).
		// SetControllerEnemy( None, GetContext() );
		SetAlertness( 0.2 );
		MinHitWall += 0.15;
		if( Pawn != None )
		{
			Pawn.bCanTeleport = false;
			Pawn.bCanWalkOffLedges = U2PBase.bCanWanderOffLedges;
			Pawn.RotationRate = Pawn.default.RotationRate;
		}

		WanderDirection = vect(0,0,0);
		SetEvents();

		if( !U2PBase.bLookForAlertFriends )
			Disable( Event_SeeAlertFriend );
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		//DM( "Wandering -- end state" );
		RestoreAlertness();
		MinHitWall -= 0.15;
		if( Pawn != None )
		{
			Pawn.bCanTeleport = Pawn.default.bCanTeleport;
			Pawn.bCanWalkOffLedges = Pawn.default.bCanWalkOffLedges;
			if( U2PBase.bWanderEndRotation )
				Pawn.RotationRate = U2PBase.WanderEndRotationRate;
		}
	}

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

@ BeginLabel:
	//Sleep( 9999 );
@ MovePickDestLabel:
	WaitForLanding( 2.0 );	// NOTE: check every time through because NPCs could be falling after MoveToPoint
	if( Pawn.Physics == PHYS_Falling )   // seeing NPCs get stuck permanently falling against static meshes...
	{
		//DMTNS( "Gave up falling bWaterVolume: " $ Pawn.PhysicsVolume.bWaterVolume );
		if( Pawn.PhysicsVolume.bWaterVolume )
			Pawn.SetPhysics( PHYS_Swimming );
		else
			Pawn.SetPhysics( PHYS_Walking );
	}
	
	// ==> SELECT NEXT DESTINATION
	//#debug DMAIM( "Wandering -- selecting destination" );
	if( !PickDestination() )
	{
		// ==> FAILED (DUE TO OBSTRUCTION) -- wait and try again
		//#debug DMAIM( "cant move -- sleeping for " $ U2PBase.WanderCantMoveWaitTime $ " seconds" );
		//DMTNS( Pawn $ ": PickDestination failed  NumMoveAttempts: " $ NumMoveAttempts );
		StopMovement( true, true );
	
		// who cares if the player is looking -- the NPC is stuck and looks lame anyway...
	 	//if( TryToFixWandering() && NumMoveAttempts++ > MaxWanderAttempts && !Pawn.PlayerCanSeeMe() )
	 	bWanderFixed = false;
	 	NumMoveAttempts++;
	 	if( NumMoveAttempts > MaxWanderAttempts )
	 	{
			if( !U2P.bDisableErrorMessages )
				DMTNS( "  " $ Pawn $ " can't move at " $ Pawn.Location );
			 		
			if( !U2P.bDisableErrorColors )
			{
	 			AddActor( Pawn, ColorWhite() );
	 			AddArrow( vect(0,0,0), Pawn.Location, ColorWhite() );
	 			if( !CanTeleportIfStuck() && !CanKillIfStuck() )
		 			U2P.bDisableErrorColors = true; // only track the first problem (or slows down build horribly)
	 		}
	 		
	 		NumMoveRecoverAttempts++;
	 		if( NumMoveRecoverAttempts <= MaxMoveRecoverAttempts && CanTeleportIfStuck() )
	 		{
	 			if( !Pawn.PlayerCanSeeMe() )
	 			{
					// try to teleport to a nearby pathnode
					bWanderFixed = RecoverFromStuckError();
					if( bWanderFixed && !U2P.bDisableErrorColors )
					{
						AddCylinder( Pawn.Location, 4, 4, ColorWhite() );
			 			U2P.bDisableErrorColors = true; // only track the first problem (or slows down build horribly)
					}
				}
	 		}
			else if( CanKillIfStuck() )	 		
	 		{
				if( !U2P.bDisableErrorMessages )
					DMTNS( "  " $ Pawn $ " killing self" );
					
				//!!mdf-tbd: kill 'em off -- too much overhead					
				Pawn.Died( None, class'Suicided', Pawn.Location, vect(0,0,0) );
				bWanderFixed = true;
			}
		}
		
		if( !bWanderFixed )
		{
			//DMTNS( "  sleeping for " $ U2PBase.WanderCantMoveWaitTime $ " seconds" );
			Sleep( U2PBase.WanderCantMoveWaitTime );
		}
	}
	else
	{
		// ==> SUCCESS -- MAYBE ROTATE
		ClearMoveAttempts();
		
		if( FDecision( U2PBase.WanderTurnToDestinationOdds ) )
		{
			//#debug DMAIM( "turning to destination" );

			// NOTE (mdf): For most NPCs we will want to do this otherwise the
			// NPC will be rotating towards his destination as he moves toward
			// it. This might be ok for "hovering" creatures (small, mobile
			// fish or birds) but for most larger and/or walking NPCs, this
			// would probably look bad/wrong, especially if the NPC doesn't 
			// have anything but forward moving animations.
			Focus = None;
			FocalPoint = Destination;
			FinishRotation( DefaultRotationThreshold );
	
			// after call to FinishRotation, NPC can end up changing height slightly but
			// when walking the destination should always be at the same height as the pawn
			// (once I fix APawn::ReachedDestination to have more height diff tolerance for
			// non-actor destinations, this shouldn't make much difference.
			if( Pawn.Physics == PHYS_Walking )
				Destination.Z = Pawn.Location.Z;
		}
	
		// ==> MOVE TOWARD DESTINATION (!!mdf-tbd: doesn't currently necessarily reach destination -- do we care?)
		SetWanderMoveSpeed();
		//#debug DMAIM( "MoveToPoint BEGIN -- moving with speed: " $ WanderMoveSpeed );
		//#debug DMAIM( "Location.Z = " $ Pawn.Location.Z $ " Destination.Z = " $ Destination.Z );

		if( Pawn.Physics != PHYS_Walking )
		{
			// needed for fish & birds or they can fly way past their destination as the new acceleration is "blended" in
			StopMovement( true, false );
			Pawn.Velocity = VSize(Pawn.Velocity) * WanderDirection; 
		}

@ MoveActiveLabel:
		if( U2PBase.bWanderLookAtDestination )
			MoveToPoint( Destination, , , WanderMoveSpeed ); // will look at destination
		else
			MoveToPoint( Destination, , Pawn, WanderMoveSpeed );

		#debug DMAIM( "MoveToPoint END -- " $ MoveTarget $ " returned MoveResult: " $ EnumStr( enum'EMoveResult', MoveResult ) );
	
		// make sure we don't rotate 180 degrees to look at destination if we overshot it a bit
		if( MoveResult == MR_DestinationReached )
		{
			Focus = None;
			FocalPoint = Pawn.Location + 512*vector(Pawn.Rotation);
			//AddActor( Pawn, ColorCyan() );
		}
		else
		{
		 	if( NumMoveAttempts++ < MaxMoveToPointAttempts )
				Goto( MoveActiveLabel ); // failure is ok -- will just try another dest
		}
			
		// ==> MAYBE ROTATE AWAY FROM VIEW OBSTRUCTION
		if( FDecision( U2PBase.WanderViewBlockedTurnOdds ) && ViewObstructed( U2PBase.WanderViewBlockedDistance ) )
		{
			//#debug DMAIM( "Wandering -- rotating away from wall" );
			FinishRotation( DefaultRotationThreshold );
		}

		// ==> MAYBE PAUSE AFTER MOVE
		// optionally pause for a bit at each wander destination
		if( ShouldWanderPause() )
		{
			//#debug DMAIM( "pausing for " $ U2PBase.WanderPauseMin $ ".." $ U2PBase.WanderPauseMax $ " seconds" );
			StopMovement( true, false );
			WanderPauseSpecialHandling(); // hook so subclasses can play special pause animations (override animation controller)
			Sleep( RandRange( U2PBase.WanderPauseMin, U2PBase.WanderPauseMax ) );
			if( WanderPauseSpecialAnimation() ) // make sure special pause anim finishes
				FinishAnim();
		}
	}

	WanderDidMoveSpecialHandling(); // hook to maybe break away from wandering after last wander move/pause (e.g. bots go roaming here)
	Goto( MovePickDestLabel );
} // WanderingState

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

state @ WanderingPanicState extends @ WanderingState
{
	ignores BeginFalling, SeeEnemy, SeeFriend, SeeAlertFriend, SeeOther, NotifyBump, HearNoise, EnemyNotVisible; 
	ignores NotifyLanded, EnemyInLeapRange, EnemyInMeleeRange, NotifyHitWall;
	
	//-------------------------------------------------------------------------

	event Tick( float DeltaTime )
	{
		Super.Tick( DeltaTime );
		if( Level.TimeSeconds >= U2PBase.StopPanicTime )
			EndPanic();
	}
	
	//-------------------------------------------------------------------------

	function bool AllowHitSounds() { return false; }
	
	//!!mdf-tbd: would be cool to allow shooting while panicked if shot went out 
	// of weapon bone but as-is shots simply don't match up with the animation 
	// enough to allow them for now.
	function bool CanFire( bool bTest ) { return false; }
	function bool CanDodge( optional bool bIgnoreFalling ) { return false; }
	function HandlePanic();

	function bool CanKillIfStuck() { return false; }
	function bool CanTeleportIfStuck() { return false; }
	
	//-------------------------------------------------------------------------

	event BeginState()
	{
		if( Pawn != None )
		{
			Pawn.MeshAgentSetInputCurValue('Mood', 'Panic');
			Pawn.MeshAgentSetInputLock('Mood', true);
			Pawn.MeshAgentSetInputCurValue('Speed', 'Run');
			Pawn.MeshAgentSetInputLock('Speed', true);
		}
				
		//set panicked properties
		SetAlert( true );
		SaveWanderingParameters();
		SetWanderingPanicParameters();
		DoPanicSounds();
		
		Super.BeginState();
		
		Pawn.RotationRate = 2*Pawn.default.RotationRate;
	}
	
	//-------------------------------------------------------------------------

	event EndState()
	{
		Super.EndState();

		if( Pawn != None )
		{
			Pawn.MeshAgentSetInputLock('Mood', false);
			Pawn.MeshAgentSetInputCurValue('Mood', 'Normal');
			Pawn.MeshAgentSetInputLock('Speed', false);
			if( Pawn.Health > 0 )
				EndPanicSound(); // shhhhh, you're dead already
		}
				
		// undo panicked properties
		SetAlert( false );
		RestoreWanderingParameters();
		RemoveTimer( 'StartPanicSound' );
		DodgeEnableTime = Level.TimeSeconds + 0.50;
	}
} // WanderingPanicState

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

defaultproperties
{
	MaxWanderAttempts=8
	MaxWanderFallbackTypes=5
	TestTacticalMoveType=TMT_Serpentine
	DefaultState='Wandering'
	DefaultScriptControllerClass=Class'U2AI.ScriptControllerInterf'
	ScriptedScriptControllerClass=Class'U2AI.ScriptControllerBase'
	CrouchingMoveSpeedMultiplier=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.871 - Created with UnCodeX