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

UTGame.UTVehicle


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

/** value for Team property that indicates the vehicle's team hasn't been set */
const UTVEHICLE_UNSET_TEAM = 128;

/** If true the driver will have the flag attached to its model */
var bool bDriverHoldsFlag;

/** Determines if a driver/passenger in this vehicle can carry the flag */
var bool bCanCarryFlag;

/** Team defines which players are allowed to enter the vehicle */
var	bool bTeamLocked;

/** if true, can be healing target for link gun */
var bool bValidLinkTarget;

/** Sound played if tries to enter a locked vehicle */
var SoundCue VehicleLockedSound;

/** Vehicle is unlocked when a player enters it.. */
var	bool bEnteringUnlocks;

/** Vehicle has special entry radius rules */
var bool bHasCustomEntryRadius;

/** hint for AI and show this vehicle on minimap */
var	repnotify bool bKeyVehicle;

/** what kind of tasks the AI should use this vehicle for */
enum EAIVehiclePurpose
{
	/** use only for offense */
	AIP_Offensive,
	/** use only for defense */
	AIP_Defensive,
	/** suitable for anything */
	AIP_Any,
};
var EAIVehiclePurpose AIPurpose;
/** bots will not try to be a passenger in this vehicle while their objective is this
 * (used for key vehicles that we want to have one bot stay in if possible)
 */
var Actor NoPassengerObjective;
/** AI flag that indicates whether this vehicle is on a fixed track
 * (i.e, it can move, but don't expect it to be able to reach anything in particular)
 * this also causes it to use ReachSpecs with the track flag (created through UTTrackTurretPathNode)
 */
var bool bIsOnTrack;
/** AI flag - indicates this vehicle has a tow cable, so evaluate if it should link up to others by calling TryAttachingTowCable() */
var bool bHasTowCable;
/** whether AI should consider using its squad's alternate path to objectives while in this vehicle
 * (set false for vehicles where detours are painful and/or the vehicle is so strong the AI just shouldn't care)
 */
var bool bUseAlternatePaths;

/** If true, all passengers (inc. the driver) will be ejected if the vehicle flips over */
var	bool bEjectPassengersWhenFlipped;

/** true if vehicle must be upright to be entered */
var				bool		bMustBeUpright;

/** Whether can override AVRiL target locks */
var	bool	bOverrideAVRiLLocks;

/** Use stick deflection to determine throttle magnitude (used for console controllers) */
var	bool bStickDeflectionThrottle;

/** When using bStickDeflectionThrottle, how far along Y do you pull stick before you actually reverse. */
var float DeflectionReverseThresh;

/** Whether or not the vehicle can auto center its view pitch.  Some vehicles (e.g. darkwalker) do not want this **/
var bool bShouldAutoCenterViewPitch;

/** HUD should draw weapon bar for this vehicle */
var bool bHasWeaponBar;

/** PhysicalMaterial to use while driving */
var transient PhysicalMaterial DrivingPhysicalMaterial;

/** PhysicalMaterial to use while not driving */
var transient PhysicalMaterial DefaultPhysicalMaterial;

/** The variable can be used to restrict this vehicle from being reset. */
var bool bNeverReset;

/** If true, any dead bodies that get ejected when the vehicle is flipped/destroy will be destroyed immediately */
var	bool bEjectKilledBodies;

/** Used to designate this vehicle as having light armor */
var	bool bLightArmor;

/** whether or not bots should leave this vehicle if they encounter enemies */
var bool bShouldLeaveForCombat;

/** whether or not to draw this vehicle's health on the HUD in addition to the driver's health */
var bool bDrawHealthOnHUD;

/** whether or not driver pawn should always cast shadow */
var bool bDriverCastsShadow;

/** whether this vehicle has been driven at any time */
var bool bHasBeenDriven;

/** if set, drop detail when the local player is driving this vehicle (unless in super high detail mode) */
var bool bDropDetailWhenDriving;

/** Used natively to determine if the vehicle has been upside down */
var float LastCheckUpsideDownTime;

/** Used natively to give a little pause before kicking everyone out */
var	float FlippedCount;

/** The pawn's light environment */
var DynamicLightEnvironmentComponent LightEnvironment;

/** Holds the team designation for this vehicle */
var	repnotify byte Team;

/** Track different milestones (in terms of time) for this vehicle */
var float VehicleLostTime, PlayerStartTime;

/** How long vehicle takes to respawn */
var		float           RespawnTime;

/** How long to wait before spawning this vehicle when its factory becomes active */
var		float			InitialSpawnDelay;

/** If > 0, Link Gun secondary heals an amount equal to its damage times this */
var	float LinkHealMult;

var audiocomponent	LinkedToAudio;
var soundcue		LinkedToCue;
var soundcue		LinkedEndSound;

/** How many linkguns are linking to this vehicle */
var protected repnotify byte LinkedToCount;

/** The force feedback waveform to play when you get in/out of the vehicle */
var ForceFeedbackWaveform DriverStatusChangedWaveform;

/** hint for AI */
var float MaxDesireability;

/** if AI controlled and bot needs to trigger an objective not triggerable by vehicles, it will try to get out this far away */
var float ObjectiveGetOutDist;

/** The sounds to play when the horn is played */
var array<SoundCue>	HornSounds;
/** radius in which friendly bots respond to the horn by trying to get into any unoccupied seats */
var float HornAIRadius;
/** The time at which the horn was last played */
var float LastHornTime;
/** Horn to play for this vehicle. */
var int HornIndex;
/** The vechile index for this vehicle. */
var int VehicleIndex;

/** Set internally by physics - if the contact force is pressing along vehicle forward direction. */
var const bool	bFrontalCollision;

/** If bFrontalCollision is true, this indicates the collision is with a fixed object (ie not PHYS_RigidBody) */
var const bool	bFrontalCollisionWithFixed;

/*********************************************************************************************
 Look Steering
********************************************************************************************* */

/** If true, use 'look to steer' on 'Normal' vehicle control settings.  */
var(LookSteer) bool bLookSteerOnNormalControls;

/** If true, use 'look to steer' on 'Simple' vehicle control settings.  */
var(LookSteer) bool bLookSteerOnSimpleControls;

/** Cached value indicating what style of control we are currently using. */
var	transient bool bUsingLookSteer;

/** When using 'steer to left stick dir', this is a straight ahead dead zone which makes steering directly forwards easier. */
var(LookSteer) float LeftStickDirDeadZone;

/** When bLookToSteer is enabled, relates angle between 'looking' and 'facing' and steering angle. */
var(LookSteer) float LookSteerSensitivity;

var(LookSteer) float LookSteerDamping;

/** When error is more than this, turn on the handbrake. */
var(LookSteer) float LookSteerDeadZone;

/** Increases sensitivity of steering around middle region of controller. */
var(LookSteer) float ConsoleSteerScale;

/** Whether the driver is allowed to exit the vehicle */
var		bool				bAllowedExit;

/** Whether to make sure exit position is near solid ground */
var		bool				bFindGroundExit;

/*********************************************************************************************
 Missile Warnings
********************************************************************************************* */

/** Sound to play when something locks on */
var SoundCue LockedOnSound;

/** If true, certain weapons/vehicles can lock their weapons on to this vehicle */
var bool	bHomingTarget;

/*********************************************************************************************
 Vehicular Manslaughter / Hijacking
********************************************************************************************* */

/** The Damage type to use when something get's run over */
var class<UTDamageType> RanOverDamageType;

/** speed must be greater than this for running into someone to do damage */
var float MinRunOverSpeed;

/** Sound to play when someone is run over */
var SoundCue RanOverSound;

/** The Message index for the "Hijack" announcement */
var int StolenAnnouncementIndex;

/** SoundCue to play when someone steals this vehicle */
var SoundCue StolenSound;

/** last time checked for pawns in front of vehicle and warned them of their impending doom. */
var	float LastRunOverWarningTime;

/** last time checked for pawns in front of vehicle and warned them of their impending doom. */
var	float MinRunOverWarningAim;

/** Quick link to the next vehicle in the chain */
var	UTVehicle NextVehicle;

/** Quick link to the factory that spawned this vehicle */
var	UTVehicleFactory ParentFactory;

/** bot that's about to get in this vehicle */
var	UTBot Reservation;

/** if vehicle has no driver, CheckReset() will be called at this time */
var	float	ResetTime;

/** String that describes "In a vehicle name"*/
var localized string VehiclePositionString;

/** The human readable name of this vehicle */
var localized string VehicleNameString;

var ObjectiveAnnouncementInfo NeedToPickUpAnnouncement;

/*********************************************************************************************
 Team beacons
********************************************************************************************* */

/** The maximum distance out that the Team Beacon will be displayed */
var	float TeamBeaconMaxDist;

/** The maximum distance out that the player info will be displayed */
var float TeamBeaconPlayerInfoMaxDist;

/** Scaling factor used to determine if crosshair might be over this vehicle */
var float HUDExtent;

/** true if pressed use while holding flag for vehicle you can't enter with flag */
var bool bRequestedEntryWithFlag;

/*********************************************************************************************
 Water Damage
********************************************************************************************* */

/** How much damage the vehicle will take when submerged in the water */
var float WaterDamage;

/** Whether takes water damage while being driven */
var bool bTakeWaterDamageWhileDriving;

/** Accumulated water damage (only call take damage when > 1 */
var float AccumulatedWaterDamage;

/** Damage type it takes when submerged in the water */
var  class<DamageType> VehicleDrowningDamType;

/** Class of ExplosionLight */
var class<UTExplosionLight> ExplosionLightClass;

/** Max distance to create ExplosionLight */
var float	MaxExplosionLightDistance;

/*********************************************************************************************
 Turret controllers / Aim Variables
********************************************************************************************* */
/*
	Vehicles need to handle the replication of all variables required for the firing of a weapon.
	Each vehicle needs to have a set of variables that begin with a common prefix and will be used
	to line up the needed replicated data with that weapon.  The first weapon of the vehicle (ie: that
	which is associated with the driver/seat 0 has no prefix.

	<prefix>WeaponRotation 	- This defines the physical desired rotation of the weapon in the world.
	<prefix>FlashLocation	- This defines the hit location when an instant-hit weapon is fired
	<prefix>FlashCount		- This value is incremented after each shot
	<prefix>FiringMode		- This is assigned the firemode the weapon is currently functioning in

	Additionally, each seat can have any number of SkelControl_TurretConstrained controls associated with
	it.  When a <prefix>WeaponRotation value is set or replicated, those controls will automatically be
	updated.

	FlashLocation, FlashCount and FiringMode (associated with seat 0) are predefined in PAWN.UC.  WeaponRotation
	is defined below.  All "turret" variables must be defined "repnotify".  FlashLocation, FlashCount and FiringMode
	variables should only be replicated to non-owning clients.
*/

/** rotation for the vehicle's main weapon */
var repnotify rotator WeaponRotation;

/** info on locations for weapon bonus effects (UDamage, etc) */
struct native WeaponEffectInfo
{
	/** socket to base on */
	var name SocketName;
	/** offset from the socket to place the effect */
	var vector Offset;
	/** Scaling for the effect */
	var vector Scale3D;
	/** reference to the component */
	var StaticMeshComponent Effect;

	structdefaultproperties
	{
		Scale3D=(X=1.0,Y=1.0,Z=1.0)
	}
};

/**	The VehicleSeat struct defines each available seat in the vehicle. */
struct native VehicleSeat
{
	// ---[ Connections] ------------------------

	/** Who is sitting in this seat. */
	var() editinline  Pawn StoragePawn;

	/** Reference to the WeaponPawn if any */
	var() editinline  Vehicle SeatPawn;

	// ---[ Weapon ] ------------------------

	/** class of weapon for this seat */
	var() class<UTVehicleWeapon> GunClass;

	/** Reference to the gun */
	var() editinline  UTVehicleWeapon Gun;

	/** Name of the socket to use for effects/spawning */
	var() array<name> GunSocket;

	/** Where to pivot the weapon */
	var() array<name> GunPivotPoints;

	var	int BarrelIndex;

	/** This is the prefix for the various weapon vars (WeaponRotation, FlashCount, etc)  */
	var() string TurretVarPrefix;

	/** list of locations for weapon bonus effects (UDamage, etc) and the component references if those effects are active */
	var array<WeaponEffectInfo> WeaponEffects;

	/** Cached names for this turret */

	var name	WeaponRotationName;
	var name	FlashLocationName;
	var name	FlashCountName;
	var name	FiringModeName;

	/** Cache pointers to the actual UProperty that is needed */

	var const pointer	WeaponRotationProperty;
	var const pointer	FlashLocationProperty;
	var const pointer	FlashCountProperty;
	var const pointer	FiringModeProperty;

	/** Holds a duplicate of the WeaponRotation value.  It's used to determine if a turret is turning */

	var rotator LastWeaponRotation;

	/** This holds all associated TurretInfos for this seat */
	var() array<name> TurretControls;

	/** Hold the actual controllers */
	var() editinline array<UTSkelControl_TurretConstrained> TurretControllers;

	/** Cached in ApplyWeaponRotation, this is the vector in the world where the player is currently aiming */
	var vector AimPoint;

	/** Cached in ApplyWeaponRotation, this is the actor the seat is currently aiming at (can be none) */
	var actor AimTarget;

	/** Z distance between weapon pivot and actual firing location - used to correct aiming rotation. */
	var float PivotFireOffsetZ;

	/** Disable adjustment to turret pitch based on PivotFireOffsetZ. */
	var bool bDisableOffsetZAdjust;

	// ---[ Camera ] ----------------------------------

	/** Name of the Bone/Socket to base the camera on */
	var() name CameraTag;

	/** Optional offset to add to the cameratag location, to determine base camera */
	var() vector CameraBaseOffset;

	/** Optional offset to add to the vehicle location, to determine safe trace start point */
	var() vector CameraSafeOffset;

	/** how far camera is pulled back */
	var() float CameraOffset;

	/** The Eye Height for Weapon Pawns */
	var() float CameraEyeHeight;

	// ---[ View Limits ] ----------------------------------
	// - NOTE!! If ViewPitchMin/Max are set to 0.0f, the values associated with the host vehicle will be used

	/** Used for setting the ViewPitchMin on the Weapon pawn */
	var() float ViewPitchMin;

	/** Used for setting the ViewPitchMax on the Weapon pawn */
	var() float ViewPitchMax;

	// ---[  Pawn Visibility ] ----------------------------------

	/** Is this a visible Seat */
	var() bool bSeatVisible;

	/** Name of the Bone to use as an anchor for the pawn */
	var() name SeatBone;

	/** Offset from the origin to place the based pawn */
	var() vector SeatOffset;

	/** Any additional rotation needed when placing the based pawn */
	var() rotator SeatRotation;

	/** Name of the Socket to attach to */
	var() name SeatSocket;

	// ---[ Muzzle Flashes ] ----------------------------------
	var class<UTExplosionLight> MuzzleFlashLightClass;

	var	UTExplosionLight		MuzzleFlashLight;

	// ---[ Impact Flashes (for instant hit only) ] ----------------------------------
	var class<UTExplosionLight> ImpactFlashLightClass;

	// ---[ Misc ] ----------------------------------

	/** damage to the driver is multiplied by this value */
	var() float DriverDamageMult;

	// ---[ Sounds ] ----------------------------------

	/** The sound to play when this seat is in motion (ie: turning) */
	var AudioComponent SeatMotionAudio;

	var VehicleMovementEffect SeatMovementEffect;

	// ---[ HUD ] ----------------------------------

	var() vector2D SeatIconPOS;

};

/** information for each seat a player may occupy
 * @note: this array is on clients as well, but SeatPawn and Gun will only be valid for the client in that seat
 */
var(Seats)	array<VehicleSeat> 	Seats;

/** This replicated property holds a mask of which seats are occupied.  */
var int SeatMask;

/*********************************************************************************************
 Vehicle Effects
********************************************************************************************* */

/** Holds the needed data to create various effects that respond to different actions on the vehicle */
struct native VehicleEffect
{
	/** Tag used to trigger the effect */
	var() name EffectStartTag;

	/** Tag used to kill the effect */
	var() name EffectEndTag;

	/** If true should restart running effects, if false will just keep running */
	var() bool bRestartRunning;

	var() bool bHighDetailOnly;

	/** Template to use */
	var() ParticleSystem EffectTemplate;

	/** Template to use for the blue team (may or may not be one)*/
	var() ParticleSystem EffectTemplate_Blue;

	/** Socket to attach to */
	var() name EffectSocket;

	/** The Actual PSC */
	var ParticleSystemComponent EffectRef;

	structdefaultproperties
	{
		bRestartRunning=true;
	}
};

/** Holds the Vehicle Effects data */
var(Effects) array<VehicleEffect>	VehicleEffects;

/** set after attaching vehicle effects, as this is delayed slightly to allow time for team info to be set */
var bool bInitializedVehicleEffects;

/**
 * This is a reference to the Emitter we spawn on death.  We need to keep a ref to it (briefly) so we can
 * turn off the particle system when the vehicle decided to burnout.
 **/
var Emitter DeathExplosion;

/**
 * How long to wait after the InitialVehicleExplosion before doing the Secondary VehicleExplosion (if it already has not happened)
 * (e.g. due to the vehicle falling from the air and hitting the ground and doing it's secondary explosion that way).
 **/
var float TimeTilSecondaryVehicleExplosion;

struct native VehicleAnim
{
	/** Used to look up the animation */
	var() name AnimTag;

	/** Animation Sequence sets to play */
	var() array<name> AnimSeqs;

	/** Rate to play it at */
	var() float AnimRate;

	/** Does it loop */
	var() bool bAnimLoopLastSeq;

	/**  The name of the UTAnimNodeSequence to use */
	var() name AnimPlayerName;
};

/** Holds a list of vehicle animations */
var(Effects) array<VehicleAnim>	VehicleAnims;

struct native VehicleSound
{
	var() name SoundStartTag;
	var() name SoundEndTag;
	var() SoundCue SoundTemplate;
	var AudioComponent SoundRef;
};

var(Effects) array<VehicleSound> VehicleSounds;
/*********************************************************************************************
 Damage Morphing
********************************************************************************************* */

struct native FDamageMorphTargets
{
	/** These are used to reference the MorphNode that is represented by this struct */
	var	name MorphNodeName;

	/** Link to the actual node */
	var	MorphNodeWeight	MorphNode;

	/** These are used to reference the next node if this is at 0 health.  It can be none */
	var name LinkedMorphNodeName;

	/** Actual Node pointed to by LinkMorphNodeName*/
	var	int LinkedMorphNodeIndex;

	/** This holds the bone that influences this node */
	var Name InfluenceBone;

	/** This is the current health of the node.  If it reaches 0, then we should pass damage to the linked node */
	var	int Health;

	/** Holds the name of the Damage Material Scalar property to adjust when it takes damage */
	var array<name> DamagePropNames;

	structdefaultproperties
	{
		Health=1.0f;
	}
};

struct native DamageParamScales
{
	var name DamageParamName;
	var float Scale;
};

var array<DamageParamScales> DamageParamScaleLevels;


/** Holds the Damage Morph Targets */
var	array<FDamageMorphTargets> DamageMorphTargets;

/** Holds the damage skel controls */
var array<UTSkelControl_Damage> DamageSkelControls;

/** client-side health for morph targets. Used to adjust everything to the replicated Health whenever we receive it */
var int ClientHealth;

/* This allows access to the Damage Material parameters */
var MaterialInstanceConstant	DamageMaterialInstance[2];

/** The Team Skins (0 = red/unknown, 1 = blue)*/
var array<MaterialInterface> TeamMaterials;

/** class to spawn for blown off vehicle pieces */
var class<UTGib_Vehicle> VehiclePieceClass;

/*********************************************************************************************
 Smoke and Fire
********************************************************************************************* */

/** The health ratio threshold at which the vehicle will begin smoking */
var float DamageSmokeThreshold;

/** The health ratio threshold at which the vehicle will catch on fire (and begin to take continuous damage if empty) */
var float FireDamageThreshold;

/** Damage per second if vehicle is on fire */
var float FireDamagePerSec;

/** Damage per second if vehicle is upside down*/
var float UpsideDownDamagePerSec;

/** Damage per second if vehicle is upside down with a driver */
var float OccupiedUpsideDownDamagePerSec;

/** Accrued Fire Damage */
var float AccruedFireDamage;

/** If true, driver is thrown from vehicle as ragdoll by darkwalker horn. */
var() bool bRagdollDriverOnDarkwalkerHorn;

/*********************************************************************************************
 Misc
********************************************************************************************* */

/** The Damage Type of the explosion when the vehicle is upside down */
var class<DamageType> ExplosionDamageType;

/** Is this vehicle dead */
var repnotify bool bDeadVehicle;
/** player that killed the vehicle (replicated, but only to that player) */
var Controller KillerController;

/** The maximum distance out where an impact effect will be spawned */
var float MaxImpactEffectDistance;

/** The maximum distance out where a fire effect will be spawned */
var float MaxFireEffectDistance;

/** Natively used in determining when a bot should just out of the vehicle */
var float LastJumpOutCheck;

/** Templates used for explosions */
var ParticleSystem ExplosionTemplate;
var array<DistanceBasedParticleTemplate> BigExplosionTemplates;
/** Secondary explosions from vehicles.  (usually just dust when they are impacting something) **/
var ParticleSystem SecondaryExplosion;

/** socket to attach big explosion to (if 'None' it won't be attached at all) */
var name BigExplosionSocket;

/** Max dist for wheel sounds and particle effects */
var float MaxWheelEffectDistSq;

/** Water effect type name */
var name WaterEffectType;

struct native BurnOutDatum
{
	var MaterialInstanceTimeVarying MITV;

	/**
	 * We need to store the value of the MIC set param on a per material basis as we have some MICs where are
	 * vastly different than the others.
	 **/
	var float CurrValue;

};

/** The material instances and their data used when showing the burning hulk */
var array<BurnOutDatum> BurnOutMaterialInstances;

/** How long does it take to burn out */
var float BurnOutTime;

/** How long should the vehicle should last after being destroyed */
var float DeadVehicleLifeSpan;

/** How many times burnout has been delayed */
var int DelayedBurnoutCount;

/** Damage/Radius/Momentum parameters for dying explosions */
var float ExplosionDamage, ExplosionRadius, ExplosionMomentum;
/** If vehicle dies in the air, this is how much spin is given to it. */
var float ExplosionInAirAngVel;
/** camera shake for players near the vehicle when it explodes */
var CameraAnim DeathExplosionShake;
/** radius at which the death camera shake is full intensity */
var float InnerExplosionShakeRadius;
/** radius at which the death camera shake reaches zero intensity */
var float OuterExplosionShakeRadius;

/** Whether or not there is a turret explosion sequence on death */
var bool bHasTurretExplosion;
/** Name of the turret skel control to scale the turret to nothing*/
var name TurretScaleControlName;
/** Name of the socket location to spawn the explosion effect for the turret blowing up*/
var name TurretSocketName;
/** Explosion of the turret*/
var array<DistanceBasedParticleTemplate> DistanceTurretExplosionTemplates;

/** The offset from the TurretSocketName to spawn the turret*/
var vector TurretOffset;
/** Reference to destroyed turret for death effects */
var UTVehicleDeathPiece DestroyedTurret;
/** Class to spawn when turret destroyed */
var StaticMesh DestroyedTurretTemplate;
/** Force applied to the turret explosion */
var float TurretExplosiveForce;

/** sound for dying explosion */
var SoundCue ExplosionSound;
/** Sound for being hit by impact hammer*/
var SoundCue ImpactHitSound;
/** stores the time of the last death impact to stop spamming them from occurring*/
var float LastDeathImpactTime;

/** The sounds this vehicle will play based on impact force */
var SoundCue LargeChunkImpactSound, MediumChunkImpactSound, SmallChunkImpactSound;

/** How long until it's done burning */
var float RemainingBurn;

/** This vehicle is dead and burning */
var bool bIsBurning;

/** names of material parameters for burnout material effect */
var name BurnTimeParameterName;

/** If true, this vehicle is scraping against something */
var bool bIsScraping;

/** Sound to play when the vehicle is scraping against something */
var(Sounds) AudioComponent ScrapeSound;

/** Sound to play from the tires */
var(Sounds) editconst const AudioComponent TireAudioComp;
var(Sounds) array<MaterialSoundEffect> TireSoundList;
var name CurrentTireMaterial;

/** This is used to determine a safe zone around the spawn point of the vehicle.  It won't spawn until this zone is clear of pawns */
var float	SpawnRadius;

/** Anim to play when a visible driver is driving */
var	name	DrivingAnim;

/** Sound to play when spawning in */
var SoundCue SpawnInSound;

/** Sound to play when despawning */
var SoundCue SpawnOutSound;

/** Sound to play when going over a boost pad. */
var SoundCue BoostPadSound;

/*********************************************************************************************
 Flag carrying
********************************************************************************************* */
var(Flag) vector	FlagOffset;
var(Flag) rotator	FlagRotation;
var(Flag) name		FlagBone;

/*********************************************************************************************
 HUD Beacon
********************************************************************************************* */

var vector HUDLocation;
var float MapSize;

/** Coordiates of the icon associated with this object */
var TextureCoordinates IconCoords;
var TextureCoordinates FlipToolTipIconCoords;
var TextureCoordinates EnterToolTipIconCoords;
var TextureCoordinates DropFlagIconCoords;
var TextureCoordinates DropOrbIconCoords;

var TextureCoordinates ChargeBarCoords;			//the charge bar as a whole
var TextureCoordinates ChargeBarEndCapCoords;	//the charge bar top endcap
var float ChargeBarPosX;	 //offset relative to the upper left of the vehicle hud bar
var float ChargeBarPosY;
var float ChargeBarWidth;
var float ChargeBarHeight;

/** Last time trace test check for drawing postrender hud icons was performed */
var float LastPostRenderTraceTime;

/** true is last trace test check for drawing postrender hud icons succeeded */
var bool bPostRenderTraceSucceeded;

var bool bShowLocked;

var float ShowLockedMaxDist;

var int LastHealth;
var float HealthPulseTime;

/** offset for team beacon */
var vector TeamBeaconOffset;

/** PRI of player in passenger turret */
var UTPlayerReplicationInfo PassengerPRI;

/** offset for passenger team beacon */
var vector PassengerTeamBeaconOffset;

/** Team specific effect played when the vehicle is spawned */
var array<ParticleSystem> SpawnInTemplates;
/** team specific materials to apply when spawning in */
struct native MaterialList
{
	var array<MaterialInterface> Materials;
};
var array<MaterialList> SpawnMaterialLists;
/** parameter for the spawn material */
var name SpawnMaterialParameterName;
var InterpCurveFloat SpawnMaterialParameterCurve;
/** list of Mesh's original materials when playing spawn effect so we can restore them afterwards */
var array<MaterialInterface> OriginalMaterials;
/** How long is the SpawnIn effect */
var float SpawnInTime;
/** whether we're currently playing the spawn effect */
var repnotify bool bPlayingSpawnEffect;

/** Burn out material (per team) */
var MaterialInterface BurnOutMaterial[2];

/** multiplier to damage from colliding with other rigid bodies */
var float CollisionDamageMult;

/** last time we took collision damage, so we don't take collision damage multiple times in the same tick */
var float LastCollisionDamageTime;

/** if true, collision damage is reduced when the vehicle collided with something below it */
var bool bReducedFallingCollisionDamage;

/*********************************************************************************************
 Penetration destruction
********************************************************************************************* */

/** If a physics penetration of greater than this is detected, destroy vehicle. */
var() float DestroyOnPenetrationThreshold;

/** If we are over DestroyOnPenetrationThreshold for more than this (seconds), call RBPenetrationDestroy. */
var() float DestroyOnPenetrationDuration;

/** TRUE indicates vehicle is currently in penetration greater than DestroyOnPenetrationThreshold. */
var bool bIsInDestroyablePenetration;

/** How long the vehicle has been in penetration greater than DestroyOnPenetrationThreshold. */
var float TimeInDestroyablePenetration;

/*********************************************************************************************
 Camera
********************************************************************************************* */

var(Seats)	float	SeatCameraScale;

/** If true, this will allow the camera to rotate under the vehicle which may obscure the view */
var(Camera)	bool bRotateCameraUnderVehicle;

/** If true, don't Z smooth lagged camera (for bumpier looking ride */
var bool bNoZSmoothing;

/** If true, make sure camera z stays above vehicle when looking up (to avoid clipping when flying vehicle going up) */
var bool bLimitCameraZLookingUp;

/** If true, don't change Z while jumping, for more dramatic looking jumps */
var bool bNoFollowJumpZ;

/** Used only if bNoFollowJumpZ=true.  True when Camera Z is being fixed. */
var bool bFixedCamZ;

/** Used only if bNoFollowJumpZ=true.  saves the Camera Z position from the previous tick. */
var float OldCamPosZ;

/** Smoothing scale for lagged camera - higher values = shorter smoothing time. */
var float CameraSmoothingFactor;

/** FOV to use when driving this vehicle */
var float DefaultFOV;

/** Saved Camera positions (for lagging camera) */
struct native TimePosition
{
	var vector Position;
	var float Time;
};
var array<TimePosition> OldPositions;

/** Amount of camera lag for this vehicle (in seconds */
var float CameraLag;

/** Smoothed Camera Offset */
var vector CameraOffset;

/** How far forward to bring camera if looking over nose of vehicle */
var(Camera) float LookForwardDist;

/** hide vehicle if camera is too close */
var	float	MinCameraDistSq;

var bool bCameraNeverHidesVehicle;

/** Stop death camera using OldCameraPosition if true */
var bool bStopDeathCamera;

/** OldCameraPosition saved when dead for use if fall below killz */
var vector OldCameraPosition;

/** for player controlled !bSeparateTurretFocus vehicles on console, this is updated to indicate whether the controller is currently turning
 * (server and owning client only)
 */
var bool bIsConsoleTurning;

/** Whether to accept jump from UTWeaponPawns */
var bool bAcceptTurretJump;

/*********************************************************************************************/

var array<UTBot> Trackers;

var bool bShowDamageDebug;

/** This vehicle should display the <Locked> cusrsor */
var bool bStealthVehicle;

/** replicated information on a hit we've taken */
var UTPawn.TakeHitInfo LastTakeHitInfo;

/** stop considering LastTakeHitInfo for replication when world time passes this (so we don't replicate out-of-date hits when pawns become relevant) */
var float LastTakeHitTimeout;

// when hit with EMP, a Vehicle is Disabled.
var repnotify bool bIsDisabled;

// how long it takes to restart this vehicle when disabled.
var() float DisabledTime;

// The time at which the last EMP grenade hit this vehicle.
var float TimeLastDisabled;

/** effect played when disabled */
var ParticleSystem DisabledTemplate;
/** component that holds the disabled effect (created dynamically) */
var ParticleSystemComponent DisabledEffectComponent;

/*********************************************************************************************/

var array<name> HoverBoardAttachSockets;

var array<bool>	HoverBoardSocketInUse;

/** if true, currently towing hoverboard */
var bool bIsTowingHoverboard;

/** If true, you can grapple to this vehicle from any direction - not just from behind it. */
var bool bAllowTowFromAllDirections;

/** If true, don't damp z component of vehicle velocity while it is in the air */
var bool bNoZDampingInAir;

/** If true, don't damp z component of vehicle velocity even when on the ground */
var bool bNoZDamping;

/** material specific wheel effects, applied to all attached UTVehicleWheels with bUseMaterialSpecificEffects set to true */
var array<MaterialParticleEffect> WheelParticleEffects;

/** Reference Mesh for the movement effect on seats*/
var StaticMesh ReferenceMovementMesh;

/** additional downward threshold for AI reach tests (for high hover vehicles) */
var float ExtraReachDownThreshold;

/** bot voice message support */
var bool bHasEnemyVehicleSound;
var float LastEnemyWarningTime;
var array<SoundNodeWave> EnemyVehicleSound;
var array<SoundNodeWave> VehicleDestroyedSound;

/** True if is Necris vehicle (used by single player campaign) */
var bool bIsNecrisVehicle;

/** true if being spectated (set temporarily in UTPlayerController.GetPlayerViewPoint() */
var bool bSpectatedView;

/** bonus given for killing this vehicle (if driven by enemy) */
var float HeroBonus;

/** Coin bonus given for killing this vehicle (if driven by enemy) */
var int GreedCoinBonus;

/** if true, show health bar for this vehicle */
var bool bDisplayHealthBar;

/** If true, call postrenderfor() even if on different team */
var bool bPostRenderOtherTeam;

replication
{
	if (bNetDirty && (!bNetOwner || bDemoRecording))
		WeaponRotation;
	if (bNetDirty)
		bTeamLocked, Team, bDeadVehicle, bPlayingSpawnEffect, bIsDisabled, SeatMask, PassengerPRI, LinkedToCount, bKeyVehicle;

	if (bNetDirty && WorldInfo.TimeSeconds < LastTakeHitTimeout)
		LastTakeHitInfo;

	if (bNetDirty && WorldInfo.ReplicationViewers.Find('InViewer', PlayerController(KillerController)) != INDEX_NONE)
		KillerController;
	if ( bNetDirty && bNetOwner )
		bIsTowingHoverboard;
}

// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)
// (cpptext)

/*********************************************************************************************
  Native Accessors for the WeaponRotation, FlashLocation, FlashCount and FiringMode
********************************************************************************************* */
native simulated function rotator 	SeatWeaponRotation	(int SeatIndex, optional rotator NewRot,	optional bool bReadValue);
native simulated function vector  	SeatFlashLocation	(int SeatIndex, optional vector  NewLoc,	optional bool bReadValue);
native simulated function byte		SeatFlashCount		(int SeatIndex, optional byte NewCount, 	optional bool bReadValue);
native simulated function byte		SeatFiringMode		(int SeatIndex, optional byte NewFireMode,	optional bool bReadValue);

native simulated function ForceWeaponRotation(int SeatIndex, Rotator NewRotation);
native simulated function vector GetSeatPivotPoint(int SeatIndex);
native simulated function int GetBarrelIndex(int SeatIndex);

/** @return whether we are currently replicating to the Controller of the given seat
 * this would be equivalent to checking bNetOwner on that seat,
 * but bNetOwner is only valid during that Actor's replication, not during the base vehicle's
 * not complex logic, but since it's for use in vehicle replication statements, the faster the better
 */
native(999) noexport final function bool IsSeatControllerReplicationViewer(int SeatIndex);

native function VehicleHudCoordsFixup();

/**
 * Hack the max radius to be updated values
 */
native function SetMaxRadius(SoundNodeAttenuation Node);

/**
 * Initialization
 */
simulated function PostBeginPlay()
{
	local PlayerController PC;

	super.PostBeginPlay();

	ClientHealth = Health;
	LastHealth = Health;

	if (Role==ROLE_Authority)
	{
		if ( !bDeleteMe && UTGame(WorldInfo.Game) != None )
		{
			UTGame(WorldInfo.Game).RegisterVehicle(self);
		}

		// Setup the Seats array
		InitializeSeats();
	}
	else if (Seats.length > 0)
	{
		// Insure our reference to self is always setup
		Seats[0].SeatPawn = self;
	}

	PreCacheSeatNames();

	// Pre-size array for tracking sockets in use.
	HoverBoardSocketInUse.length = HoverBoardAttachSockets.length;

	InitializeTurrets();		// Setup the turrets
	SetTimer(0.01, false, 'InitializeEffects');		// Setup any effects for this vehicle
	InitializeMorphs();			// Setup the damage morph targets

	// add to local HUD's post-rendered list
	ForEach LocalPlayerControllers(class'PlayerController', PC)
	{
		if ( UTHUD(PC.MyHUD) != None )
		{
			UTHUD(PC.MyHUD).AddPostRenderedActor(self);
		}
	}
	if ( bKeyVehicle )
		UTMapInfo(WorldInfo.GetMapInfo()).AddKeyVehicle(self);

	if (WorldInfo.NetMode != NM_DedicatedServer)
	{
		UpdateShadowSettings(!class'Engine'.static.IsSplitScreen() && class'UTPlayerController'.Default.PawnShadowMode == SHADOW_All);
		CreateDamageMaterialInstance();
	}

	VehicleEvent('Created');

	CheckGameClass();

	VehicleHudCoordsFixup();
}

/** customize based on gameclass
  */
simulated function CheckGameClass()
{
	if ( WorldInfo.GRI.GameClass == None )
	{
		// check again later for valid gameclass
		SetTimer(3.0+2.0*FRand(), false, 'CheckGameClass');
	}
	else if ( (class<UTGame>(WorldInfo.GRI.GameClass) != None) && class<UTGame>(WorldInfo.GRI.GameClass).Default.bShouldPostRenderEnemyPawns )
	{
		bPostRenderOtherTeam = true;
		if ( !class<UTGame>(WorldInfo.GRI.GameClass).Default.bTeamGame )
		{
			TeamBeaconMaxDist = class<UTGame>(WorldInfo.GRI.GameClass).Default.DMBeaconMaxDist;
		}
	}
}

simulated function UpdateShadowSettings(bool bWantShadow)
{
	local bool bNewCastShadow, bNewCastDynamicShadow;

	if (Mesh != None)
	{
		bNewCastShadow = default.Mesh.CastShadow && bWantShadow;
		bNewCastDynamicShadow = default.Mesh.bCastDynamicShadow && bWantShadow;
		if (bNewCastShadow != Mesh.CastShadow || bNewCastDynamicShadow != Mesh.bCastDynamicShadow)
		{
			Mesh.CastShadow = bNewCastShadow;
			Mesh.bCastDynamicShadow = bNewCastDynamicShadow;
			// defer if we can do so without it being noticeable
			if (LastRenderTime < WorldInfo.TimeSeconds - 1.0)
			{
				SetTimer(0.1 + FRand() * 0.5, false, 'ReattachMesh');
			}
			else
			{
				ReattachMesh();
			}
		}
	}
}

/** reattaches the mesh component, because settings were updated */
simulated function ReattachMesh()
{
	DetachComponent(Mesh);
	AttachComponent(Mesh);
}

simulated function CreateDamageMaterialInstance()
{
	DamageMaterialInstance[0] = Mesh.CreateAndSetMaterialInstanceConstant(0);
}

simulated function UpdateLookSteerStatus()
{
	local UTPlayerController UTPC;

	UTPC = UTPlayerController(Controller);
	// If no player, or not a human player
	if( UTPC == None ||
		UTPC.VehicleControlType == UTVC_Advanced ||
		(UTPC.VehicleControlType == UTVC_Normal && !bLookSteerOnNormalControls) ||
		(UTPC.VehicleControlType == UTVC_Simple && !bLookSteerOnSimpleControls) )
	{
		bUsingLookSteer = FALSE;
	}
	else
	{
		bUsingLookSteer = TRUE;
	}
}

/**
 * Console specific input modification
 */
simulated function SetInputs(float InForward, float InStrafe, float InUp)
{
	local bool bReverseThrottle;
	local UTConsolePlayerController ConsolePC;
	local rotator SteerRot, VehicleRot;
	local vector SteerDir, VehicleDir, AngVel;
	local float VehicleHeading, SteerHeading, DeltaTargetHeading, Deflection;

	Throttle = InForward;
	Steering = InStrafe;
	Rise = InUp;

	ConsolePC = UTConsolePlayerController(Controller);
	if (ConsolePC != None)
	{
		Steering = FClamp(Steering * ConsoleSteerScale, -1.0, 1.0);

		UpdateLookSteerStatus();

		// tank, wheeled / heavy vehicles will use this

		// If we desire 'look steering' on this vehicle, do it here.
		if (bUsingLookSteer && IsHumanControlled())
		{
			// If there is a deflection, look at the angle that its point in.
			Deflection = Sqrt(Throttle*Throttle + Steering*Steering);

			if(bStickDeflectionThrottle)
			{
				// The region we consider 'reverse' is anything below DeflectionReverseThresh, or anything withing the triangle below the center position.
				bReverseThrottle = ((Throttle < DeflectionReverseThresh) || (Throttle < 0.0 && Abs(Steering) < -Throttle));
				Throttle = Deflection;

				if (bReverseThrottle)
				{
					Throttle *= -1;
				}
			}

			VehicleRot.Yaw = Rotation.Yaw;
			VehicleDir = vector(VehicleRot);

			SteerRot.Yaw = DriverViewYaw;
			SteerDir = vector(SteerRot);

			VehicleHeading = GetHeadingAngle(VehicleDir);
			SteerHeading = GetHeadingAngle(SteerDir);
			DeltaTargetHeading = FindDeltaAngle(SteerHeading, VehicleHeading);

			if (DeltaTargetHeading > LookSteerDeadZone)
			{
				Steering = FMin((DeltaTargetHeading - LookSteerDeadZone) * LookSteerSensitivity, 1.0);
			}
			else if (DeltaTargetHeading < -LookSteerDeadZone)
			{
				Steering = FMax((DeltaTargetHeading + LookSteerDeadZone) * LookSteerSensitivity, -1.0);
			}
			else
			{
				Steering = 0.0;
			}

			AngVel = Mesh.BodyInstance.GetUnrealWorldAngularVelocity();

			Steering = FClamp(Steering + (AngVel.Z * LookSteerDamping), -1.0, 1.0);

			// Reverse steering when reversing
			if (Throttle < 0.0 && ForwardVel < 0.0)
			{
				Steering = -1.0 * Steering;
			}
		}
		// flying hovering vehicles will use this
		else
		{
			//`log( " flying hovering vehicle" );
			if (bStickDeflectionThrottle)
			{
				// The region we consider 'reverse' is anything below DeflectionReverseThresh, or anything withing the triangle below the center position.
				bReverseThrottle = ((Throttle < DeflectionReverseThresh) || (Throttle < 0.0 && Abs(Steering) < -Throttle));

				Deflection = Sqrt(Throttle*Throttle + Steering*Steering);
				Throttle = Deflection;

				if (bReverseThrottle)
				{
					Throttle *= -1;
				}
			}
		}

		//`log( "Throttle: " $ Throttle $ " Steering: " $ Steering );
	}
}

simulated event FellOutOfWorld(class<DamageType> dmgType)
{
    super.FellOutOfWorld(DmgType);
    bStopDeathCamera = true;
}

simulated function float GetChargePower();

simulated function PlaySpawnEffect()
{
	local MaterialInstanceTimeVarying SpawnMaterialInstance;
	local int i;

	if (!IsTimerActive('StopSpawnEffect')) //@note: don't check bPlayingSpawnEffect here because that's already true on the client
	{
		bPlayingSpawnEffect = true;
		if (WorldInfo.NetMode != NM_DedicatedServer)
		{
			// spawn emitter
			if (Team < SpawnInTemplates.length)
			{
				WorldInfo.MyEmitterPool.SpawnEmitter(SpawnInTemplates[Team], Location, Rotation);
			}
			else if (SpawnInTemplates.length > 0)
			{
				WorldInfo.MyEmitterPool.SpawnEmitter(SpawnInTemplates[0], Location, Rotation);
			}
			// set spawn materials
			if (Team < SpawnMaterialLists.length)
			{
				for (i = 0; i < Mesh.GetNumElements() && i < SpawnMaterialLists[Team].Materials.length; i++)
				{
					OriginalMaterials[i] = Mesh.GetMaterial(i);
					SpawnMaterialInstance = new(self) class'MaterialInstanceTimeVarying';
					SpawnMaterialInstance.SetParent(SpawnMaterialLists[Team].Materials[i]);
					SpawnMaterialInstance.SetScalarCurveParameterValue(SpawnMaterialParameterName, SpawnMaterialParameterCurve);
					Mesh.SetMaterial(i, SpawnMaterialInstance);
					SpawnMaterialInstance.SetScalarStartTime(SpawnMaterialParameterName, 0.0);
					//`log( "SpawnMaterialInstance: " $ SpawnMaterialInstance $ " P: " $ SpawnMaterialLists[Team].Materials[i] $ " PP: " $ MaterialInstance(SpawnMaterialLists[Team].Materials[i]).Parent );
				}
			}

			if (SpawnInSound != None)
			{
				PlaySound(SpawnInSound, true);
			}
		}
		SetTimer(SpawnInTime, false, 'StopSpawnEffect');
	}
}

simulated function StopSpawnEffect()
{
	local int i;

	bPlayingSpawnEffect = false;
	for (i = 0; i < OriginalMaterials.length; i++)
	{
		Mesh.SetMaterial(i, OriginalMaterials[i]);
	}
	ClearTimer('StopSpawnEffect');
}

event SelfDestruct(Actor ImpactedActor);

function EjectSeat(int SeatIdx)
{
	local UTVehicleBase VB;
	bShouldEject=true;
	if(SeatIdx == 0)
	{
		DriverLeave(true);
	}
	else
	{
		VB = UTVehicleBase(Seats[SeatIdx].SeatPawn);
		if(VB != none)
		{
			VB.bShouldEject = true;
			VB.DriverLeave(true);
		}
	}
}

event DisplayWeaponBar(Canvas canvas, UTHUD HUD);

/**
 * function used to update where icon for this actor should be rendered on the HUD
 *  @param 	NewHUDLocation 		is a vector whose X and Y components are the X and Y components of this actor's icon's 2D position on the HUD
 */
simulated native function SetHUDLocation(vector NewHUDLocation);


simulated static function DrawKillIcon(Canvas Canvas, float ScreenX, float ScreenY, float HUDScaleX, float HUDScaleY)
{
	local color CanvasColor;

	LogInternal("### DrawKillIcon");

	// save current canvas color
	CanvasColor = Canvas.DrawColor;

	// draw vehicle shadow
	Canvas.DrawColor = class'UTHUD'.default.BlackColor;
	Canvas.DrawColor.A = CanvasColor.A;
	Canvas.SetPos( ScreenX - 2, ScreenY - 2 );
	Canvas.DrawTile(class'UTHUD'.default.IconHudTexture, 4 + HUDScaleX * 96, 4 + HUDScaleY * 64, default.IconCoords.U, default.IconCoords.V, default.IconCoords.UL, default.IconCoords.VL);

	// draw the vehicle icon
	Canvas.DrawColor =  class'UTHUD'.default.WhiteColor;
	Canvas.DrawColor.A = CanvasColor.A;
	Canvas.SetPos( ScreenX, ScreenY );
   	Canvas.DrawTile(class'UTHUD'.default.IconHudTexture, HUDScaleX * 96, HUDScaleY * 64, default.IconCoords.U, default.IconCoords.V, default.IconCoords.UL, default.IconCoords.VL);
	Canvas.DrawColor = CanvasColor;
}

/**
 * When an icon for this vehicle is needed on the hud, this function is called
 */
simulated function RenderMapIcon(UTMapInfo MP, Canvas Canvas, UTPlayerController PlayerOwner, LinearColor FinalColor)
{
	local LinearColor DrawColor;
	DrawColor = MakeLinearColor(0,0,0,0.6);
	MP.DrawRotatedTile(Canvas,class'UTHUD'.default.IconHudTexture, HUDLocation, Rotation.Yaw + 16384, MapSize * 1.05, IconCoords, DrawColor);
	FinalColor.A = 0.6;
	MP.DrawRotatedTile(Canvas,class'UTHUD'.default.IconHudTexture, HUDLocation, Rotation.Yaw + 16384, MapSize, IconCoords, FinalColor);
}

/**
 * JumpOutCheck()
 * Check if bot wants to jump out of vehicle, which is currently descending towards its destination
 */
event JumpOutCheck();


/**
 * ContinueOnFoot() - used by AI Called from route finding if route can only be continued on foot.
 * @Returns true if driver left vehicle
 */
event bool ContinueOnFoot()
{
	local UTBot B;

	B = UTBot(Controller);
	if (B == None)
	{
		return Super.ContinueOnFoot();
	}
	else if (B.Squad == None || B.Squad.AllowContinueOnFoot(B, self))
	{
		B.NoVehicleGoal = B.RouteGoal;
		if (B.RouteCache.Length > 0 && B.RouteCache[0] != None)
		{
			B.DirectionHint = Normal(B.RouteCache[0].Location - Location);
		}

		B.LeaveVehicle(false);
		return true;
	}
	else
	{
		return false;
	}
}

/**
 *  AI hint
 */
function bool FastVehicle()
{
	return false;
}

/** @return whether bots should consider attaching a tow link to this vehicle */
function bool IsGoodTowTruck()
{
	return FastVehicle();
}

/** @return whether the given vehicle pawn is in this vehicle's driver seat
 * (usually seat 0, but some vehicles may give driver control of a different seat when deployed)
 */
function bool IsDriverSeat(Vehicle TestSeatPawn)
{
	return (Seats[0].SeatPawn == TestSeatPawn);
}

function bool RecommendCharge(UTBot B, Pawn Enemy)
{
	return false;
}

/** Recommend high priority charge at enemy */
function bool CriticalChargeAttack(UTBot B)
{
	return false;
}

/************************************************************************************
 * Effects
 ***********************************************************************************/

simulated function CreateVehicleEffect(int EffectIndex)
{
	VehicleEffects[EffectIndex].EffectRef = new(self) class'UTParticleSystemComponent';
	if (VehicleEffects[EffectIndex].EffectStartTag != 'BeginPlay')
	{
		VehicleEffects[EffectIndex].EffectRef.bAutoActivate = false;
	}

	// if we have a blue particle system and we are on the blue team
	if (VehicleEffects[EffectIndex].EffectTemplate_Blue != None && GetTeamNum() == 1)
	{
		VehicleEffects[EffectIndex].EffectRef.SetTemplate(VehicleEffects[EffectIndex].EffectTemplate_Blue);
	}
	// use the default template which will be red or some neutral color
	else
	{
		VehicleEffects[EffectIndex].EffectRef.SetTemplate(VehicleEffects[EffectIndex].EffectTemplate);
	}

	Mesh.AttachComponentToSocket(VehicleEffects[EffectIndex].EffectRef, VehicleEffects[EffectIndex].EffectSocket);
}

/**
 * Initialize the effects system.  Create all the needed PSCs and set their templates
 */
simulated function InitializeEffects()
{
	if (WorldInfo.NetMode != NM_DedicatedServer && !bInitializedVehicleEffects)
	{
		bInitializedVehicleEffects = true;
		TriggerVehicleEffect('BeginPlay');
	}
}

/**
 * Whenever a vehicle effect is triggered, this function is called (after activation) to allow for the
 * setting of any parameters associated with the effect.
 *
 * @param	TriggerName		The effect tag that describes the effect that was activated
 * @param	PSC				The Particle System component associated with the effect
 */
simulated function SetVehicleEffectParms(name TriggerName, ParticleSystemComponent PSC)
{
	local float Pct;

	if (TriggerName == 'DamageSmoke')
	{
		Pct = float(Health) / float(HealthMax);
		PSC.SetFloatParameter('smokeamount', (Pct < DamageSmokeThreshold) ? (1.0 - Pct) : 0.0);
		PSC.SetFloatParameter('fireamount', (Pct < FireDamageThreshold) ? (1.0 - Pct) : 0.0);
	}
}

/**
 * Trigger or untrigger a vehicle effect
 *
 * @param	EventTag	The tag that describes the effect
 *
 */
simulated function TriggerVehicleEffect(name EventTag)
{
	local int i;

	if (WorldInfo.NetMode != NM_DedicatedServer)
	{
		for (i = 0; i < VehicleEffects.length; i++)
		{
			if (VehicleEffects[i].EffectStartTag == EventTag)
			{
				if ( !VehicleEffects[i].bHighDetailOnly || (WorldInfo.GetDetailMode() == DM_High) )
				{
					if (VehicleEffects[i].EffectRef == None)
					{
						CreateVehicleEffect(i);
					}
					if (VehicleEffects[i].bRestartRunning)
					{
						VehicleEffects[i].EffectRef.KillParticlesForced();
						VehicleEffects[i].EffectRef.ActivateSystem();
					}
					else if (!VehicleEffects[i].EffectRef.bIsActive)
					{
						VehicleEffects[i].EffectRef.ActivateSystem();
					}

					SetVehicleEffectParms(EventTag, VehicleEffects[i].EffectRef);
				}
			}
			else if (VehicleEffects[i].EffectRef != None && VehicleEffects[i].EffectEndTag == EventTag)
			{
				VehicleEffects[i].EffectRef.DeActivateSystem();
			}
		}
	}
}

/**
 * Trigger or untrigger a vehicle sound
 *
 * @param	EventTag	The tag that describes the effect
 *
 */
simulated function PlayVehicleSound(name SoundTag)
{
	local int i;
	for(i=0;i<VehicleSounds.Length;++i)
	{
		if(VehicleSounds[i].SoundEndTag == SoundTag)
		{
			if(VehicleSounds[i].SoundRef != none)
			{
				VehicleSounds[i].SoundRef.Stop();
				VehicleSounds[i].SoundRef = none;
			}
		}
		if(VehicleSounds[i].SoundStartTag == SoundTag)
		{
			if(VehicleSounds[i].SoundRef == none)
			{
				VehicleSounds[i].SoundRef = CreateAudioComponent(VehicleSounds[i].SoundTemplate, false, true);
			}
			if(VehicleSounds[i].SoundRef != none && (!VehicleSounds[i].SoundRef.bWasPlaying || VehicleSounds[i].SoundRef.bFinished))
			{
				VehicleSounds[i].SoundRef.Play();
			}
		}
	}
}
/**
 * Plays a Vehicle Animation
 */
simulated function PlayVehicleAnimation(name EventTag)
{
	local int i;
	local UTAnimNodeSequence Player;

	if ( Mesh != none && mesh.Animations != none && VehicleAnims.Length > 0 )
	{
		for (i=0;i<VehicleAnims.Length;i++)
		{
			if (VehicleAnims[i].AnimTag == EventTag)
			{
				Player = UTAnimNodeSequence(Mesh.Animations.FindAnimNode(VehicleAnims[i].AnimPlayerName));
				if ( Player != none )
				{
					Player.PlayAnimationSet( VehicleAnims[i].AnimSeqs,
												VehicleAnims[i].AnimRate,
												VehicleAnims[i].bAnimLoopLastSeq );
				}
			}
		}
	}
}

function bool EagleEyeTarget()
{
	return bCanFly;
}

/**
 * An interface for causing various events on the vehicle.
 */
simulated function VehicleEvent(name EventTag)
{
	// Cause/kill any effects
	TriggerVehicleEffect(EventTag);

	// Play any animations
	PlayVehicleAnimation(EventTag);

	PlayVehicleSound(EventTag);
}


/**
 * EntryAnnouncement() - Called when Controller possesses vehicle, for any visual/audio effects
 *
 * @param	C		The controller of that possessed the vehicle
 */
simulated function EntryAnnouncement(Controller C)
{
	Super.EntryAnnouncement(C);

	if ( Role < ROLE_Authority )
		return;

	// If Stole another team's vehicle, set Team to new owner's team
	if( (C != none) && WorldInfo.Game.bTeamGame )
	{
		if ( Team != C.GetTeamNum() )
		{
			//add stat tracking event/variable here?
			if ( Team != 255 && PlayerController(C) != None )
			{
				PlayerController(C).ReceiveLocalizedMessage( class'UTVehicleMessage', StolenAnnouncementIndex);
				UTPlayerReplicationInfo(C.PlayerReplicationInfo).IncrementEventStat('EVENT_HIJACKED');
				if( StolenSound != None )
					PlaySound(StolenSound);
			}
			if ( C.GetTeamNum() != 255 )
				SetTeamNum( C.GetTeamNum() );
		}
	}
}

/**
  * Returns rotation used for determining valid exit positions
  */
function Rotator ExitRotation()
{
	return Rotation;
}

/**
 * FindAutoExit() Tries to find exit position on either side of vehicle, in back, or in front
 * returns true if driver successfully exited.
 *
 * @param	ExitingDriver	The Pawn that is leaving the vehicle
 */
function bool FindAutoExit(Pawn ExitingDriver)
{
	local vector X, Y, Z, DirectionHint;
	local float PlaceDist;

	GetAxes(ExitRotation(), X,Y,Z);
	Y *= -1;

	if ( ExitRadius == 0 )
	{
		ExitRadius = CylinderComponent.CollisionRadius + 2*ExitingDriver.GetCollisionRadius();
	}
	PlaceDist = ExitRadius + ExitingDriver.GetCollisionRadius();

	if ( Controller != None )
	{
		if ( UTBot(ExitingDriver.Controller) != None )
		{
			// bot picks which side he'd prefer to get out on (since bots are bad at running around vehicles)
			DirectionHint = UTBot(ExitingDriver.Controller).GetDirectionHint();
			if (IsZero(DirectionHint))
			{
				// try to guess based on AI's current path
				if (ExitingDriver.Controller.MoveTarget != Anchor)
				{
					DirectionHint = Normal(ExitingDriver.Controller.MoveTarget.Location - Location);
				}
				else if (ExitingDriver.Controller.RouteCache.length > 1 && ExitingDriver.Controller.RouteCache[1] != None)
				{
					DirectionHint = Normal(ExitingDriver.Controller.RouteCache[1].Location - Location);
				}
				else if (ExitingDriver.Controller.RouteGoal != None)
				{
					DirectionHint = Normal(ExitingDriver.Controller.RouteGoal.Location - Location);
				}
			}
			if (DirectionHint Dot Y < 0.0)
			{
				Y *= -1;
			}
			if (DirectionHint Dot X < 0.0)
			{
				X *= -1;
			}
		}
		else
		{
			// use the controller's rotation as a hint
			if ( (Y dot vector(Controller.Rotation)) < 0 )
			{
				Y *= -1;
			}
		}
	}

	if ( VSize(Velocity) > MinCrushSpeed )
	{
		//avoid running driver over by placing in direction away from velocity
		if ( (Velocity Dot X) < 0 )
			X *= -1;
		// check if going sideways fast enough
		if ( (Velocity Dot Y) > MinCrushSpeed )
			Y *= -1;
	}

	if ( TryExitPos(ExitingDriver, GetTargetLocation() + (ExitOffset >> Rotation) + (PlaceDist * Y), bFindGroundExit) )
		return true;
	if ( TryExitPos(ExitingDriver, GetTargetLocation() + (ExitOffset >> Rotation) - (PlaceDist * Y), bFindGroundExit) )
		return true;

	if ( TryExitPos(ExitingDriver, GetTargetLocation() + (ExitOffset >> Rotation) - (PlaceDist * X), false) )
		return true;
	if ( TryExitPos(ExitingDriver, GetTargetLocation() + (ExitOffset >> Rotation) + (PlaceDist * X), false) )
		return true;
	if ( !bFindGroundExit )
		return false;
	if ( TryExitPos(ExitingDriver, GetTargetLocation() + (ExitOffset >> Rotation) + (PlaceDist * Y), false) )
		return true;
	if ( TryExitPos(ExitingDriver, GetTargetLocation() + (ExitOffset >> Rotation) - (PlaceDist * Y), false) )
		return true;
	if ( TryExitPos(ExitingDriver, GetTargetLocation() + (ExitOffset >> Rotation) + (PlaceDist * Z), false) )
		return true;

	return false;
}

/**
 * RanInto() called for encroaching actors which successfully moved the other actor out of the way
 *
 * @param	Other 		The pawn that was hit
 */
event RanInto(Actor Other)
{
	local vector Momentum;
	local float Speed;
	local class<UTEmitCameraEffect> CameraEffect;

	if ( Pawn(Other) == None || (Vehicle(Other) != None && !Other.IsA('UTVehicle_Hoverboard')) || Other == Instigator || Other.Role != ROLE_Authority )
		return;

	Speed = VSize(Velocity);
	if (Speed > MinRunOverSpeed)
	{
		Momentum = Velocity * 0.25 * Pawn(Other).Mass;
		if ( RanOverSound != None )
			PlaySound(RanOverSound);

		if ( WorldInfo.GRI.OnSameTeam(self,Other) || ((UTPawn(Other) != None) && UTPawn(Other).IsHero()) )
		{
			Momentum += Speed * 0.25 * Pawn(Other).Mass * Normal(Velocity cross vect(0,0,1));
		}
		else
		{
			Other.TakeDamage(int(Speed * 0.075), GetCollisionDamageInstigator(), Other.Location, Momentum, RanOverDamageType);

			if (Pawn(Other).Health <= 0 && UTPlayerController(Controller) != none)
			{
				CameraEffect = RanOverDamageType.static.GetDeathCameraEffectInstigator(UTPawn(Other));
				if (CameraEffect != None)
				{
					UTPlayerController(Controller).ClientSpawnCameraEffect(CameraEffect);
				}
			}
		}
	}
}

function PancakeOther(Pawn Other)
{
	if ( (UTPawn(Other) != None) && UTPawn(Other).IsHero() && (Other.Controller != None) )
	{
		TakeDamage(1000, Other.Controller, Other.Location, Velocity * Other.Mass, CrushedDamageType);
	}
	Other.TakeDamage(10000, GetCollisionDamageInstigator(), Other.Location, Velocity * Other.Mass, CrushedDamageType);
}

/**
 * TakeWaterDamage() called every tick when AccumulatedWaterDamage>0 and PhysicsVolume.bWaterVolume=true
 *
 * @param	DeltaTime		The amount of time passed since it was last called
 */
event TakeWaterDamage()
{
	local int ImpartedWaterDamage;

	ImpartedWaterDamage = AccumulatedWaterDamage;
	AccumulatedWaterDamage -= ImpartedWaterDamage;
	TakeDamage(ImpartedWaterDamage, Controller, Location, vect(0,0,0), VehicleDrowningDamType);
}

/**
 * This function is called to see if radius damage should be applied to the driver.  It is called
 * from SVehicle::TakeRadiusDamage().
 *
 * @param	DamageAmount		The amount of damage taken
 * @param	DamageRadius		The radius that the damage covered
 * @param	EventInstigator		Who caused the damage
 * @param	DamageType			What type of damage
 * @param	Momentum			How much force should be imparted
 * @param	HitLocation			Where
 */
function DriverRadiusDamage( float DamageAmount, float DamageRadius, Controller EventInstigator,
				class<DamageType> DamageType, float Momentum, vector HitLocation, Actor DamageCauser )
{
	local int i;
	local Vehicle V;

	if ( bDriverIsVisible )
	{
		Super.DriverRadiusDamage(DamageAmount, DamageRadius, EventInstigator, DamageType, Momentum, HitLocation, DamageCauser);
	}

	// pass damage to seats as well but skip seats[0] since that is us and was already handled by the Super

	for (i = 1; i < Seats.length; i++)
	{
		V = Seats[i].SeatPawn;
		if( ( V != none ) && ( V.bDriverIsVisible ) )
		{
			V.DriverRadiusDamage(DamageAmount, DamageRadius, EventInstigator, DamageType, Momentum, HitLocation, DamageCauser);
		}
	}

}

/**
 * Called when the vehicle is destroyed.  Clean up the seats/effects/etc
 */
simulated function Destroyed()
{
	local UTVehicle	V, Prev;
	local int i;
	local PlayerController PC;

	for(i=1;i<Seats.Length;i++)
	{
   		if ( Seats[i].SeatPawn != None )
   		{
   			if (Seats[i].SeatPawn.Controller != None)
   			{
   				WarnInternal(self @ "destroying seat" @ i @ "still controlled by" @ Seats[i].SeatPawn.Controller @ Seats[i].SeatPawn.Controller.GetHumanReadableName());
   			}
			Seats[i].SeatPawn.Destroy();
		}
		if (Seats[i].SeatMovementEffect != None)
		{
			SetMovementEffect(i, false);
		}
	}
	if ( ParentFactory != None )
		ParentFactory.VehicleDestroyed( Self );		// Notify parent factory of death

	if ( UTGame(WorldInfo.Game) != None )
	{
		if ( UTGame(WorldInfo.Game).VehicleList == Self )
			UTGame(WorldInfo.Game).VehicleList = NextVehicle;
		else
		{
			Prev = UTGame(WorldInfo.Game).VehicleList;
			if ( Prev != None )
				for ( V=UTGame(WorldInfo.Game).VehicleList.NextVehicle; V!=None; V=V.NextVehicle )
				{
					if ( V == self )
					{
						Prev.NextVehicle = NextVehicle;
						break;
					}
					else
						Prev = V;
				}
		}
	}

	SetTexturesToBeResident( FALSE );

	super.Destroyed();

	// remove from local HUD's post-rendered list
	ForEach LocalPlayerControllers(class'PlayerController', PC)
		if ( UTHUD(PC.MyHUD) != None )
			UTHUD(PC.MyHUD).RemovePostRenderedActor(self);
}


/** This will set the textures to be resident or not **/
simulated function SetTexturesToBeResident( bool bActive )
{
	local int i, j;
	local array<texture> Textures;
	local int NumElems;
	local int NumTextures;
	local Texture2D Tex2d;
	local MaterialInterface Material;

	// reset all of the textures to not be resident
	NumElems = Mesh.GetNumElements();
	for (i = 0; i < NumElems; i++)
	{
		Material = Mesh.GetMaterial(i);
		if (Material != None)
		{
			Textures = Material.GetMaterial().GetTextures();
			NumTextures = Textures.Length;
			for( j = 0; j < NumTextures; ++j )
			{
				//`log( "Texture setting bForceMiplevelsToBeResident: " $ bActive $ " " $ Textures[j] );
				Tex2d = Texture2D(Textures[j]);
				if( Tex2d != none )
				{
					Tex2d.bForceMiplevelsToBeResident = bActive;
				}
			}
		}
	}
}


simulated function bool DisableVehicle()
{
	local int seatIdx;

	if ( Occupied() )
	{
		bIsDisabled = true;

		if (Role == ROLE_Authority)
		{
			SetTimer(DisabledTime, false, 'EnableVehicle');

			// everybody out!
			if (bDriving)
			{
				DriverLeave(true);
			}
			for (seatIdx = 0; seatIdx < seats.Length; ++seatIdx)
			{
				if (Seats[seatIdx].SeatPawn != None && Seats[SeatIdx].SeatPawn.bDriving)
				{
					Seats[seatIdx].SeatPawn.DriverLeave(true); // and all the passengers
				}
			}
		}

		if (WorldInfo.NetMode != NM_DedicatedServer)
		{
			if (DisabledEffectComponent == None)
			{
				DisabledEffectComponent = new(self) class'ParticleSystemComponent';
				DisabledEffectComponent.SetTemplate(DisabledTemplate);
				AttachComponent(DisabledEffectComponent);
			}
			DisabledEffectComponent.ActivateSystem();
		}
		return true;
	}
	return false;
}

simulated function EnableVehicle()
{
	bIsDisabled = false;
	if (WorldInfo.NetMode != NM_DedicatedServer && DisabledEffectComponent != None)
	{
		DetachComponent(DisabledEffectComponent);
		DisabledEffectComponent = None;
	}
}

/**
 * This event occurs when the physics determines the vehicle is upside down or empty and on fire.  Called from AUTVehicle::TickSpecial()
 */
event TakeFireDamage()
{
	local int CurrentDamage;

	CurrentDamage = int(AccruedFireDamage);
	AccruedFireDamage -= CurrentDamage;
	TakeDamage(CurrentDamage, Controller, Location, vect(0,0,0), ExplosionDamageType);
}

/**
 * Given the variable prefix, find the seat index that is associated with it
 *
 * @returns the index if found or -1 if not found
 */

simulated function int GetSeatIndexFromPrefix(string Prefix)
{
	local int i;

	for (i=0; i < Seats.Length; i++)
	{
		if (Seats[i].TurretVarPrefix ~= Prefix)
		{
			return i;
		}
	}
	return -1;
}

/** used on console builds to set the value of bIsConsoleTurning on the server */
reliable server function ServerSetConsoleTurning(bool bNewConsoleTurning)
{
	bIsConsoleTurning = bNewConsoleTurning;
}

simulated function ProcessViewRotation(float DeltaTime, out rotator out_ViewRotation, out rotator out_DeltaRot)
{
	local int i, MaxDelta;
	local float MaxDeltaDegrees;

	if (WorldInfo.bUseConsoleInput)
	{
		if (!bSeparateTurretFocus && ShouldClamp())
		{
			if (out_DeltaRot.Yaw == 0)
			{
				if (bIsConsoleTurning)
				{
					// if controller stops rotating on a vehicle whose view rotation yaw gets clamped,
					// set the controller's yaw to where we got so that there's no control lag
					out_ViewRotation.Yaw = GetClampedViewRotation().Yaw;
					bIsConsoleTurning = false;
					ServerSetConsoleTurning(false);
				}
			}

			else if (!bIsConsoleTurning)
			{
				// don't allow starting a new turn if the view would already be clamped
				// because that causes nasty jerking
				if (GetClampedViewRotation().Yaw == Controller.Rotation.Yaw)
				{
					bIsConsoleTurning = true;
					ServerSetConsoleTurning(true);
				}
				else
				{
					// @fixme:  this should be setting to max turn rate so we actually do something when outside of the cone
					out_DeltaRot.Yaw = 0;
				}
			}

			// clamp player rotation to turret rotation speed
			for (i = 0; i < Seats[0].TurretControllers.length; i++)
			{
				MaxDeltaDegrees = FMax(MaxDeltaDegrees, Seats[0].TurretControllers[i].LagDegreesPerSecond);
			}

			if (MaxDeltaDegrees > 0.0)
			{
				MaxDelta = int(MaxDeltaDegrees * 182.0444 * DeltaTime);
				out_DeltaRot.Pitch = (out_DeltaRot.Pitch >= 0) ? Min(out_DeltaRot.Pitch, MaxDelta) : Max(out_DeltaRot.Pitch, -MaxDelta);
				out_DeltaRot.Yaw = (out_DeltaRot.Yaw >= 0) ? Min(out_DeltaRot.Yaw, MaxDelta) : Max(out_DeltaRot.Yaw, -MaxDelta);
				out_DeltaRot.Roll = (out_DeltaRot.Roll >= 0) ? Min(out_DeltaRot.Roll, MaxDelta) : Max(out_DeltaRot.Roll, -MaxDelta);
			}
		}
	}
	Super.ProcessViewRotation(DeltaTime, out_ViewRotation, out_DeltaRot);
}

simulated function rotator GetClampedViewRotation()
{
	local rotator ViewRotation, ControlRotation, MaxDelta;
	local UTVehicleWeapon VWeap;

	VWeap = UTVehicleWeapon(Weapon);
	if (VWeap != None && ShouldClamp())
	{
		// clamp view yaw so that it doesn't exceed how far the vehicle can aim on console
		ViewRotation.Yaw = Controller.Rotation.Yaw;
		MaxDelta.Yaw = ACos(VWeap.GetMaxFinalAimAdjustment()) * 180.0 / Pi * 182.0444;
		if (!ClampRotation(ViewRotation, Rotation, MaxDelta, MaxDelta))
		{
			// prevent the controller's rotation from diverging too much from the actual view rotation
			ControlRotation.Yaw = Controller.Rotation.Yaw;
			if (!ClampRotation(ControlRotation, ViewRotation, rot(0,16384,0), rot(0,16384,0)))
			{
				ControlRotation.Pitch = Controller.Rotation.Pitch;
				ControlRotation.Roll = Controller.Rotation.Roll;
				Controller.SetRotation(ControlRotation);
			}
		}

		ViewRotation.Pitch = Controller.Rotation.Pitch;
		ViewRotation.Roll = Controller.Rotation.Roll;
		return ViewRotation;
	}
	else
	{
		return super.GetViewRotation();
	}
}

simulated function bool ShouldClamp()
{
	return true;
}

simulated event rotator GetViewRotation()
{
	if (bIsConsoleTurning && !bSeparateTurretFocus && PlayerController(Controller) != None)
	{
		return GetClampedViewRotation();
	}
	else
	{
		return Super.GetViewRotation();
	}
}

/**
 * this function is called when a weapon rotation value has changed.  It sets the DesiredboneRotations for each controller
 * associated with the turret.
 *
 * Network: Remote clients.  All other cases are handled natively
 * FIXME: Look at handling remote clients natively as well
 *
 * @param	SeatIndex		The seat at which the rotation changed
 */

simulated function WeaponRotationChanged(int SeatIndex)
{
	local int i;

	if ( SeatIndex>=0 )
	{
		for (i=0;i<Seats[SeatIndex].TurretControllers.Length;i++)
		{
			Seats[SeatIndex].TurretControllers[i].DesiredBoneRotation = SeatWeaponRotation(SeatIndex,,true);
		}
	}
}

/**
 * This event is triggered when a repnotify variable is received
 *
 * @param	VarName		The name of the variable replicated
 */

simulated event ReplicatedEvent(name VarName)
{
	local string VarString;
	local int SeatIndex;

	if (VarName == 'bPlayingSpawnEffect')
	{
		if (bPlayingSpawnEffect)
		{
			if (Team != UTVEHICLE_UNSET_TEAM)
			{
				PlaySpawnEffect();
			}
		}
		else
		{
			StopSpawnEffect();
		}
	}
	else if ( VarName == 'Team' )
	{
		TeamChanged();
		if (bPlayingSpawnEffect)
		{
			PlaySpawnEffect();
		}
	}
	else if (VarName == 'bDeadVehicle')
	{
		BlowupVehicle();
	}
	else if (VarName == 'bIsDisabled')
	{
		if (bIsDisabled)
		{
			DisableVehicle();
		}
		else
		{
			EnableVehicle();
		}
	}
	else if (VarName == 'LinkedToCount')
	{
		if (LinkedToCount > 0)
		{
			StartLinkedEffect();
		}
		else
		{
			StopLinkedEffect();
		}
	}
	else if ( VarName == 'bKeyVehicle' )
	{
	  if ( bKeyVehicle )
		UTMapInfo(WorldInfo.GetMapInfo()).AddKeyVehicle(self);
	}
	else
	{
		// Ok, some magic occurs here.  The turrets/seat use a prefix system to determine
		// which values to adjust. Here we decode those values and call the appropriate functions

		// First check for <xxxxx>weaponrotation

		VarString = ""$VarName;
		if ( Right(VarString, 14) ~= "weaponrotation" )
		{
			SeatIndex = GetSeatIndexFromPrefix( Left(VarString, Len(VarString)-14) );
			if (SeatIndex >= 0)
			{
				WeaponRotationChanged(SeatIndex);
			}
		}

		// Next, check for <xxxxx>flashcount

		else if ( Right(VarString, 10) ~= "flashcount" )
		{
			SeatIndex = GetSeatIndexFromPrefix( Left(VarString, Len(VarString)-10) );
			if ( SeatIndex>=0 )
			{
				Seats[SeatIndex].BarrelIndex++;

				if ( SeatFlashCount(SeatIndex,,true) > 0 )
				{
					VehicleWeaponFired(true, vect(0,0,0), SeatIndex);
				}
				else
				{
					VehicleWeaponStoppedFiring(true,SeatIndex);
				}
			}
		}

		// finally <xxxxxx>flashlocation

		else if ( Right(VarString, 13) ~= "flashlocation" )
		{
			SeatIndex = GetSeatIndexFromPrefix( Left(VarString, Len(VarString)-13) );
			if ( SeatIndex>=0 )
			{
				Seats[SeatIndex].BarrelIndex++;

				if ( !IsZero(SeatFlashLocation(SeatIndex,,true)) )
				{
					VehicleWeaponFired(true, SeatFlashLocation(SeatIndex,,true), SeatIndex);
				}
				else
				{
					VehicleWeaponStoppedFiring(true,SeatIndex);
				}
			}
		}
		else
		{
			super.ReplicatedEvent(VarName);
		}
	}
}

event SetKeyVehicle()
{
	bKeyVehicle = true;
	UTMapInfo(WorldInfo.GetMapInfo()).AddKeyVehicle(self);
}

/**
 * AI Hint
 * @returns true if there is an occupied turret
 */

function bool HasOccupiedTurret()
{
	local int i;

	for (i = 1; i < Seats.length; i++)
	{
		if( ( Seats[i].SeatPawn != none )
			&& ( Seats[i].SeatPawn.Controller != None )
			)
		{
			return true;
		}
	}

	return false;
}

/**
 * This function is called when the driver's status has changed.
 */
simulated function DrivingStatusChanged()
{
	local UTConsolePlayerController UTPC;

	// turn parking friction on or off
	bUpdateWheelShapes = true;

	// possibly use different physical material while being driven (to allow properties like friction to change).
	if ( bDriving )
	{
		if ( DrivingPhysicalMaterial != None )
		{
			Mesh.SetPhysMaterialOverride(DrivingPhysicalMaterial);
		}
	}
	else if ( DefaultPhysicalMaterial != None )
	{
		Mesh.SetPhysMaterialOverride(DefaultPhysicalMaterial);
	}

	if ( bDriving && !bIsDisabled )
	{
		VehiclePlayEnterSound();
	}
	else if ( Health > 0 )
	{
		VehiclePlayExitSound();
	}

	bBlocksNavigation = !bDriving;

	if (!bDriving)
	{
		StopFiringWeapon();

		SetMovementEffect(0, false);
		SetTexturesToBeResident(false);
	}

	VehicleEvent(bDriving ? 'EngineStart' : 'EngineStop');

	UTPC = UTConsolePlayerController(Controller);
	if (UTPC == None && Driver != None)
	{
		UTPC = UTConsolePlayerController(Driver.Controller);
	}

	if (UTPC != None && LocalPlayer(UTPC.Player) != None)
	{
		UTPC.ClientPlayForceFeedbackWaveform(DriverStatusChangedWaveform);
	}
}

event OnAnimEnd(AnimNodeSequence SeqNode, float PlayedTime, float ExcessTime)
{
	super.OnAnimEnd(SeqNode,PlayedTime,ExcessTime);
	if(bDriving)
	{
		VehicleEvent('Idle');
	}
}

/**
 * @Returns true if a seat is not occupied
 */
function bool SeatAvailable(int SeatIndex)
{
	return Seats[SeatIndex].SeatPawn == none || Seats[SeatIndex].SeatPawn.Controller == none;
}

/**
 * @return true if there is a seat
 */
function bool AnySeatAvailable()
{
	local int i;
	for (i=0;i<Seats.Length;i++)
	{
		if( ( Seats[i].SeatPawn != none )
			&& ( Seats[i].SeatPawn.Controller==none )
			)
		{
			return true;
		}
	}
	return false;
}

/**
 * @returns the Index for this Controller's current seat or -1 if there isn't one
 */
simulated function int GetSeatIndexForController(controller ControllerToMove)
{
	local int i;
	for (i=0;i<Seats.Length;i++)
	{
		if (Seats[i].SeatPawn.Controller != none && Seats[i].SeatPawn.Controller == ControllerToMove )
		{
			return i;
		}
	}
	return -1;
}

/**
 * @returns the controller of a given seat.  Can be none if the seat is empty
 */
function controller GetControllerForSeatIndex(int SeatIndex)
{
	return Seats[SeatIndex].SeatPawn.Controller;
}

/**
request change to adjacent vehicle seat
*/
reliable server function ServerAdjacentSeat(int Direction, Controller C)
{
	local int CurrentSeat, NewSeat;

	CurrentSeat = GetSeatIndexForController(C);
	if (CurrentSeat != INDEX_NONE)
	{
		NewSeat = CurrentSeat;
		do
		{
			NewSeat += Direction;
			if (NewSeat < 0)
			{
				NewSeat = Seats.Length - 1;
			}
			else if (NewSeat == Seats.Length)
			{
				NewSeat = 0;
			}
			if (NewSeat == CurrentSeat)
			{
				// no available seat
				if ( PlayerController(C) != None )
				{
					PlayerController(C).ClientPlaySound(VehicleLockedSound);
				}
				return;
			}
		} until (SeatAvailable(NewSeat) || (Seats[NewSeat].SeatPawn != None && UTBot(Seats[NewSeat].SeatPawn.Controller) != None));

		// change to the seat we found
		ChangeSeat(C, NewSeat);
	}
}

/**
 * Called when a client is requesting a seat change
 *
 * @network	Server-Side
 */
reliable server function ServerChangeSeat(int RequestedSeat)
{
	if ( RequestedSeat == -1 )
		DriverLeave(false);
	else
		ChangeSeat(Controller, RequestedSeat);
}

/**
 * This function looks at 2 controllers and decides if one as priority over the other.  Right now
 * it looks to see if a human is against a bot but it could be extended to use rank/etc.
 *
 * @returns	ture if First has priority over second
 */
function bool HasPriority(controller First, controller Second)
{
	if ( First != Second && PlayerController(First) != none && PlayerController(Second) == none)
		return true;
	else
		return false;
}

/**
 * ChangeSeat, this controller to change from it's current seat to a new one if (A) the new
 * set is empty or (B) the controller looking to move has Priority over the controller already
 * there.
 *
 * If the seat is filled but the new controller has priority, the current seat holder will be
 * bumped and swapped in to the seat left vacant.
 *
 * @param	ControllerToMove		The Controller we are trying to move
 * @param	RequestedSeat			Where are we trying to move him to
 *
 * @returns true if successful
 */
function bool ChangeSeat(Controller ControllerToMove, int RequestedSeat)
{
	local int OldSeatIndex;
	local Pawn OldPawn, BumpPawn;
	local Controller BumpController;

	// Make sure we are looking to switch to a valid seat
	if ( (RequestedSeat >= Seats.Length) || (RequestedSeat < 0) )
	{
		return false;
	}

	// get the seat index of the pawn looking to move.
	OldSeatIndex = GetSeatIndexForController(ControllerToMove);
	if (OldSeatIndex == -1)
	{
		// Couldn't Find the controller, should never happen
		WarnInternal("[Vehicles] Attempted to switch" @ ControllerToMove @ "to a seat in" @ self @ " when he is not already in the vehicle");
		return false;
	}

	// If someone is in the seat, see if we can bump him
	if (!SeatAvailable(RequestedSeat))
	{
		// Get the Seat holder's controller and check it for Priority
		BumpController = GetControllerForSeatIndex(RequestedSeat);
		if (BumpController == none)
		{
			WarnInternal("[Vehicles]" @ ControllertoMove @ "Attempted to bump a phantom Controller in seat in" @ RequestedSeat @ " (" $ Seats[RequestedSeat].SeatPawn $ ")");
			return false;
		}

		if ( !HasPriority(ControllerToMove,BumpController) )
		{
			// Nope, same or great priority on the seat holder, deny the move
			if ( PlayerController(ControllerToMove) != None )
			{
				PlayerController(ControllerToMove).ClientPlaySound(VehicleLockedSound);
			}
			return false;
		}

		// If we are bumping someone, free their seat.
		if (BumpController != None)
		{
			BumpPawn = Seats[RequestedSeat].StoragePawn;
			Seats[RequestedSeat].SeatPawn.DriverLeave(true);

			// Handle if we bump the driver
			if (RequestedSeat == 0)
			{
				// Reset the controller's AI if needed
				if (BumpController.RouteGoal == self)
				{
					BumpController.RouteGoal = None;
				}
				if (BumpController.MoveTarget == self)
				{
					BumpController.MoveTarget = None;
				}
			}
		}
	}

	OldPawn = Seats[OldSeatIndex].StoragePawn;

	// Leave the current seat and take over the new one
	Seats[OldSeatIndex].SeatPawn.DriverLeave(true);
	if (OldSeatIndex == 0)
	{
		// Reset the controller's AI if needed
		if (ControllerToMove.RouteGoal == self)
		{
			ControllerToMove.RouteGoal = None;
		}
		if (ControllerToMove.MoveTarget == self)
		{
			ControllerToMove.MoveTarget = None;
		}
	}

	if (RequestedSeat == 0)
	{
		DriverEnter(OldPawn);
	}
	else
	{
		PassengerEnter(OldPawn, RequestedSeat);
	}


	// If we had to bump a pawn, seat them in this controller's old seat.
	if (BumpPawn != None)
	{
		if (OldSeatIndex == 0)
		{
			DriverEnter(BumpPawn);
		}
		else
		{
			PassengerEnter(BumpPawn, OldSeatIndex);
		}
	}
	return true;
}

/**
 * This event is called when the pawn is torn off
 */
simulated event TornOff()
{
	WarnInternal(self @ "Torn off");
}

function Controller GetCollisionDamageInstigator()
{
	// give vehicle killer credit if possible
	return (KillerController != None) ? KillerController : Super.GetCollisionDamageInstigator();
}

/**
 * See Pawn::Died()
 */
function bool Died(Controller Killer, class<DamageType> DamageType, vector HitLocation)
{
	local UTCarriedObject Flag;
	local UTPawn UTP;
	local UTPlayerReplicationInfo UTPRI;
	local int i;

	// before we kill the vehicle and everyone inside, eject anyone who has a shieldbelt
	for (i=0;i<Seats.Length;i++)
	{
		if (Seats[i].SeatPawn != None || Seats[i].StoragePawn != None)
		{
			UTP = UTPawn(Seats[i].StoragePawn);
			if((UTP != none) && UTP.ShieldBeltArmor > 0)
			{
				UTP.ShieldBeltArmor = 0;
				UTP.SetOverlayMaterial(none);
				EjectSeat(i);
			}
		}
	}
	if ( Super(Vehicle).Died(Killer, DamageType, HitLocation) )
	{
		if ( (VehicleDestroyedSound.Length > 0) && (UTBot(Killer) != None) )
		{
			UTBot(Killer).KilledVehicleClass = Class;
			Killer.SendMessage(None, 'VEHICLEKILL', 10);
		}
		KillerController = Killer;
		HitDamageType = DamageType; // these are replicated to other clients
		TakeHitLocation = HitLocation;
		UTPRI = UTPlayerReplicationInfo(PlayerReplicationInfo);
		if ( UTPRI != None )
		{
			UTPRI.StopDrivingStat(GetVehicleDrivingStatName());
		}
		BlowupVehicle();

		HandleDeadVehicleDriver();

		for (i = 1; i < Seats.Length; i++)
		{
			if (Seats[i].SeatPawn != None)
			{
				UTPRI = UTPlayerReplicationInfo(Seats[i].SeatPawn.PlayerReplicationInfo);
				if ( UTPRI != None )
				{
					UTPRI.StopDrivingStat(UTVehicleBase(Seats[i].SeatPawn).GetVehicleDrivingStatName());
				}
				// kill the WeaponPawn with the appropriate killer, etc for kill credit and death messages
				Seats[i].SeatPawn.Died(Killer, DamageType, HitLocation);
			}
		}

		// drop flag
		ForEach BasedActors(class'UTCarriedObject' , Flag)
		{
			Flag.SetBase(None);
		}

		// notify vehicle factory
		if (ParentFactory != None)
		{
			ParentFactory.VehicleDestroyed(self);
			ParentFactory = None;
		}
		return true;
	}
	return false;
}

/**
 * Call this function to blow up the vehicle
 */
simulated function BlowupVehicle()
{
	local int i;
	local UTDeployedActor D;

	if(bDriving)
	{
		VehicleEvent('EngineStop');
	}

	bCanBeBaseForPawns = false;
	LinkHealMult = 0.0;
	GotoState('DyingVehicle');
	AddVelocity(TearOffMomentum, TakeHitLocation, HitDamageType);
	bDeadVehicle = true;
	bStayUpright = false;

	if ( StayUprightConstraintInstance != None )
	{
		StayUprightConstraintInstance.TermConstraint();
	}

	// Iterate over wheels, turning off those we want
	for(i=0; i<Wheels.length; i++)
	{
		if(UTVehicleWheel(Wheels[i]) != None && UTVehicleWheel(Wheels[i]).bDisableWheelOnDeath)
		{
			SetWheelCollision(i, FALSE);
		}
	}

	// kill deployed actors based on this vehicle
	foreach BasedActors(class'UTDeployedActor', D)
	{
		D.destroy();
	}
}

/**
  * if bHasCustomEntryRadius, this is called to see if Pawn P is in it.
  */
function bool InCustomEntryRadius(Pawn P)
{
	return false;
}

simulated function PlayerReplicationInfo GetSeatPRI(int SeatNum)
{
	if ( Role == ROLE_Authority )
	{
		return Seats[SeatNum].SeatPawn.PlayerReplicationInfo;
	}
	else
	{
		return (SeatNum==0) ? PlayerReplicationInfo : PassengerPRI;
	}
}

/**
 * CanEnterVehicle()
 * @return true if Pawn P is allowed to enter this vehicle
 */
simulated function bool CanEnterVehicle(Pawn P)
{
	local int i;
	local bool bSeatAvailable, bIsHuman;
	local PlayerReplicationInfo SeatPRI;

	if ( P.bIsCrouched || (P.DrivenVehicle != None) || (P.Controller == None) || !P.Controller.bIsPlayer
	     || Health <= 0 || bDeleteMe || ((UTPawn(P) != None) && UTPawn(P).IsHero()) )
	{
		return false;
	}

	// check for available seat, and no enemies in vehicle
	// allow humans to enter if full but with bots (TryToDrive() will kick one out if possible)
	bIsHuman = P.IsHumanControlled();
	bSeatAvailable = false;
	for (i=0;i<Seats.Length;i++)
	{
		SeatPRI = GetSeatPRI(i);
		if (SeatPRI == None)
		{
			bSeatAvailable = true;
		}
		else if (!WorldInfo.GRI.OnSameTeam(P, SeatPRI))
		{
			return false;
		}
		else if (bIsHuman && SeatPRI.bBot)
		{
			bSeatAvailable = true;
		}
	}

	return bSeatAvailable;
}

/**
 * The pawn Driver has tried to take control of this vehicle
 *
 * @param	P		The pawn who wants to drive this vehicle
 */
function bool TryToDrive(Pawn P)
{
	local vector X,Y,Z;
	local bool bFreedSeat;
	local bool bEnteredVehicle;

	// don't allow while playing spawn effect
	if (bPlayingSpawnEffect)
	{
		return false;
	}

	// Does the vehicle need to be uprighted?
	if ( bIsInverted && bMustBeUpright && !bVehicleOnGround && VSize(Velocity) <= 5.0f )
	{
		if ( bCanFlip )
		{
			bIsUprighting = true;
			UprightStartTime = WorldInfo.TimeSeconds;
			GetAxes(Rotation,X,Y,Z);
			bFlipRight = ((P.Location - Location) dot Y) > 0;
		}
		return false;
	}

	if ( !CanEnterVehicle(P) || (Vehicle(P) != None) )
	{
		return false;
	}

	// Check vehicle Locking....
	// Must be a non-disabled same team (or no team game) vehicle
	if (!bIsDisabled && (Team == UTVEHICLE_UNSET_TEAM || !bTeamLocked || !WorldInfo.Game.bTeamGame || WorldInfo.GRI.OnSameTeam(self,P)))
	{
		if (bEnteringUnlocks)
		{
			bTeamLocked = false;
			if (ParentFactory != None)
			{
				ParentFactory.VehicleTaken();
			}
		}

		if (!AnySeatAvailable())
		{
			if (WorldInfo.GRI.OnSameTeam(self, P))
			{
				// kick out the first bot in the vehicle to make way for this driver
				bFreedSeat = KickOutBot();
			}

			if (!bFreedSeat)
			{
				// we were unable to kick a bot out
				return false;
			}
		}

		// Look to see if the driver seat is open
		bEnteredVehicle = (Driver == None) ? DriverEnter(P) : PassengerEnter(P, GetFirstAvailableSeat());

		if( bEnteredVehicle )
		{
			SetTexturesToBeResident( TRUE );
		}

		return bEnteredVehicle;
	}

	VehicleLocked( P );
	return false;
}

/**
  * kick out the first bot in the vehicle to make way for human driver
  */
function bool KickOutBot()
{
	local int i;
	local UTBot B;

	for (i = 0; i < Seats.length; i++)
	{
		B = UTBot(Seats[i].SeatPawn.Controller);
		if (B != None && Seats[i].SeatPawn.DriverLeave(false))
		{
			// we can't tell the bot to re-evaluate right away, because it will often get right back in this vehicle
			B.SetTimer(0.01, false, 'WhatToDoNext');
			return true;
		}
	}
	return false;
}

/**
 * Pawn tried to enter vehicle, but it's locked!!
 *
 * @param	P	The pawn that tried
 */
function VehicleLocked( Pawn P )
{
	local PlayerController PC;

	PC = PlayerController(P.Controller);

	if ( PC != None )
	{
		PC.ClientPlaySound(VehicleLockedSound);
		PC.ReceiveLocalizedMessage(class'UTVehicleMessage', 1);
	}
}

simulated native function bool InUseableRange(UTPlayerController PC, float Dist);
/**
  * returns TRUE if vehicle is useable (can be entered)
  */
simulated function bool ShouldShowUseable(PlayerController PC, float Dist)
{
	local UTPlayerController UTPC;

	UTPC = UTPlayerController(PC);
	return ( InUseableRange(UTPC, Dist) && CanEnterVehicle(PC.Pawn)
				&& ((UTPC.CheckVehicleToDrive(false) == self)
					|| (bRequestedEntryWithFlag && UTPC.bJustFoundVehicle && UTPlayerReplicationInfo(PC.PlayerReplicationInfo).bHasFlag)) );
}

simulated native function NativePostRenderFor(PlayerController PC, Canvas Canvas, vector CameraPosition, vector CameraDir);

/**
 * PostRenderFor() Hook to allow pawns to render HUD overlays for themselves.
 * Assumes that appropriate font has already been set
 *
 * @param	PC		The Player Controller who is rendering this pawn
 * @param	Canvas	The canvas to draw on
 */
simulated event PostRenderFor(PlayerController PC, Canvas Canvas, vector CameraPosition, vector CameraDir)
{
	local float TextXL, XL, YL, Dist, HealthY, xscale, MaxOffset;
	local vector ScreenLoc, HitNormal, HitLocation, CrossDir;
	local actor HitActor;
	local LinearColor TeamColor;
	local Color	TextColor;
	local string ScreenName;
	local bool bShowUseable;
	local UTWeapon Weap;
	local UTHUD HUD;

	// NOTE bShowlocked is set in NativePostRenderFor().
	HUD = UTHUD(PC.MyHUD);

	Dist = VSize(CameraPosition - Location);

	if ( WorldInfo.GRI.GameClass.default.bTeamGame && !WorldInfo.GRI.OnSameTeam(self, PC) )
	{
		if ( IsInvisible() )
		{
			LastPostRenderTraceTime = WorldInfo.TimeSeconds;
			return;
		}
		if ( !bPostRenderOtherTeam )
		{
			if ( !bShowLocked && !PC.PlayerReplicationInfo.bOnlySpectator )
			{
				// if not on same team, then only draw icon if locked
				// maybe change to action music if close enough
				if ( (PlayerReplicationInfo != None) && (WorldInfo.TimeSeconds - LastPostRenderTraceTime > 0.5) )
				{
					if ( !UTPlayerController(PC).AlreadyInActionMusic() && (Dist*Dist < VSizeSq(PC.ViewTarget.Location - Location)) )
					{
						// check whether close enough to crosshair
						screenLoc = Canvas.Project(Location);
						if ( (Abs(screenLoc.X - 0.5*Canvas.ClipX) < 0.1 * Canvas.ClipX)
							&& (Abs(screenLoc.Y - 0.5*Canvas.ClipY) < 0.1 * Canvas.ClipY) )
						{
							// make sure really visible using traces
							if ( FastTrace(Location, CameraPosition,, true)
										|| FastTrace(Location+GetCollisionHeight()*vect(0,0,1), CameraPosition,, true) )
							{
								UTPlayerController(PC).ClientMusicEvent(0);;
							}
						}
					}
					LastPostRenderTraceTime = WorldInfo.TimeSeconds + 0.2*FRand();
				}
				bShowUseable = ShouldShowUseable(PC, Dist);
				if ( !bShowUseable )
				{
					return;
				}
			}
		}
	}

	ScreenLoc = bShowLocked ? Canvas.Project(Location) : Canvas.Project(Location + TeamBeaconOffset);

	// make sure not clipped out
	if (screenLoc.X < 0 ||
		screenLoc.X >= Canvas.ClipX ||
		screenLoc.Y < 0 ||
		screenLoc.Y >= Canvas.ClipY)
	{
		// what if should draw "E to enter"
		if ( !bShowLocked && !bShowUseable && !bPlayingSpawnEffect && ((UTPawn(PC.Pawn) != None) || (UTVehicle_Hoverboard(PC.Pawn) != None)) )
		{
			bShowUseable = ShouldShowUseable(PC, Dist);
		}
		if ( !bShowUseable )
		{
			return;
		}
	}

	// make sure not behind weapon
	if ( UTPawn(PC.Pawn) != None )
	{
		Weap = UTWeapon(UTPawn(PC.Pawn).Weapon);
		if ( (Weap != None) && Weap.CoversScreenSpace(screenLoc, Canvas) )
		{
			return;
		}
	}
	else if ( (UTVehicle_Hoverboard(PC.Pawn) != None) && UTVehicle_Hoverboard(PC.Pawn).CoversScreenSpace(screenLoc, Canvas) )
	{
		return;
	}

	// periodically make sure really visible using traces
	if ( WorldInfo.TimeSeconds - LastPostRenderTraceTime > 0.5 )
	{
		LastPostRenderTraceTime = WorldInfo.TimeSeconds + 0.2*FRand();
		bPostRenderTraceSucceeded = FastTrace(Location, CameraPosition);

		if ( !bPostRenderTraceSucceeded )
		{
			if ( bShowLocked )
			{
				return;
			}
			bPostRenderTraceSucceeded = FastTrace(Location+GetCollisionHeight()*vect(0,0,1), CameraPosition);
			if ( !bPostRenderTraceSucceeded )
			{
				// now try top corners of vehicle, before giving up
				CrossDir = Normal(Vect(0,0,1) cross (Location - CameraPosition));
				bPostRenderTraceSucceeded = FastTrace(Location+GetCollisionHeight()*vect(0,0,1)+CylinderComponent.CollisionRadius*CrossDir, CameraPosition)
										|| FastTrace(Location+GetCollisionHeight()*vect(0,0,1)-CylinderComponent.CollisionRadius*CrossDir, CameraPosition);
			}
		}
	}
	if ( !bPostRenderTraceSucceeded )
	{
		return;
	}

	if ( bShowLocked )
	{
		// draw no entry indicator
		// don't draw it if there's another vehicle in front of the vehicle
		HitActor = Trace(HitLocation, HitNormal, Location, CameraPosition, true,,,TRACEFLAG_Blocking);
		if ( UTVehicle(HitActor) != None )
		{
			return;
		}

		// draw locked symbol
		xscale = FClamp( (2*TeamBeaconPlayerInfoMaxDist - Dist)/(2*TeamBeaconPlayerInfoMaxDist), 0.55f, 1.f);
		xscale = xscale * xscale;
		Canvas.SetPos(ScreenLoc.X-16*xscale,ScreenLoc.Y-16*xscale);
		Canvas.DrawColor = class'UTHUD'.Default.WhiteColor;

		Canvas.DrawColorizedTile(class'UTHUD'.Default.AltHudTexture,30*xscale, 30*xscale,599,208,15,21, MakeLinearColor( 4.0, 2.0, 0.5, 1.0) );
		return;
	}

	if ( Dist > TeamBeaconPlayerInfoMaxDist )
	{
		HealthY = 8 * Canvas.ClipX/1024;
	}
	else if ( PlayerReplicationInfo == None )
	{
		HealthY = 8 * Canvas.ClipX/1024 * (1 + 2*Square((TeamBeaconPlayerInfoMaxDist-Dist)/TeamBeaconPlayerInfoMaxDist));
	}
	else
	{
		HealthY = 16 * Canvas.ClipX/1024 * (1 + 2*Square((TeamBeaconPlayerInfoMaxDist-Dist)/TeamBeaconPlayerInfoMaxDist));
	}

	class'UTHUD'.Static.GetTeamColor( GetTeamNum(), TeamColor, TextColor);

	if ( Dist > TeamBeaconPlayerInfoMaxDist )
	{
		XL = 2 * HealthY;
	}
	else if ( PlayerReplicationInfo != None )
	{
		ScreenName = PlayerReplicationInfo.GetPlayerAlias();
		Canvas.StrLen(ScreenName, TextXL, YL);
		if (bDisplayHealthBar)
		{
			XL = Max( TextXL, 2*HealthY );
			HealthY *= 0.5;
		}
		else
		{
			XL = TextXL;
		}
	}
	else
	{
		XL = 2 * HealthY;
	}

	// customize beacon if this vehicle could be entered
	if ( !bPlayingSpawnEffect && ((UTPawn(PC.Pawn) != None) || (UTVehicle_Hoverboard(PC.Pawn) != None)) )
	{
		if ( bShowUseable || ShouldShowUseable(PC, Dist) )
		{
			// programmer art - just color it greenish
			bShowUseable = true;
			if ( bRequestedEntryWithFlag && UTPlayerReplicationInfo(PC.PlayerReplicationInfo).bHasFlag )
			{
				//Show a flag for CTF/VCTF, an orb for WAR
				if(ClassIsChildOf(WorldInfo.GRI.GameClass, class'UTOnslaughtGame') == False)
				{
					HUD.DrawToolTip(Canvas, PC, "GBA_Use", Canvas.ClipX * 0.5, Canvas.ClipY * 0.6, DropFlagIconCoords.U, DropFlagIconCoords.V, DropFlagIconCoords.UL, DropFlagIconCoords.VL, Canvas.ClipY / 768);
				}
				else
				{
					HUD.DrawToolTip(Canvas, PC, "GBA_Use", Canvas.ClipX * 0.5, Canvas.ClipY * 0.6, DropOrbIconCoords.U, DropOrbIconCoords.V, DropOrbIconCoords.UL, DropOrbIconCoords.VL, Canvas.ClipY / 768);
				}
			}
			else
			{
				if (bIsInverted && bCanFlip)
				{
					HUD.DrawToolTip(Canvas, PC, "GBA_Use", Canvas.ClipX * 0.5, Canvas.ClipY * 0.6, FlipToolTipIconCoords.U, FlipToolTipIconCoords.V, FlipToolTipIconCoords.UL, FlipToolTipIconCoords.VL, Canvas.ClipY / 768);
				}
				else
				{
					HUD.DrawToolTip(Canvas, PC, "GBA_Use", Canvas.ClipX * 0.5, Canvas.ClipY * 0.6, EnterToolTipIconCoords.U, EnterToolTipIconCoords.V, EnterToolTipIconCoords.UL, EnterToolTipIconCoords.VL, Canvas.ClipY / 768);
				}
			}

			// don't draw main beacon if clipped out
			if (screenLoc.X < 0 ||
				screenLoc.X >= Canvas.ClipX ||
				screenLoc.Y < 0 ||
				screenLoc.Y >= Canvas.ClipY)
			{
	            // should I register as friendly for crosshair?
	            if ( (HUD != None) && !HUD.bCrosshairOnFriendly )
	            {
		            ScreenLoc = Canvas.Project(Location);
		            MaxOffset = HUDExtent/Dist;
		            if ( (Abs(screenLoc.X - 0.5*Canvas.ClipX) < MaxOffset * Canvas.ClipX)
		            && (Abs(screenLoc.Y - 0.5*Canvas.ClipY) < MaxOffset * Canvas.ClipY) )
		            {
			            HUD.bCrosshairOnFriendly = true;
		            }
	            }
				return;
			}
		}
		else
		{
			if ( !WorldInfo.GRI.GameClass.default.bTeamGame && !bPostRenderOtherTeam )
			{
				return;
			}
			if ( bRequestedEntryWithFlag )
			{
				UTPlayerController(PC).bJustFoundVehicle = false;
			}
			bRequestedEntryWithFlag = false;
		}
	}
	else
	{
		if ( !WorldInfo.GRI.GameClass.default.bTeamGame && !bPostRenderOtherTeam )
		{
			return;
		}
		if ( bRequestedEntryWithFlag )
		{
			UTPlayerController(PC).bJustFoundVehicle = false;
		}
		bRequestedEntryWithFlag = false;
	}

	if ( HUD != None )
	{
		HUD.DrawVehicleBeacon(self, Canvas, ScreenLoc, XL, YL, HealthY, TextXL, Dist, TeamColor, ScreenName, TextColor );
	}

	if ( Dist < TeamBeaconPlayerInfoMaxDist )
	{
		RenderPassengerBeacons(PC, Canvas, TeamColor, TextColor, Weap);
	}

	// should I register as friendly for crosshair?
	if ( (HUD != None) && !HUD.bCrosshairOnFriendly )
	{
		ScreenLoc = Canvas.Project(Location);
		MaxOffset = HUDExtent/Dist;
		if ( (Abs(screenLoc.X - 0.5*Canvas.ClipX) < MaxOffset * Canvas.ClipX)
		&& (Abs(screenLoc.Y - 0.5*Canvas.ClipY) < MaxOffset * Canvas.ClipY) )
		{
			HUD.bCrosshairOnFriendly = true;
		}
	}
}

simulated function float GetDisplayedHealth()
{
	return Health;
}

simulated function RenderPassengerBeacons(PlayerController PC, Canvas Canvas, LinearColor TeamColor, Color TextColor, UTWeapon Weap)
{
	if ( PassengerPRI != None )
	{
		PostRenderPassengerBeacon(PC, Canvas, TeamColor, TextColor, Weap, PassengerPRI, PassengerTeamBeaconOffset);
	}
}

/**
 * PostRenderPassengerBeacon() renders
 * Assumes that appropriate font has already been set
 *
 * @param	PC		The Player Controller who is rendering this pawn
 * @param	Canvas	The canvas to draw on
 */
simulated function PostRenderPassengerBeacon(PlayerController PC, Canvas Canvas, LinearColor TeamColor, Color TextColor, UTWeapon Weap, UTPlayerReplicationInfo InPassengerPRI, vector InPassengerTeamBeaconOffset)
{
	local float TextXL, XL, YL, NumXL, NumYL, FontScale;
	local vector ScreenLoc, X, Y, Z;
	local string NumString;
	local UTHUD HUD;

	GetAxes(Rotation, X, Y, Z);
	ScreenLoc = Canvas.Project(Location + InPassengerTeamBeaconOffset.X * X + InPassengerTeamBeaconOffset.Y * Y + InPassengerTeamBeaconOffset.Z * Z);

	// make sure not clipped out
	if (screenLoc.X < 0 ||
		screenLoc.X >= Canvas.ClipX ||
		screenLoc.Y < 0 ||
		screenLoc.Y >= Canvas.ClipY)
	{
		return;
	}

	// make sure not behind weapon
	if ( (Weap != None) && Weap.CoversScreenSpace(ScreenLoc, Canvas) )
	{
		return;
	}
	else if ( (UTVehicle_Hoverboard(PC.Pawn) != None) && UTVehicle_Hoverboard(PC.Pawn).CoversScreenSpace(ScreenLoc, Canvas) )
	{
		return;
	}

	Canvas.StrLen(InPassengerPRI.GetPlayerAlias(), TextXL, YL);
	XL = TextXL;

	HUD = UTHUD(PC.myHUD);
	if ( HUD != None )
	{
		if ( InPassengerPRI.GetNumCoins() > 0 )
		{
			Canvas.Font = HUD.GetFontSizeIndex(2);
			NumString = string(InPassengerPRI.GetNumCoins());
			Canvas.StrLen(NumString, NumXL, NumYL);
			FontScale = 0.75;
			Canvas.Font = HUD.GetFontSizeIndex(0);
			YL += NumYL * FontScale;
		}

		HUD.DrawBeaconBackground(ScreenLoc.X-0.7*XL,ScreenLoc.Y-1.8*YL,1.4*XL,1.9*YL, TeamColor, Canvas);
		Canvas.DrawColor = TextColor;
		if ( InPassengerPRI.GetNumCoins() > 0 )
		{
			Canvas.Font = HUD.GetFontSizeIndex(2);
			Canvas.SetPos(ScreenLoc.X - 0.5*FontScale*NumXL,ScreenLoc.Y-1.5*NumYL*FontScale);
			Canvas.DrawTextClipped(NumString, true, FontScale, FontScale);
			Canvas.SetPos(ScreenLoc.X-0.5*TextXL,ScreenLoc.Y-1.2*YL);
			Canvas.Font = HUD.GetFontSizeIndex(0);
		}
		else
		{
			Canvas.SetPos(ScreenLoc.X-0.5*TextXL,ScreenLoc.Y-1.2*YL);
		}
		Canvas.DrawTextClipped(InPassengerPRI.GetPlayerAlias(), true);
	}
}

/**
 * Team is changed when vehicle is possessed
 */
event SetTeamNum(byte T)
{
	if ( T != Team )
	{
		Team = T;
		TeamChanged();
	}
}

/**
 * This function is called when the team has changed.  Use it to setup team specific overlays/etc
 *
 * NOTE: the UTVehicle_Scavenger is doing all kinds of crazy special case stuff and does NOT call super.  Make certain that you check
 * UTVehicle_Scavenger.TeamChanged() when making changes here.
 */
simulated function TeamChanged()
{
	local MaterialInterface NewMaterial;

	if (WorldInfo.NetMode != NM_DedicatedServer)
	{
		if (Team < TeamMaterials.length && TeamMaterials[Team] != None)
		{
			NewMaterial = TeamMaterials[Team];
		}
		else if (TeamMaterials.length > 0 && TeamMaterials[0] != None)
		{
			NewMaterial = TeamMaterials[0];
		}

		if (NewMaterial != None)
		{
			if (DamageMaterialInstance[0] != None)
			{
				DamageMaterialInstance[0].SetParent(NewMaterial);
		}
			else
			{
				Mesh.SetMaterial(0, NewMaterial);
			}
		}

		TeamChanged_VehicleEffects();

		UpdateDamageMaterial();
	}
}

/**
 * This function is called when we need to change Vehicle Effects.
 *
 * To get blue effects add this to the VehicleEffects list entry:  EffectTemplate_Blue=ParticleSystem'',
 **/
simulated function TeamChanged_VehicleEffects()
{
	local int Len;
	local int TeamNum;
	local int VehicleEffectIndex;
	local ParticleSystem NewTemplate;

	InitializeEffects();

	TeamNum = GetTeamNum();
	Len = VehicleEffects.length;

	for( VehicleEffectIndex = 0; VehicleEffectIndex < Len; ++VehicleEffectIndex )
	{
		// if we have a blue particle system then we will need to change the system based on team otherwise this vehicle effect doesn't need to be changed
		if (VehicleEffects[VehicleEffectIndex].EffectTemplate_Blue != None && VehicleEffects[VehicleEffectIndex].EffectRef != None)
		{
			NewTemplate = (TeamNum == 1) ? VehicleEffects[VehicleEffectIndex].EffectTemplate_Blue : VehicleEffects[VehicleEffectIndex].EffectTemplate;
			if (VehicleEffects[VehicleEffectIndex].EffectRef.Template != NewTemplate)
			{
				VehicleEffects[VehicleEffectIndex].EffectRef.SetTemplate(NewTemplate);
			}
		}
	}
}



/**
 * Stub out the Dodge event.  Override if the vehicle needs a dodge
 *
 * See Pawn::Dodge()
 */
function bool Dodge(eDoubleClickDir DoubleClickMove);

/**
 * This function is called from an incoming missile that is targetting this vehicle
 *
 * @param P		The incoming projectile
 */
event IncomingMissile(Projectile P)
{
	local AIController C;

	C = AIController(Controller);
	if (C != None && C.Skill >= 5.0 && (C.Enemy == None || !C.LineOfSightTo(C.Enemy)))
	{
		ShootMissile(P);
	}
}

/**
 * AI hint - Shoot at the missle
 *
 * @param P		The incoming projectile
 */

function ShootMissile(Projectile P)
{
	Controller.Focus = P;
	Controller.FireWeaponAt(P);
}

/**
 * sends the LockOn message to all seats in this vehicle with the specified switch
 *
 * @param Switch 	The message switch
 */
simulated function SendLockOnMessage(int Switch)
{
	local int i;
	local Pawn P;

	for (i = 0; i < Seats.length; i++)
	{
		P = Seats[i].SeatPawn;

		if( ( P != none )
			&& (PlayerController(P.Controller) != None)
			&& P.IsLocallyControlled() 
			&& (P.Controller.Pawn == P) // for client side lock warnings
			)
		{
			PlayerController(P.Controller).ReceiveLocalizedMessage(class'UTLockWarningMessage', Switch);
			PlayerController(P.Controller).ClientPlaySound(LockedOnSound);
		}
	}
}

/**
 *  LockOnWarning() called by seeking missiles to warn vehicle they are incoming
 */
simulated event LockOnWarning(UTProjectile IncomingMissile)
{
	SendLockOnMessage(1);
}

/**
 * Check to see if Other is too close to attack
 *
 * @param	Other		Actor to check against
 * @returns true if he's too close
 */

function bool TooCloseToAttack(Actor Other)
{
	local int NeededPitch, i;
	local bool bControlledWeaponPawn;

	if (VSize(Location - Other.Location) > 2500.0)
	{
		return false;
	}

	if (Weapon == None)
	{
		if (Seats.length < 2)
		{
			return false;
		}
		for (i = 0; i < Seats.length; i++)
		{
			if (Seats[i].SeatPawn != None && Seats[i].SeatPawn.Controller != None)
			{
				bControlledWeaponPawn = true;
				if (!Seats[i].SeatPawn.TooCloseToAttack(Other))
				{
					return false;
				}
			}
		}

		return bControlledWeaponPawn;
	}

	NeededPitch = rotator(Other.GetTargetLocation(self) - Weapon.GetPhysicalFireStartLoc()).Pitch & 65535;
	return CheckTurretPitchLimit(NeededPitch, 0);
}

/** checks if the given pitch would be limited by the turret controllers, i.e. we cannot possibly fire in that direction
 * @return whether the pitch would be constrained
 */
function bool CheckTurretPitchLimit(int NeededPitch, int SeatIndex)
{
	local int i;

	if (SeatIndex >= 0)
	{
		if (Seats[SeatIndex].TurretControllers.length > 0)
		{
			for (i = 0; i < Seats[SeatIndex].TurretControllers.Length; i++ )
			{
				if (!Seats[SeatIndex].TurretControllers[i].WouldConstrainPitch(NeededPitch, Mesh))
				{
					return false;
				}
			}

			return true;
		}
		else if (Seats[SeatIndex].Gun != None)
		{
			return (Cos(Abs(NeededPitch - (Rotation.Pitch & 65535)) / 182.0444) > Seats[SeatIndex].Gun.GetMaxFinalAimAdjustment());
		}
	}

	return false;
}

/**
 * Play the horn for this vehicle
 */

function PlayHorn()
{
	local int i, NumPositions;
	local Pawn P;
	local UTPawn UTP;
	local UTVehicle V;

	if (WorldInfo.TimeSeconds - LastHornTime > 1.0 && HornIndex >= 0 && HornIndex < HornSounds.Length)
	{
		PlaySound(HornSounds[HornIndex]);
		LastHornTime = WorldInfo.TimeSeconds;
	}

	if (PlayerController(Controller) != None)
	{
		// if a seat is available, nearby friendly bots respond to horn and try to get in
		for (i = 0; i < Seats.length; i++)
		{
			if (Seats[i].SeatPawn.Controller == None)
			{
				NumPositions++;
			}
		}
		if (NumPositions > 0)
		{
			foreach VisibleCollidingActors(class'Pawn', P, HornAIRadius)
			{
				if (UTBot(P.Controller) != None && WorldInfo.GRI.OnSameTeam(P, self))
				{
					V = UTVehicle(P);
					if (V != None)
					{
						// if bot is on a hoverboard, get off it to respond to horn
						UTP = UTPawn(V.Driver);
						if (UTP != None && UTP.HoverboardClass == V.Class && V.DriverLeave(false))
						{
							P = UTP;
						}
					}
					if (Vehicle(P) == None)
					{
						UTBot(P.Controller).SetTemporaryOrders('Follow', Controller);
						if (--NumPositions == 0)
						{
							break;
						}
					}
				}
			}
		}
	}
}

/**
 * UpdateControllerOnPossess() override Pawn.UpdateControllerOnPossess() to keep from changing controller's rotation
 *
 * @param	bVehicleTransition	Will be true if this the pawn is entering/leaving a vehicle
 */
function UpdateControllerOnPossess(bool bVehicleTransition);

/**
 * @returns the number of passengers in this vehicle
 */
simulated function int NumPassengers()
{
	local int i, Num;

	for (i = 0; i < Seats.length; i++)
	{
		if( (Seats[i].SeatPawn != None)
			&& (Seats[i].SeatPawn.Controller != None)
			)
		{
			Num++;
		}
	}

	return Num;
}

/**
 * AI Hint
 */
function UTVehicle GetMoveTargetFor(Pawn P)
{
	return self;
}

/** handles dealing with any flag the given driver/passenger may be holding */
function HandleEnteringFlag(UTPlayerReplicationInfo EnteringPRI)
{
	if (EnteringPRI.bHasFlag)
	{
		if (!bCanCarryFlag)
		{
			EnteringPRI.GetFlag().Drop();
		}
		else if (!bDriverHoldsFlag)
		{
			AttachFlag(EnteringPRI.GetFlag(), Driver);
		}
	}
}

/**
 * Called when a pawn enters the vehicle
 *
 * @Param P		The Pawn entering the vehicle
 */
function bool DriverEnter(Pawn P)
{
	local UTPlayerController PC;

	P.StopFiring();

	if (Seats[0].Gun != none)
	{
		InvManager.SetCurrentWeapon(Seats[0].Gun);
	}

	Instigator = self;

	if ( !Super.DriverEnter(P) )
		return false;

	HandleEnteringFlag(UTPlayerReplicationInfo(PlayerReplicationInfo));

	SetSeatStoragePawn(0,P);

	if (ParentFactory != None)
	{
		ParentFactory.TriggerEventClass(class'UTSeqEvent_VehicleFactory', None, 3);
	}

	if ( PlayerController(Controller) != None )
	{
		VehicleLostTime = 0;
	}
	StuckCount = 0;
	ResetTime = WorldInfo.TimeSeconds - 1;
	bHasBeenDriven = true;

	if ( bKeyVehicle || (UTVehicle_Deployable(self) != None) )
	{
		// notify any players that have this as their objective
		ForEach WorldInfo.AllControllers(class'UTPlayerController', PC)
		{
			if (PC.LastAutoObjective == self)
			{
				PC.CheckAutoObjective(true);
			}
		}
	}
	return true;
}

/**
 * HoldGameObject() Attach GameObject to mesh.
 * @param 	GameObj 	Game object to hold
 */
simulated event HoldGameObject(UTCarriedObject GameObj)
{
	local UTPawn P;

	GameObj.SetHardAttach(GameObj.default.bHardAttach);
	GameObj.bIgnoreBaseRotation = GameObj.default.bIgnoreBaseRotation;

	if (bDriverHoldsFlag)
	{
		P = UTPawn(Driver);
		if (P != None)
		{
			P.HoldGameObject(GameObj);
		}
	}
	else
	{
		AttachFlag(GameObj, Driver);
	}
}

/**
 * If the driver enters the vehicle with a UTCarriedObject, this event
 * is triggered.
 *
 * @param	FlagActor		The object being carried
 * @param	NewDriver		The driver (may not yet have been set)
 */
simulated function AttachFlag(UTCarriedObject FlagActor, Pawn NewDriver)
{
	if ( FlagActor != None )
	{
		if ( FlagBone == '' )
		{
			FlagActor.BaseBoneName = '';
			FlagActor.BaseSkelComponent = None;
			FlagActor.SetBase(self);
		}
		else
		{
			FlagActor.SetBase(self,,Mesh,FlagBone);
		}
		FlagActor.SetRelativeRotation(FlagRotation);
		FlagActor.SetRelativeLocation(FlagOffset);
	}
}


exec function FixedView(string VisibleMeshes)
{
	local int SeatIdx;
	local UTPawn P;

	// find a local player in one of the seats and pass call onto him
	for (SeatIdx=0; SeatIdx<Seats.length; ++SeatIdx)
	{
		P = UTPawn(Seats[SeatIdx].SeatPawn.Driver);
		if (P != None)
		{
			P.FixedView(VisibleMeshes);
		}
	}
}


/**
 * DriverLeft() called by DriverLeave() after the drive has been taken out of the vehicle
 */
function DriverLeft()
{
	local float Dist;

	Super.DriverLeft();

	if (bNeverReset || ParentFactory == None || Occupied())
	{
		return;
	}

	Dist = VSize(Location - ParentFactory.Location);
	if (Dist >= 2000 && (Dist > 5000 || !FastTrace(ParentFactory.Location, Location)))
	{
		ResetTime = WorldInfo.TimeSeconds + (bKeyVehicle ? 15.0 : 30.0);
	}
}

/**
 * @returns the first available passenger seat, or -1 if there are none available
 */
function int GetFirstAvailableSeat()
{
	local int i;

	for (i = 1; i < Seats.Length; i++)
	{
		if (SeatAvailable(i))
		{
			return i;
		}
	}

	return -1;
}

/**
 * Called when a passenger enters the vehicle
 *
 * @param P				The Pawn entering the vehicle
 * @param SeatIndex		The seat where he is to sit
 */

function bool PassengerEnter(Pawn P, int SeatIndex)
{
	// Restrict someone not on the same team
	if ( WorldInfo.Game.bTeamGame && !WorldInfo.GRI.OnSameTeam(P,self) )
	{
		return false;
	}

	if (SeatIndex <= 0 || SeatIndex >= Seats.Length)
	{
		WarnInternal("Attempted to add a passenger to unavailable passenger seat" @ SeatIndex);
		return false;
	}

	if ( !Seats[SeatIndex].SeatPawn.DriverEnter(p) )
	{
		return false;
	}

	HandleEnteringFlag(UTPlayerReplicationInfo(Seats[SeatIndex].SeatPawn.PlayerReplicationInfo));

	SetSeatStoragePawn(SeatIndex,P);

	bHasBeenDriven = true;
	return true;
}

/**
 * Called when the driver leaves the vehicle
 *
 * @param	bForceLeave		Is true if the driver was forced out
 */

event bool DriverLeave(bool bForceLeave)
{
	local bool bResult;
	local Pawn OldDriver;

	if (!bForceLeave && !bAllowedExit)
	{
		return false;
	}

	OldDriver = Driver;
	bResult = Super.DriverLeave(bForceLeave);
	if (bResult)
	{
		SetSeatStoragePawn(0,None);
//		Seats[0].StoragePawn = None;
		// set Instigator to old driver so if vehicle continues on and runs someone over, the appropriate credit is given
		Instigator = OldDriver;
		if (ParentFactory != None)
		{
			ParentFactory.TriggerEventClass(class'UTSeqEvent_VehicleFactory', None, 4);
		}
	}

	return bResult;
}

/**
 * Called when a passenger leaves the vehicle
 *
 * @param	SeatIndex		Leaving from which seat
 */

function PassengerLeave(int SeatIndex)
{
	SetSeatStoragePawn(SeatIndex, None);
}

/**
 *  Vehicle has been in the middle of nowhere with no driver for a while, so consider resetting it
 */
event CheckReset()
{
	local Pawn P;
	local Controller C;

	if ( Occupied() )
	{
		ResetTime = WorldInfo.TimeSeconds - 1;
		return;
	}

	foreach WorldInfo.AllControllers(class'Controller', C)
	{
		P = C.Pawn;
		if ( P != None && WorldInfo.GRI.OnSameTeam(P, self) && (VSize(Location - P.Location) < 2500.0) )
		{
			if ( (PlayerController(C) != None) || (Instigator == C.Pawn) )
			{
				if ( FastTrace(P.Location + P.GetCollisionHeight() * vect(0,0,1), Location + GetCollisionHeight() * vect(0,0,1)) )
				{
					ResetTime = WorldInfo.TimeSeconds + 10;
					return;
				}
			}
			else if ( C.RouteGoal == self )
			{
				ResetTime = WorldInfo.TimeSeconds + 10;
				return;
			}
		}
	}

	if (bKeyVehicle && Health < HealthMax / 2)
	{
		Died(None, class'DamageType', Location);
	}
	else
	{
		//if factory is active, we want it to spawn new vehicle NOW
		if ( ParentFactory != None )
		{
			ParentFactory.ChildVehicle = None;
			ParentFactory.SpawnVehicle();
			ParentFactory = None; //so doesn't call ParentFactory.VehicleDestroyed() again in Destroyed()
		}

		Destroy();
	}
}

/**
 *  AI code
 */
function bool Occupied()
{
	local int i;

	if ( Controller != None )
		return true;

	for ( i=0; i<Seats.Length; i++ )
		if ( !SeatAvailable(i) )
			return true;

	return false;
}

/**
 * OpenPositionFor() returns true if there is a seat available for P
 *
 * @param P		The Pawn to test for
 * @returns true if open
 */
function bool OpenPositionFor(Pawn P)
{
	local int i;

	if ( UTGame(WorldInfo.Game).JustStarted(20) && (Reservation != None) && (Reservation != P.Controller) && (Reservation.RouteGoal == Self)
		&& (Reservation.Pawn != None) && (VSize(Reservation.Pawn.Location - Location) <= VSize(P.Location - Location)) )
	{
		for ( i=0; i<Seats.Length; i++ )
			if ( SeatAvailable(i) )
				return true;
		return false;
	}

	if ( Controller == None )
		return true;

	if ( !WorldInfo.GRI.OnSameTeam(Controller,P) )
		return false;

	for ( i=0; i<Seats.Length; i++ )
		if ( SeatAvailable(i) )
			return true;

	return false;
}

/**
 * @Returns the TeamIndex of this vehicle
 */
simulated native function byte GetTeamNum();

/**
 * return a value indicating how useful this vehicle is to bots
 *
 * @param S				The Actor who desires this vehicle
 * @param TeamIndex		The Team index of S
 * @param Objective		The objective
 */

function float BotDesireability(UTSquadAI S, int TeamIndex, Actor Objective)
{
	local bool bSameTeam;
	local PlayerController P;

	bSameTeam = (Team == TeamIndex || Team == UTVEHICLE_UNSET_TEAM);
	if ( bSameTeam )
	{
		if ( !bKeyVehicle && (WorldInfo.TimeSeconds < PlayerStartTime) )
		{
			ForEach LocalPlayerControllers(class'PlayerController', P)
				break;
			if ( (P == None) || ((P.Pawn != None) && (Vehicle(P.Pawn) == None)) )
				return 0;
		}
	}
	if ( !bKeyVehicle && !bStationary && (WorldInfo.TimeSeconds < VehicleLostTime) )
		return 0;
	else if (Health <= 0 || bIsDisabled || (bTeamLocked && !bSameTeam) || Occupied())
	{
		return 0;
	}

	if (bKeyVehicle)
		return 100;

	return ((MaxDesireability * 0.5) + (MaxDesireability * 0.5 * (float(Health) / HealthMax)));
}

/**
 * AT Hint
 */

function float ReservationCostMultiplier(Pawn P)
{
	if ( Reservation == P.Controller )
		return 1.0;
	if ( UTGame(WorldInfo.Game).JustStarted(20) && (Reservation != None) && (Reservation.Pawn != None)
		&& (VSize(Reservation.Pawn.Location - Location) <= VSize(P.Location - Location)) )
	{
		return 0;
	}
	if ( (Reservation == None) || (Reservation.Pawn == None) )
		return 1.0;
	if ( (Reservation.MoveTarget == self) && Reservation.InLatentExecution(Reservation.LATENT_MOVETOWARD) )
		return 0;
	return 0.25;
}

/**
 * AI Hint
 */
function bool ChangedReservation(Pawn P)
{
	if ( UTGame(WorldInfo.Game).JustStarted(20) && (Reservation != None) && (Reservation != P.Controller) )
	{
		if ( (Reservation.RouteGoal == Self) && (Reservation.Pawn != None) && (VSize(Reservation.Pawn.Location - Location) <= VSize(P.Location - Location)) )
		{
			return true;
		}
		Reservation = UTBot(P.Controller);
		return false;
	}
	return false;
}

/**
 * AI Hint
 */

function bool SpokenFor(Controller C)
{
	local UTBot B;

	if ( Reservation == None )
		return false;
	if ( (Reservation.Pawn == None) || (Vehicle(Reservation.Pawn) != None) )
	{
		Reservation = None;
		return false;
	}
	if ( ((Reservation.RouteGoal != self && (Reservation.RouteGoal != LastAnchor || LastAnchor == None)) && Reservation.MoveTarget != self)
		|| !Reservation.InLatentExecution(Reservation.LATENT_MOVETOWARD) )
	{
		Reservation = None;
		return false;
	}

	if ( !WorldInfo.GRI.OnSameTeam(Reservation,C) )
		return false;

	B = UTBot(C);
	if ( B == None )
		return true;
	if ( Seats.Length > 0 )
		return ( B.Squad != Reservation.Squad );
	if( UTGame(WorldInfo.Game).JustStarted(20) )
	{
		if ( VSize(Reservation.Pawn.Location - Location) > VSize(C.Pawn.Location - Location) )
			return false;
	}

	return true;
}

/* epic ===============================================
* ::StopsProjectile()
*
* returns true if Projectiles should call ProcessTouch() when they touch this actor
*/
simulated function bool StopsProjectile(Projectile P)
{
	// Don't block projectiles fired from this vehicle
	if ( P.Instigator == self )
		return false;

	// Don't block projectiles fired from turret on this vehicle
	return ( (P.Instigator == None) || (P.Instigator.Base != self) || !P.Instigator.IsA('UTWeaponPawn') );
}

/**
 * AI Hint
 */
function SetReservation(controller C)
{
	if ( !SpokenFor(C) )
		Reservation = UTBot(C);
}

/**
 * AI Hint
 */

function bool TeamLink(int TeamNum)
{
	return (LinkHealMult > 0 && Team == TeamNum && Health > 0);
}


/** called when the link gun hits an Actor that has this vehicle as its Owner
 * @param OwnedActor - the Actor owned by this vehicle that was hit
 * @return whether attempting to link to OwnedActor should be treated as linking to this vehicle
 */
simulated function bool AllowLinkThroughOwnedActor(Actor OwnedActor);

/**
 * This function is called to heal the vehicle
 * @See Actor.HealDamage()
 */

function bool HealDamage(int Amount, Controller Healer, class<DamageType> DamageType)
{
	if ( PlayerController(Healer) != None )
		PlayerStartTime = WorldInfo.TimeSeconds + 3;
	if (Health <= 0 || Health >= HealthMax || Amount <= 0 || Healer == None || !TeamLink(Healer.GetTeamNum()))
		return false;

	Amount = Min(Amount * LinkHealMult, HealthMax - Health);
	Health += Amount;

	if ( (Health >= HealthMax) && (SpawnInSound != None) )
	{
		PlaySound(SpawnInSound);
	}
	bForceNetUpdate = TRUE;

	ApplyMorphHeal(Amount);

	//  Add time to the reset timer if you are healing it.
	if ( ResetTime - WorldInfo.TimeSeconds < 10.0 )
		ResetTime = WorldInfo.TimeSeconds+10.0;

	CheckDamageSmoke();

	return true;
}

function IncrementLinkedToCount()
{
	if (LinkedToCount++ == 0)
	{
		StartLinkedEffect();
	}
}

function DecrementLinkedToCount()
{
	if (--LinkedToCount <= 0)
	{
		LinkedToCount = 0;
		StopLinkedEffect();
	}
}

/** function to call whenever a link gun links to this vehicle (e.g. to heal the Vehicle)*/
protected simulated function StartLinkedEffect()
{
	local MaterialInstanceConstant MIC;
	local LinearColor Red, Blue;
	local int i;

	Red = MakeLinearColor(4.0, 0.1, 0.0, 1.0);
	Blue = MakeLinearColor(0.0, 1.0, 4.0, 1.0);
	for (i = 0; i < Mesh.Materials.Length || i < Mesh.SkeletalMesh.Materials.Length; i++)
	{
		if (i < Mesh.Materials.Length)
		{
			MIC = MaterialInstanceConstant(Mesh.Materials[i]);
		}
		if (MIC == None)
		{
			if (i >= Mesh.Materials.Length || Mesh.Materials[i] == None)
			{
				Mesh.SetMaterial(i, Mesh.SkeletalMesh.Materials[i]);
			}
			MIC = Mesh.CreateAndSetMaterialInstanceConstant(i);
		}
		if (MIC != None)
		{
			MIC.SetVectorParameterValue('Veh_OverlayColor', (Team == 1) ? Blue : Red);
		}
	}
	if (LinkedToAudio == None)
	{
		LinkedToAudio = CreateAudioComponent(LinkedToCue, false, true);
	}
	if (LinkedToAudio != None)
	{
		LinkedToAudio.FadeIn(0.2f, 1.0f);
	}
}

/** function to call when a link gun unlinks */
protected simulated function StopLinkedEffect()
{
	local MaterialInstanceConstant mic;
	local LinearColor Black;
	local int i;

	for (i = 0; i < Mesh.Materials.Length; i++)
	{
		MIC = MaterialInstanceConstant(Mesh.Materials[i]);
		if (MIC != None)
		{
			MIC.SetVectorParameterValue('Veh_OverlayColor',Black);
		}
	}
	PlaySound(LinkedEndSound, true);
	if (LinkedToAudio != None)
	{
		LinkedToAudio.FadeOut(0.1f, 0.0f);
		LinkedToAudio = none;
	}
}

function PlayHit(float Damage, Controller InstigatedBy, vector HitLocation, class<DamageType> damageType, vector Momentum, TraceHitInfo HitInfo)
{
	local UTPlayerController Hearer;
	local class<UTDamageType> UTDamage;

	if (InstigatedBy != None && class<UTDamageType>(DamageType) != None && class<UTDamageType>(DamageType).default.bDirectDamage)
	{
		Hearer = UTPlayerController(InstigatedBy);
		if (Hearer != None)
		{
			Hearer.bAcuteHearing = true;
		}
	}
	//@todo FIXME: play vehicle hit sound here?
	Super.PlayHit(Damage, InstigatedBy, HitLocation, DamageType, Momentum, HitInfo);
	if (Hearer != None)
	{
		Hearer.bAcuteHearing = false;
	}

	if (Damage > 0 || ((Controller != None) && Controller.bGodMode))
	{
		CheckHitInfo( HitInfo, Mesh, Normal(Momentum), HitLocation );

		LastTakeHitInfo.Damage = Damage;
		LastTakeHitInfo.HitLocation = HitLocation;
		LastTakeHitInfo.Momentum = Momentum;
		LastTakeHitInfo.DamageType = DamageType;
		LastTakeHitInfo.HitBone = HitInfo.BoneName;
		UTDamage = class<UTDamageType>(DamageType);
		LastTakeHitTimeout = WorldInfo.TimeSeconds + ( (UTDamage != None) ? UTDamage.static.GetHitEffectDuration(self, Damage)
									: class'UTDamageType'.static.GetHitEffectDuration(self, Damage) );

		PlayTakeHitEffects();
	}
}

/** plays take hit effects; called from PlayHit() on server and whenever LastTakeHitInfo is received on the client */
simulated event PlayTakeHitEffects()
{
	local class<UTDamageType> UTDamage;

	if (EffectIsRelevant(Location, false))
	{
		UTDamage = class<UTDamageType>(LastTakeHitInfo.DamageType);
		if (UTDamage != None)
		{
			UTDamage.static.SpawnHitEffect(self, LastTakeHitInfo.Damage, LastTakeHitInfo.Momentum, LastTakeHitInfo.HitBone, LastTakeHitInfo.HitLocation);
		}
	}

	ApplyMorphDamage(LastTakeHitInfo.HitLocation, LastTakeHitInfo.Damage, LastTakeHitInfo.Momentum);
	ClientHealth -= LastTakeHitInfo.Damage;
}

function NotifyTakeHit(Controller InstigatedBy, vector HitLocation, int Damage, class<DamageType> damageType, vector Momentum)
{
	local int i;

	Super.NotifyTakeHit(InstigatedBy, HitLocation, Damage, DamageType, Momentum);

	// notify anyone in turrets
	for (i = 1; i < Seats.length; i++)
	{
		if (Seats[i].SeatPawn != None)
		{
			Seats[i].SeatPawn.NotifyTakeHit(InstigatedBy, HitLocation, Damage, DamageType, Momentum);
		}
	}
}

/**
 * @See Actor.TakeDamage()
 */
simulated event TakeDamage(int Damage, Controller EventInstigator, vector HitLocation, vector Momentum, class<DamageType> DamageType, optional TraceHitInfo HitInfo, optional Actor DamageCauser)
{
	if (Role == ROLE_Authority)
	{
		if ( (UTPawn(Driver) != None) && UTPawn(Driver).bIsInvulnerable )
			Damage = 0;
		else if ( DamageType == class'UTDmgType_ScorpionSelfDestruct' )
			Damage = class'UTDmgType_ScorpionSelfDestruct'.default.DamageGivenForSelfDestruct;
	}

	Super.TakeDamage(Damage, EventInstigator, HitLocation, Momentum, DamageType, HitInfo, DamageCauser);

	if (Role == ROLE_Authority)
	{
		CheckDamageSmoke();
	}

	if(DamageType == class'UTDmgType_ImpactHammer')
	{
		PlaySound(ImpactHitSound);
	}
}

/** Implementation of TakeHeadShot that iterates over seats checking each person in vehicle. */
function bool TakeHeadShot(const out ImpactInfo Impact, class<UTDamageType> HeadShotDamageType, int HeadDamage, float AdditionalScale, Controller InstigatingController)
{
	local int SeatIndex;
	local UTVehicleBase UTVBase;

	// First call base-class TakeHeadShot (for driver)
	if (Super.TakeHeadShot(Impact, HeadShotDamageType, HeadDamage, AdditionalScale, InstigatingController))
	{
		return true;
	}

	// Now check each seat in the vehicle.
	for (SeatIndex = 0; SeatIndex < Seats.length; SeatIndex++)
	{
		UTVBase = UTVehicleBase(Seats[SeatIndex].SeatPawn);
		if (UTVBase != None && UTVBase != self)
		{
			if (UTVBase.TakeHeadShot(Impact, HeadShotDamageType, HeadDamage, AdditionalScale, InstigatingController))
			{
				return true;
			}
		}
	}

	return false;
}

/**
 * GetHomingTarget is called from projectiles looking to seek to this vehicle.  It returns the actor the projectile should target
 *
 * @param	Seeker			The projectile that seeking this vehcile
 * @param	InstigatedBy	Who is controlling that projectile
 * @returns the target to see
 */
event Actor GetHomingTarget(UTProjectile Seeker, Controller InstigatedBy)
{
	return self;
}

/**
 * AI Hint
 */
function bool IsArtillery()
{
	return false;
}

function bool ImportantVehicle()
{
	return false;
}

/*********************************************************************************************
 * Vehicle Weapons, Drivers and Passengers
 *********************************************************************************************/

/**
 * Create all of the vehicle weapons
 */
function InitializeSeats()
{
	local int i;
	if (Seats.Length==0)
	{
		LogInternal("WARNING: Vehicle ("$self$") **MUST** have at least one seat defined");
		destroy();
		return;
	}

	for(i=0;i<Seats.Length;i++)
	{
		// Seat 0 = Driver Seat.  It doesn't get a WeaponPawn

		if (i>0)
		{
	   		Seats[i].SeatPawn = Spawn(class'UTWeaponPawn');
	   		Seats[i].SeatPawn.SetBase(self);
			Seats[i].Gun = UTVehicleWeapon(Seats[i].SeatPawn.InvManager.CreateInventory(Seats[i].GunClass));
			Seats[i].Gun.SetBase(self);
			Seats[i].SeatPawn.EyeHeight = Seats[i].SeatPawn.BaseEyeheight;
			UTWeaponPawn(Seats[i].SeatPawn).MyVehicleWeapon = Seats[i].Gun;
			UTWeaponPawn(Seats[i].SeatPawn).MyVehicle = self;
	   		UTWeaponPawn(Seats[i].SeatPawn).MySeatIndex = i;

	   		if ( Seats[i].ViewPitchMin != 0.0f )
	   		{
				UTWeaponPawn(Seats[i].SeatPawn).ViewPitchMin = Seats[i].ViewPitchMin;
			}
			else
	   		{
				UTWeaponPawn(Seats[i].SeatPawn).ViewPitchMin = ViewPitchMin;
			}


	   		if ( Seats[i].ViewPitchMax != 0.0f )
	   		{
				UTWeaponPawn(Seats[i].SeatPawn).ViewPitchMax = Seats[i].ViewPitchMax;
			}
			else
	   		{
				UTWeaponPawn(Seats[i].SeatPawn).ViewPitchMax = ViewPitchMax;
			}
		}
		else
		{
			Seats[i].SeatPawn = self;
			Seats[i].Gun = UTVehicleWeapon(InvManager.CreateInventory(Seats[i].GunClass));
			Seats[i].Gun.SetBase(self);
		}

		Seats[i].SeatPawn.DriverDamageMult = Seats[i].DriverDamageMult;
		Seats[i].SeatPawn.bDriverIsVisible = Seats[i].bSeatVisible;

		if (Seats[i].Gun!=none)
		{
			Seats[i].Gun.SeatIndex = i;
			Seats[i].Gun.MyVehicle = self;
		}

		// Cache the names used to access various variables
   	}
}

simulated function PreCacheSeatNames()
{
	local int i;
	for (i=0;i<Seats.Length;i++)
	{
		Seats[i].WeaponRotationName	= NAME( Seats[i].TurretVarPrefix$"WeaponRotation" );
		Seats[i].FlashLocationName	= NAME( Seats[i].TurretVarPrefix$"FlashLocation" );
		Seats[i].FlashCountName		= NAME( Seats[i].TurretVarPrefix$"FlashCount" );
		Seats[i].FiringModeName		= NAME( Seats[i].TurretVarPrefix$"FiringMode" );
	}
}

simulated function InitializeTurrets()
{
	local int Seat, i;
	local UTSkelControl_TurretConstrained Turret;
	local vector PivotLoc, MuzzleLoc;

	if (Mesh == None)
	{
		WarnInternal("No Mesh for" @ self);
	}
	else
	{
		for (Seat = 0; Seat < Seats.Length; Seat++)
		{
			for (i = 0; i < Seats[Seat].TurretControls.Length; i++)
			{
				Turret = UTSkelControl_TurretConstrained( Mesh.FindSkelControl(Seats[Seat].TurretControls[i]) );
				if ( Turret != none )
				{
					Turret.AssociatedSeatIndex = Seat;
					Seats[Seat].TurretControllers[i] = Turret;

					// Initialize turrets to vehicle rotation.
					Turret.InitTurret(Rotation, Mesh);
				}
				else
				{
					WarnInternal("Failed to find skeletal controller named" @ Seats[Seat].TurretControls[i] @ "(Seat "$Seat$") for" @ self @ "in AnimTree" @ Mesh.AnimTreeTemplate);
				}
			}

			if(Role == ROLE_Authority)
			{
				SeatWeaponRotation(Seat, Rotation, FALSE);
			}

			// Calculate Z distance between weapon pivot and muzzle
			PivotLoc = GetSeatPivotPoint(Seat);
			GetBarrelLocationAndRotation(Seat, MuzzleLoc);

			Seats[Seat].PivotFireOffsetZ = MuzzleLoc.Z - PivotLoc.Z;
		}
	}
}

function PossessedBy(Controller C, bool bVehicleTransition)
{
	super.PossessedBy(C,bVehicleTransition);

	if (Seats[0].Gun!=none)
		Seats[0].Gun.ClientWeaponSet(false);
}

simulated function SetFiringMode(byte FiringModeNum)
{
	SeatFiringMode(0, FiringModeNum, false);
}

simulated function ClearFlashCount(Weapon Who)
{
	local UTVehicleWeapon VWeap;

	VWeap = UTVehicleWeapon(Who);
	if (VWeap != none)
	{
		VehicleAdjustFlashCount(VWeap.SeatIndex, SeatFiringMode(VWeap.SeatIndex,,true), true);
	}

}

simulated function IncrementFlashCount(Weapon Who, byte FireModeNum)
{
	local UTVehicleWeapon VWeap;

	VWeap = UTVehicleWeapon(Who);
	if (VWeap != none)
	{
		VehicleAdjustFlashCount(VWeap.SeatIndex, FireModeNum, false);
	}
}

function SetFlashLocation( Weapon Who, byte FireModeNum, vector NewLoc )
{
	local UTVehicleWeapon VWeap;

	VWeap = UTVehicleWeapon(Who);
	if (VWeap != none)
	{
		VehicleAdjustFlashLocation(VWeap.SeatIndex, FireModeNum, NewLoc,  false);
	}
}

/**
 * Reset flash location variable. and call stop firing.
 * Network: Server only
 */
function ClearFlashLocation( Weapon Who )
{
	local UTVehicleWeapon VWeap;

	VWeap = UTVehicleWeapon(Who);
	if (VWeap != none)
	{
		VehicleAdjustFlashLocation(VWeap.SeatIndex, SeatFiringMode(VWeap.SeatIndex,,true), Vect(0,0,0),  true);
	}
}

simulated event GetBarrelLocationAndRotation(int SeatIndex, out vector SocketLocation, optional out rotator SocketRotation)
{
	if (Seats[SeatIndex].GunSocket.Length>0)
	{
		Mesh.GetSocketWorldLocationAndRotation(Seats[SeatIndex].GunSocket[GetBarrelIndex(SeatIndex)], SocketLocation, SocketRotation);
	}
	else
	{
		SocketLocation = Location;
		SocketRotation = Rotation;
	}
}

simulated function vector GetEffectLocation(int SeatIndex)
{
	local vector SocketLocation;

	if ( Seats[SeatIndex].GunSocket.Length == 0 )
		return Location;

	GetBarrelLocationAndRotation(SeatIndex,SocketLocation);
	return SocketLocation;
}

simulated function Vector GetPhysicalFireStartLoc(UTWeapon ForWeapon)
{
	local UTVehicleWeapon VWeap;

	VWeap = UTVehicleWeapon(ForWeapon);
	if ( VWeap != none )
	{
		return GetEffectLocation(VWeap.SeatIndex);
	}
	else
		return location;
}




/**
 * This function returns the aim for the weapon
 */
function rotator GetWeaponAim(UTVehicleWeapon VWeapon)
{
	local vector SocketLocation, CameraLocation, RealAimPoint, DesiredAimPoint, HitLocation, HitRotation, DirA, DirB;
	local rotator CameraRotation, SocketRotation, ControllerAim, AdjustedAim;
	local float DiffAngle, MaxAdjust;
	local Controller C;
	local PlayerController PC;
	local Quat Q;

	if ( VWeapon != none )
	{
		C = Seats[VWeapon.SeatIndex].SeatPawn.Controller;

		PC = PlayerController(C);
		if (PC != None)
		{
			PC.GetPlayerViewPoint(CameraLocation, CameraRotation);
			DesiredAimPoint = CameraLocation + Vector(CameraRotation) * VWeapon.GetTraceRange();
			if (Trace(HitLocation, HitRotation, DesiredAimPoint, CameraLocation) != None)
			{
				DesiredAimPoint = HitLocation;
			}
		}
		else if (C != None)
		{
			DesiredAimPoint = C.FocalPoint;
		}

		if ( Seats[VWeapon.SeatIndex].GunSocket.Length>0 )
		{
			GetBarrelLocationAndRotation(VWeapon.SeatIndex, SocketLocation, SocketRotation);
			if(VWeapon.bIgnoreSocketPitchRotation || ((DesiredAimPoint.Z - Location.Z)<0 && VWeapon.bIgnoreDownwardPitch))
			{
				SocketRotation.Pitch = Rotator(DesiredAimPoint - Location).Pitch;
			}
		}
		else
		{
			SocketLocation = Location;
			SocketRotation = Rotator(DesiredAimPoint - Location);
		}

		RealAimPoint = SocketLocation + Vector(SocketRotation) * VWeapon.GetTraceRange();
		DirA = normal(DesiredAimPoint - SocketLocation);
		DirB = normal(RealAimPoint - SocketLocation);
		DiffAngle = ( DirA dot DirB );
		MaxAdjust = VWeapon.GetMaxFinalAimAdjustment();
		if ( DiffAngle >= MaxAdjust )
		{
			// bit of a hack here to make bot aiming and single player autoaim work
			ControllerAim = (C != None) ? C.Rotation : Rotation;
			AdjustedAim = VWeapon.GetAdjustedAim(SocketLocation);
			if (AdjustedAim == VWeapon.Instigator.GetBaseAimRotation() || AdjustedAim == ControllerAim)
			{
				// no adjustment
				return rotator(DesiredAimPoint - SocketLocation);
			}
			else
			{
				// FIXME: AdjustedAim.Pitch = Instigator.LimitPitch(AdjustedAim.Pitch);
				return AdjustedAim;
			}
		}
		else
		{
			Q = QuatFromAxisAndAngle(Normal(DirB cross DirA), ACos(MaxAdjust));
			return Rotator( QuatRotateVector(Q,DirB));
		}
	}
	else
	{
		return Rotation;
	}
}

/** Gives the vehicle an opportunity to override the functionality of the given fire mode, called on both the owning client and the server
	@return false to allow the vehicle weapon to use its behavior, true to override it */
simulated function bool OverrideBeginFire(byte FireModeNum);
simulated function bool OverrideEndFire(byte FireModeNum);

/**
 * GetWeaponViewAxes should be subclassed to support returningthe rotator of the various weapon points.
 */
simulated function GetWeaponViewAxes( UTWeapon WhichWeapon, out vector xaxis, out vector yaxis, out vector zaxis )
{
	GetAxes( Controller.Rotation, xaxis, yaxis, zaxis );
}

/**
 * Causes the muzzle flashlight to turn on and setup a time to
 * turn it back off again.
 */
simulated function CauseMuzzleFlashLight(int SeatIndex)
{
	// must have valid gunsocket
	if (Seats[SeatIndex].GunSocket.Length == 0 || bDeadVehicle)
		return;

	// only enable muzzleflash light if performance is high enough
	if ( !WorldInfo.bDropDetail || (Seats[SeatIndex].SeatPawn != None && PlayerController(Seats[SeatIndex].SeatPawn.Controller) != None && Seats[SeatIndex].SeatPawn.IsLocallyControlled()) )
	{
		if ( Seats[SeatIndex].MuzzleFlashLight == None )
		{
			if ( Seats[SeatIndex].MuzzleFlashLightClass != None )
			{
				Seats[SeatIndex].MuzzleFlashLight = new(Outer) Seats[SeatIndex].MuzzleFlashLightClass;
			}
		}
		else
		{
			Seats[SeatIndex].MuzzleFlashLight.ResetLight();
		}

		// FIXMESTEVE: OFFSET!

		if ( Seats[SeatIndex].MuzzleFlashLight != none )
		{
			Mesh.DetachComponent(Seats[SeatIndex].MuzzleFlashLight);
			Mesh.AttachComponentToSocket(Seats[SeatIndex].MuzzleFlashLight, Seats[SeatIndex].GunSocket[GetBarrelIndex(SeatIndex)]);
		}
	}
}

simulated function WeaponFired( bool bViaReplication, optional vector HitLocation)
{
	VehicleWeaponFired(bViaReplication, HitLocation, 0);
}

/**
 * Vehicle will want to override WeaponFired and pass off the effects to the proper Seat
 */
simulated function VehicleWeaponFired( bool bViaReplication, vector HitLocation, int SeatIndex )
{
	// Trigger any vehicle Firing Effects
	if ( WorldInfo.NetMode != NM_DedicatedServer )
	{
		VehicleWeaponFireEffects(HitLocation, SeatIndex);

		if (Role == ROLE_Authority || bViaReplication)
		{
			VehicleWeaponImpactEffects(HitLocation, SeatIndex);
		}

		if (SeatIndex == 0)
		{
			Seats[SeatIndex].Gun = UTVehicleWeapon(Weapon);
		}
		if (Seats[SeatIndex].Gun != None)
		{
			Seats[SeatIndex].Gun.ShakeView();
		}
		if ( EffectIsRelevant(Location,false,MaxFireEffectDistance) )
		{
			CauseMuzzleFlashLight(SeatIndex);
		}
	}
}

simulated function WeaponStoppedFiring( bool bViaReplication )
{
	VehicleWeaponStoppedFiring(bViaReplication, 0);
}

simulated function VehicleWeaponStoppedFiring( bool bViaReplication, int SeatIndex )
{
	local name StopName;

	// Trigger any vehicle Firing Effects
	if ( WorldInfo.NetMode != NM_DedicatedServer )
	{
		if (Role == ROLE_Authority || bViaReplication)
		{
			StopName = Name( "STOP_"$Seats[SeatIndex].GunClass.static.GetFireTriggerTag( GetBarrelIndex(SeatIndex) , SeatFiringMode(SeatIndex,,true) ) );
			VehicleEvent( StopName );
		}
	}
}

/**
 * This function should be subclassed and manage the different effects
 */
simulated function VehicleWeaponFireEffects(vector HitLocation, int SeatIndex)
{
	VehicleEvent( Seats[SeatIndex].GunClass.static.GetFireTriggerTag( GetBarrelIndex(SeatIndex), SeatFiringMode(SeatIndex,,true) ) );
}

/**
 * This function is here so that children vehicles can get access to the retrace to get the hitnormal.  See the Dark Walker
 */

simulated function actor FindWeaponHitNormal(out vector HitLocation, out Vector HitNormal, vector End, vector Start, out TraceHitInfo HitInfo)
{
	return Trace(HitLocation, HitNormal, End, Start, true,, HitInfo, TRACEFLAG_Bullet);
}

/**
 * Spawn any effects that occur at the impact point.  It's called from the pawn.
 */
simulated function VehicleWeaponImpactEffects(vector HitLocation, int SeatIndex)
{
	local vector NewHitLoc, HitNormal, LightLoc;
	local Actor HitActor;
	local TraceHitInfo HitInfo;
	local MaterialImpactEffect ImpactEffect;
	local MaterialInterface MI;
	local MaterialInstanceTimeVarying MITV_Decal;
	local int DecalMaterialsLength;
	local Vehicle V;
	local Pawn EffectInstigator;
	local UTPlayerController PC;

	HitNormal = Normal(Location - HitLocation);
	HitActor = FindWeaponHitNormal(NewHitLoc, HitNormal, (HitLocation - (HitNormal * 32)), HitLocation + (HitNormal * 32),HitInfo);

	if ( (HitActor == None) && (VSize(Location - HitLocation) > 10000) )
	{
		return;
	}

	if (Pawn(HitActor) != None)
	{
		CheckHitInfo(HitInfo, Pawn(HitActor).Mesh, -HitNormal, NewHitLoc);
	}
	// figure out the impact effect to use
	ImpactEffect = Seats[SeatIndex].GunClass.static.GetImpactEffect(HitActor, HitInfo.PhysMaterial, SeatFiringMode(SeatIndex,, true));
	if (ImpactEffect.Sound != None)
	{
		// if hit a vehicle controlled by the local player, always play it full volume
		V = Vehicle(HitActor);
		if (V != None && V.IsLocallyControlled() && V.IsHumanControlled())
		{
			PlayerController(V.Controller).ClientPlaySound(ImpactEffect.Sound);
		}
		else
		{
			if ( (Seats[SeatIndex].GunClass.default.BulletWhip != None) && (WorldInfo.GRI != None) )
			{
				ForEach LocalPlayerControllers(class'UTPlayerController', PC)
				{
					if (!WorldInfo.GRI.OnSameTeam(self, PC))
					{
						PC.CheckBulletWhip(Seats[SeatIndex].GunClass.default.BulletWhip, Location, Normal(HitLocation - Location), HitLocation);
					}
				}
			}
			PlaySound(ImpactEffect.Sound, true,,, HitLocation);
		}
	}

	EffectInstigator = Seats[SeatIndex].SeatPawn;
	if (EffectInstigator == None)
	{
		EffectInstigator = self;
	}
	if (EffectInstigator.EffectIsRelevant(HitLocation, false, MaxImpactEffectDistance))
	{
		// Pawns handle their own hit effects
		if (HitActor != None && (Pawn(HitActor) == None || Vehicle(HitActor) != None))
		{
			// this code is mostly duplicated in:  UTGib, UTProjectile, UTVehicle, UTWeaponAttachment be aware when updating
			if ( !WorldInfo.bDropDetail && (Pawn(HitActor) == None) )
			{
				// if we have a decal to spawn on impact
				DecalMaterialsLength = ImpactEffect.DecalMaterials.length;
				if( DecalMaterialsLength > 0 )
				{
					MI = ImpactEffect.DecalMaterials[Rand(DecalMaterialsLength)];
					if( MI != None )
					{
						if( MaterialInstanceTimeVarying(MI) != none )
						{
							MITV_Decal = new(self) class'MaterialInstanceTimeVarying';
							MITV_Decal.SetParent( MI );

							WorldInfo.MyDecalManager.SpawnDecal( MITV_Decal, HitLocation, rotator(-HitNormal), ImpactEffect.DecalWidth,
								ImpactEffect.DecalHeight, 10.0, false,, HitInfo.HitComponent, true, false, HitInfo.BoneName, HitInfo.Item, HitInfo.LevelIndex );
							//here we need to see if we are an MITV and then set the burn out times to occur
							MITV_Decal.SetScalarStartTime( ImpactEffect.DecalDissolveParamName, ImpactEffect.DurationOfDecal );
						}
						else
						{
							WorldInfo.MyDecalManager.SpawnDecal( MI, HitLocation, rotator(-HitNormal), ImpactEffect.DecalWidth,
								ImpactEffect.DecalHeight, 10.0, false,, HitInfo.HitComponent, true, false, HitInfo.BoneName, HitInfo.Item, HitInfo.LevelIndex );
						}
					}
				}
			}

			if (ImpactEffect.ParticleTemplate != None)
			{
				SpawnImpactEmitter(HitLocation, HitNormal, ImpactEffect, SeatIndex );
				if ( (Seats[SeatIndex].ImpactFlashLightClass != None) && (WorldInfo.GetDetailMode() != DM_Low) && !class'Engine'.static.IsSplitScreen()
					&& (!WorldInfo.bDropDetail || (Seats[SeatIndex].SeatPawn != None && PlayerController(Seats[SeatIndex].SeatPawn.Controller) != None && Seats[SeatIndex].SeatPawn.IsLocallyControlled())) )
				{
					LightLoc = HitLocation + ((0.5 * Seats[SeatIndex].ImpactFlashLightClass.default.TimeShift[0].Radius * vect(1,0,0)) >> rotator(HitNormal));
					UTEmitterPool(WorldInfo.MyEmitterPool).SpawnExplosionLight(Seats[SeatIndex].ImpactFlashLightClass, LightLoc);
				}
			}
		}
	}
}

simulated function SpawnImpactEmitter(vector HitLocation, vector HitNormal, const out MaterialImpactEffect ImpactEffect, int SeatIndex)
{
	WorldInfo.MyEmitterPool.SpawnEmitter(ImpactEffect.ParticleTemplate, HitLocation, rotator(HitNormal));
}

/**
 * These two functions needs to be subclassed in each weapon
 */
simulated function VehicleAdjustFlashCount(int SeatIndex, byte FireModeNum, optional bool bClear)
{
	if (bClear)
	{
		SeatFlashCount( SeatIndex, 0 );
		VehicleWeaponStoppedFiring( false, SeatIndex );
	}
	else
	{
		SeatFiringMode(SeatIndex,FireModeNum);
		SeatFlashCount( SeatIndex, SeatFlashCount(SeatIndex,,true)+1 );
		VehicleWeaponFired( false, vect(0,0,0), SeatIndex );
		Seats[SeatIndex].BarrelIndex++;
	}

	bForceNetUpdate = TRUE;	// Force replication
}

simulated function VehicleAdjustFlashLocation(int SeatIndex, byte FireModeNum, vector NewLocation, optional bool bClear)
{
	if (bClear)
	{
		SeatFlashLocation( SeatIndex, Vect(0,0,0) );
		VehicleWeaponStoppedFiring( false, SeatIndex );
	}
	else
	{
		// Make sure 2 consecutive flash locations are different, for replication
		if( NewLocation == SeatFlashLocation(SeatIndex,,true) )
		{
			NewLocation += vect(0,0,1);
		}

		// If we are aiming at the origin, aim slightly up since we use 0,0,0 to denote
		// not firing.
		if( NewLocation == vect(0,0,0) )
		{
			NewLocation = vect(0,0,1);
		}

		SeatFiringMode(SeatIndex,FireModeNum);
		SeatFlashLocation( SeatIndex, NewLocation );
		VehicleWeaponFired( false, NewLocation, SeatIndex );
		Seats[SeatIndex].BarrelIndex++;
	}


	bForceNetUpdate = TRUE;	// Force replication
}

/** Used by PlayerController.FindGoodView() in RoundEnded State */
simulated function FindGoodEndView(PlayerController PC, out Rotator GoodRotation)
{
	local vector cameraLoc;
	local rotator cameraRot, ViewRotation;
	local int tries;
	local float bestdist, newdist, FOVAngle;

	ViewRotation = GoodRotation;
	ViewRotation.Pitch = 56000;
	tries = 0;
	bestdist = 0.0;
	for (tries=0; tries<16; tries++)
	{
		cameraLoc = Location;
		cameraRot = ViewRotation;
		CalcCamera( 0, cameraLoc, cameraRot, FOVAngle );
		newdist = VSize(cameraLoc - Location);
		if (newdist > bestdist)
		{
			bestdist = newdist;
			GoodRotation = cameraRot;
		}
		ViewRotation.Yaw += 4096;
	}
}

/**
 * We override CalcCamera so as to use the Camera Distance of the seat
 */
simulated function bool CalcCamera(float DeltaTime, out vector out_CamLoc, out rotator out_CamRot, out float out_FOV)
{
    local vector out_CamStart;

	VehicleCalcCamera(DeltaTime, 0, out_CamLoc, out_CamRot, out_CamStart);
	return true;
}

/**
  * returns the camera focus position (without camera lag)
  */
simulated function vector GetCameraFocus(int SeatIndex)
{
	local vector CamStart, HitLocation, HitNormal;
	local actor HitActor;

	//  calculate camera focus
	if ( !bDeadVehicle && Seats[SeatIndex].CameraTag != '' )
	{
		Mesh.GetSocketWorldLocationAndRotation(Seats[SeatIndex].CameraTag, CamStart);

		// Do a line check from actor location to this socket. If we hit the world, use that location instead.
		HitActor = Trace(HitLocation, HitNormal, CamStart, Location, FALSE, vect(12,12,12));
		if( HitActor != None )
		{
			CamStart = HitLocation;
		}
	}
	else
	{
		CamStart = Location;
	}
	CamStart += (Seats[SeatIndex].CameraBaseOffset >> Rotation);
	//DrawDebugSphere(CamStart, 8, 10, 0, 255, 0, FALSE);
	//DrawDebugSphere(Location, 8, 10, 255, 255, 0, FALSE);
	return CamStart;
}

/**
  * returns the camera focus position (adjusted for camera lag)
  */
simulated function vector GetCameraStart(int SeatIndex)
{
	local int i, len, obsolete;
	local vector CamStart;
	local float OriginalCamZ;
	local TimePosition NewPos, PrevPos;
	local float DeltaTime;

	// If we've already updated the cameraoffset, just return it
	len = OldPositions.Length;
	if (len > 0 && SeatIndex == 0 && OldPositions[len-1].Time == WorldInfo.TimeSeconds)
	{
		return CameraOffset + Location;
	}

	CamStart = GetCameraFocus(SeatIndex);
	OriginalCamZ = CamStart.Z;
	if (CameraLag == 0 || SeatIndex != 0 || !IsHumanControlled())
	{
		return CamStart;
	}

	// cache our current location
	NewPos.Time = WorldInfo.TimeSeconds;
	NewPos.Position = CamStart;
	OldPositions[len] = NewPos;

	// if no old locations saved, return offset
	if ( len == 0 )
	{
		CameraOffset = CamStart - Location;
		return CamStart;
	}
	DeltaTime = (len > 1) ? (WorldInfo.TimeSeconds - OldPositions[len-2].Time) : 0.0;

	len = OldPositions.Length;
	obsolete = 0;
	for ( i=0; i<len; i++ )
	{
		if ( OldPositions[i].Time < WorldInfo.TimeSeconds - CameraLag )
		{
			PrevPos = OldPositions[i];
			obsolete++;
		}
		else
		{
			if ( Obsolete > 0 )
			{
				// linear interpolation to maintain same distance in past
				if ( (i == 0) || (OldPositions[i].Time - PrevPos.Time > 0.2) )
				{
					CamStart = OldPositions[i].Position;
				}
				else
				{
					CamStart = PrevPos.Position + (OldPositions[i].Position - PrevPos.Position)*(WorldInfo.TimeSeconds - CameraLag - PrevPos.Time)/(OldPositions[i].Time - PrevPos.Time);
				}
				if ( Obsolete > 1)
					OldPositions.Remove(0, obsolete-1);
			}
			else
			{
				CamStart = OldPositions[i].Position;
			}
			// need to smooth camera to vehicle distance, since vehicle update rate not synched with frame rate
			if ( DeltaTime > 0 )
			{
				DeltaTime *= CameraSmoothingFactor;
				CameraOffset = (CamStart - Location)*DeltaTime + CameraOffset*(1-DeltaTime);
				if ( bNoZSmoothing )
				{
					// don't smooth z - want it bouncy
					CameraOffset.Z = CamStart.Z - Location.Z;
				}
			}
			else
			{
				CameraOffset = CamStart - Location;
			}
			CamStart = CameraOffset + Location;
			if ( bLimitCameraZLookingUp )
			{
				CamStart.Z = LimitCameraZ(CamStart.Z, OriginalCamZ, SeatIndex);
			}
			return CamStart;
		}
	}
	CamStart = OldPositions[len-1].Position;
	if ( bLimitCameraZLookingUp )
	{
		CamStart.Z = LimitCameraZ(CamStart.Z, OriginalCamZ, SeatIndex);
	}
	return CamStart;
}


/**
  * returns the camera focus position (adjusted for camera lag)
  */
simulated function float LimitCameraZ(float CurrentCamZ, float OriginalCamZ, int SeatIndex)
{
	local rotator CamRot;
	local float Pct;

	CamRot = Seats[SeatIndex].SeatPawn.GetViewRotation();
	CamRot.Pitch = CamRot.Pitch & 65535;
	if ( (CamRot.Pitch < 32768) )
	{
		Pct = FClamp(float(CamRot.Pitch)*0.00025, 0.0, 1.0);
		CurrentCamZ = OriginalCamZ*Pct + CurrentCamZ*(1.0-Pct);
	}
	return CurrentCamZ;
}

simulated function VehicleCalcCamera(float DeltaTime, int SeatIndex, out vector out_CamLoc, out rotator out_CamRot, out vector CamStart, optional bool bPivotOnly)
{
	local vector CamPos, CamDir, HitLocation, FirstHitLocation, HitNormal, CamRotX, CamRotY, CamRotZ, SafeLocation, X, Y, Z;
	local actor HitActor;
	local float NewCamStartZ;
	local UTPawn P;
	local bool bObstructed, bInsideVehicle;

	Mesh.SetOwnerNoSee(false);
	if ( (UTPawn(Driver) != None) && !Driver.bHidden && Driver.Mesh.bOwnerNoSee )
		UTPawn(Driver).SetMeshVisibility(true);

	// Handle the fixed view
	P = UTPawn(Seats[SeatIndex].SeatPawn.Driver);
	if (P != None && P.bFixedView)
	{
		out_CamLoc = P.FixedViewLoc;
		out_CamRot = P.FixedViewRot;
		return;
	}

	CamStart = GetCameraStart(SeatIndex);

	// Get the rotation
	if ( (Seats[SeatIndex].SeatPawn.Controller != None) && !bSpectatedView  )
	{
		out_CamRot = Seats[SeatIndex].SeatPawn.GetViewRotation();
	}

	// support debug 3rd person cam
	if (P != None)
	{
		P.ModifyRotForDebugFreeCam(out_CamRot);
	}

	GetAxes(out_CamRot, CamRotX, CamRotY, CamRotZ);
	CamStart += (Seats[SeatIndex].SeatPawn.EyeHeight + LookForwardDist * FMax(0,(1.0 - CamRotZ.Z)))* CamRotZ;

	/* if bNoFollowJumpZ, Z component of Camera position is fixed during a jump */
	if ( bNoFollowJumpZ )
	{
		NewCamStartZ = CamStart.Z;
		if ( (Velocity.Z > 0) && !HasWheelsOnGround() && (OldCamPosZ != 0) )
		{
			// upward part of jump. Fix camera Z position.
			bFixedCamZ = true;
			if ( OldPositions.Length > 0 )
				OldPositions[OldPositions.Length-1].Position.Z += (OldCamPosZ - CamStart.Z);
			CamStart.Z = OldCamPosZ;
			if ( NewCamStartZ - CamStart.Z > 64 )
				CamStart.Z = NewCamStartZ - 64;
		}
		else if ( bFixedCamZ )
		{
			// Camera z position is being fixed, now descending
			if ( HasWheelsOnGround() || (CamStart.Z <= OldCamPosZ) )
			{
				// jump has ended
				if ( DeltaTime >= 0.1 )
				{
					// all done
					bFixedCamZ = false;
				}
				else
				{
					// Smoothly return to normal camera mode.
					CamStart.Z = 10*DeltaTime*CamStart.Z + (1 - 10*DeltaTime)*OldCamPosZ;
					if ( abs(NewCamStartZ - CamStart.Z) < 1.f )
						bFixedCamZ = false;
				}
			}
			else
			{
				// descending from jump, still in the air, so fix camera Z position
				if ( OldPositions.Length > 0 )
					OldPositions[OldPositions.Length-1].Position.Z += (OldCamPosZ - CamStart.Z);
				CamStart.Z = OldCamPosZ;
			}
		}
	}

	// Trace up to the view point to make sure it's not obstructed.
	if ( Seats[SeatIndex].CameraSafeOffset == vect(0,0,0) )
	{
		SafeLocation = Location;
	}
	else
	{
	    GetAxes(Rotation, X, Y, Z);
	    SafeLocation = Location + Seats[SeatIndex].CameraSafeOffset.X * X + Seats[SeatIndex].CameraSafeOffset.Y * Y + Seats[SeatIndex].CameraSafeOffset.Z * Z;
	}
	// DrawDebugSphere(SafeLocation, 16, 10, 255, 0, 255, FALSE);
	// DrawDebugSphere(CamStart, 16, 10, 255, 255, 0, FALSE);

	HitActor = Trace(HitLocation, HitNormal, CamStart, SafeLocation, false, vect(12, 12, 12));
	if ( HitActor != None)
	{
			bObstructed = true;
			CamStart = HitLocation;
			//`log("obstructed 0");
	}

	OldCamPosZ = CamStart.Z;
	if (bPivotOnly)
	{
		out_CamLoc = CamStart;
		return;
	}

	// Calculate the optimal camera position
	CamDir = CamRotX * Seats[SeatIndex].CameraOffset * SeatCameraScale;

	// keep camera from going below vehicle
	if ( !bRotateCameraUnderVehicle && (CamDir.Z < 0) )
	{
		CamDir *= (VSize(CamDir) - abs(CamDir.Z))/(VSize(CamDir) + abs(CamDir.Z));
	}

	CamPos = CamStart + CamDir;

	// Adjust for obstructions
	HitActor = Trace(HitLocation, HitNormal, CamPos, CamStart, false, vect(12, 12, 12));

	if ( HitActor != None )
	{
		out_CamLoc = HitLocation;
		bObstructed = true;
		//`log("obstructed 2");
	}
	else
	{
		out_CamLoc = CamPos;
	}
	if ( !bRotateCameraUnderVehicle && (CamDir.Z < 0) && TraceComponent( FirstHitLocation, HitNormal, CollisionComponent, out_CamLoc, CamStart, vect(0,0,0)) )
	{
		// going through vehicle - it's ok if outside collision on other side
		if ( !TraceComponent( HitLocation, HitNormal, CollisionComponent, CamStart, out_CamLoc, vect(0,0,0)) )
		{
			// end point is inside collision - that's bad
			out_CamLoc = FirstHitLocation;
			bObstructed = true;
			bInsideVehicle = true;
			//`log("obstructed 1");
		}
	}

	// if trace doesn't hit collisioncomponent going back in, it means we are inside the collision box
	// in which case we want to hide the vehicle
	if ( !bCameraNeverHidesVehicle && bObstructed )
	{
		bInsideVehicle = bInsideVehicle
						|| !TraceComponent( HitLocation, HitNormal, CollisionComponent, SafeLocation, out_CamLoc, vect(0,0,0))
						|| (VSizeSq(HitLocation - out_CamLoc) < MinCameraDistSq);
		Mesh.SetOwnerNoSee(bInsideVehicle);
		if ( (UTPawn(Driver) != None) && !Driver.bHidden && (Driver.Mesh.bOwnerNoSee != Mesh.bOwnerNoSee) )
		{
			// Handle the main player mesh
			Driver.Mesh.SetOwnerNoSee(Mesh.bOwnerNoSee);
		}
	}
}

/** moves the camera in or out */
simulated function AdjustCameraScale(bool bMoveCameraIn)
{
	//SeatCameraScale = FMax(0.0, SeatCameraScale + (bMoveCameraIn ? -0.1 : 0.1));
	//`log("New camera scale "$SeatCameraScale);
}


simulated function StartBurnOut()
{
	local int i;
	local int NumBurnOutMaterials;

	// here we need to check to see if we are a vehicle which is falling down from the sky!
	// if we are then we want to push the actual burn out til after we have hit the ground (and possibly do a secondary explosion)
	if( Velocity.Z < -100.0f )
	{
		DelayedBurnoutCount++;
		if ( DelayedBurnoutCount < 6 )
		{
			SetTimer( 1.0f, false, 'StartBurnOut' );
			LifeSpan += 1.0f;
			return;
		}
	}

	if (SpawnOutSound != none)
	{
		PlaySound( SpawnOutSound, TRUE );
	}

	bIsBurning = TRUE;
	SetTimer( 0.500, FALSE, 'DisableCollision' ); // turn off collision quicker rather than slower for when vehicles are burning out
	DisableDamageSmoke();
	StopVehicleSounds();

	NumBurnOutMaterials = BurnOutMaterialInstances.length;
	for( i = 0; i < NumBurnOutMaterials; ++i )
	{
		if( BurnOutMaterialInstances[i].MITV != None )
		{
			//`log( NumBurnOutMaterials $ " starting burnout on: " $ BurnOutMaterialInstances[i].MITV $ " " $ self );
			 BurnOutMaterialInstances[i].MITV.SetScalarStartTime( 'BurnTime', 0.0f );
		}
	}

	// these will turn off the damage Particle Effects (smoke/fire/sparks)
	VehicleEvent( 'NoDamageSmoke' );
	if( DeathExplosion != none )
	{
		DeathExplosion.ParticleSystemComponent.DeactivateSystem();
	}

	// wait a few before turning off shadows (this reduces the jarring pop that you see if everything happens all at once)
	SetTimer( 0.5f, FALSE, 'TurnOffShadows' );
}

/** This will turn off the shadow casting of the vehicle **/
simulated function TurnOffShadows()
{
	// turn off any shadows we have
	UpdateShadowSettings( FALSE );
	//Mesh.CastShadow = FALSE;
	//DynamicLightEnvironmentComponent(Mesh.LightEnvironment).bCastShadows = FALSE;
}


/** deactivates smoke/fire emitter when vehicle is mostly burned out */
simulated function DisableDamageSmoke()
{
	VehicleEvent('NoDamageSmoke');
}

/** turns off collision on the vehicle when it's almost fully burned out */
simulated function DisableCollision()
{
	SetCollision(false);
	Mesh.SetBlockRigidBody(false);
}

simulated function SetBurnOut()
{
	local int i, NumElements;
	local int TeamNum;
	local BurnOutDatum BOD;
	local UTCarriedObject Flag;

	if ( LifeSpan != 0 )
		return;

	TeamNum = GetTeamNum();

	if( TeamNum > 1 )
	{
		TeamNum = 0;
	}

	// burn out immediately if parked on flag
	ForEach TouchingActors(class'UTCarriedObject', Flag)
	{
		DeadVehicleLifeSpan = BurnOutTime + 0.01;
		break;
	}
	LifeSpan = DeadVehicleLifeSpan;

	// set up material instance (for burnout effects)
	if (BurnOutMaterial[TeamNum] != None)
	{
		Mesh.SetMaterial(0,BurnOutMaterial[TeamNum]);
		if(DestroyedTurret != none)
		{
			DestroyedTurret.GibMeshComp.SetMaterial(0,BurnOutMaterial[TeamNum]);
		}
	}

	NumElements = Mesh.GetNumElements();
	for (i = 0; i < NumElements; i++)
	{
		BOD.MITV = Mesh.CreateAndSetMaterialInstanceTimeVarying(i);
		BurnOutMaterialInstances[BurnOutMaterialInstances.length] = BOD;

		if(DestroyedTurret != none)
		{
			DestroyedTurret.GibMeshComp.SetMaterial(i,BurnOutMaterialInstances[i].MITV);
		}
	}
	RemainingBurn = BurnOutTime;
	SetTimer(LifeSpan - BurnOutTime, false, 'StartBurnOut');
}

/** ShouldSpawnExplosionLight()
Decide whether or not to create an explosion light for this explosion
*/
simulated function bool ShouldSpawnExplosionLight(vector HitLocation, vector HitNormal)
{
	local PlayerController P;
	local float Dist;

	// decide whether to spawn explosion light
	ForEach LocalPlayerControllers(class'PlayerController', P)
	{
		Dist = VSize(P.ViewTarget.Location - Location);
		if ( (P.Pawn == Instigator) || (Dist < ExplosionLightClass.Default.Radius) || ((Dist < MaxExplosionLightDistance) && ((vector(P.Rotation) dot (Location - P.ViewTarget.Location)) > 0)) )
		{
			return true;
		}
	}
	return false;
}

simulated state DyingVehicle
{
	ignores Bump, HitWall, HeadVolumeChange, PhysicsVolumeChange, Falling, BreathTimer, FellOutOfWorld;

	simulated function PlayWeaponSwitch(Weapon OldWeapon, Weapon NewWeapon) {}
	simulated function PlayNextAnimation() {}
	singular event BaseChange() {}
	event Landed(vector HitNormal, Actor FloorActor) {}

	function bool Died(Controller Killer, class<DamageType> damageType, vector HitLocation);

	simulated event PostRenderFor(PlayerController PC, Canvas Canvas, vector CameraPosition, vector CameraDir) {}

	simulated function BlowupVehicle() {}

	simulated function CheckDamageSmoke();

	/** spawn an explosion effect and damage nearby actors */
	simulated function DoVehicleExplosion(bool bDoingSecondaryExplosion)
	{
		local UTPlayerController UTPC;
		local float Dist, ShakeScale, MinViewDist;
		local ParticleSystem Template;
		local SkelControlListHead LH;
		local SkelControlBase NextSkelControl;
		local UTSkelControl_Damage DamSkelControl;
		local vector BoneLocation;
		local bool bIsVisible;

		if ( WorldInfo.NetMode != NM_DedicatedServer )
		{
			if ( bDoingSecondaryExplosion )
			{
				// already checked visibility
				bIsVisible = true;
			}
			else
			{
				// viewshakes and visibility check
				MinViewDist = 10000.0;
				foreach LocalPlayerControllers(class'UTPlayerController', UTPC)
				{
					Dist = VSize(Location - UTPC.ViewTarget.Location);
					if (UTPC == KillerController)
					{
						bIsVisible = true;
						Dist *= 0.25;
					}
					MinViewDist = FMin(Dist, MinViewDist);
					if (Dist < OuterExplosionShakeRadius)
					{
						bIsVisible = true;
						if (DeathExplosionShake != None)
						{
							ShakeScale = 1.0;
							if (Dist > InnerExplosionShakeRadius)
							{
								ShakeScale -= (Dist - InnerExplosionShakeRadius) / (OuterExplosionShakeRadius - InnerExplosionShakeRadius);
							}
							UTPC.PlayCameraAnim(DeathExplosionShake, ShakeScale);
						}
					}
				}
				bIsVisible = bIsVisible || (WorldInfo.TimeSeconds - LastRenderTime < 3.0);
			}

			// determine which explosion to use
			if ( bIsVisible )
			{
				if( !bDoingSecondaryExplosion )
				{
					if( BigExplosionTemplates.length > 0 )
					{
						Template = class'UTEmitter'.static.GetTemplateForDistance(BigExplosionTemplates, Location, WorldInfo);
					}
				}
				else
				{
					Template = SecondaryExplosion;
				}

				PlayVehicleExplosionEffect( Template, !bDoingSecondaryExplosion );
			}

			if (ExplosionSound != None)
			{
				PlaySound(ExplosionSound, true);
			}

			// this will break only pieces that are marked for OnDeath
			if( MinViewDist < 6000.0 && Mesh != none && AnimTree(Mesh.Animations) != none)
			{
				// look at the first SkelControler for each bone
				foreach AnimTree(Mesh.Animations).SkelControlLists(LH)
				{
					// then look down the list of the nodes that may exist
					NextSkelControl = LH.ControlHead;
					while (NextSkelControl != None)
					{
						DamSkelControl = UTSkelControl_Damage(NextSkelControl);
						if( DamSkelControl != none)
						{
							if( DamSkelControl.bOnDeathUseForSecondaryExplosion == bDoingSecondaryExplosion )
							{
								BoneLocation = Mesh.GetBoneLocation(LH.BoneName);
								DamSkelControl.BreakApartOnDeath(BoneLocation, bIsVisible);
							}
						}

						NextSkelControl = NextSkelControl.NextControl;
					}
				}
			}
		}
		HurtRadius(ExplosionDamage, ExplosionRadius, class'UTDmgType_VehicleExplosion', ExplosionMomentum, Location,, GetCollisionDamageInstigator());
		AddVelocity((ExplosionMomentum / Mass) * vect(0,0,1), Location, class'UTDmgType_VehicleExplosion');

		// If in air, add some anglar spin.
		if(Role == ROLE_Authority && !bVehicleOnGround)
		{
			Mesh.SetRBAngularVelocity(VRand() * ExplosionInAirAngVel, TRUE);
		}
	}

	/** This will spawn the actual explosion particle system.  It could be a fiery death or just dust when the vehicle hits the ground **/
	simulated function PlayVehicleExplosionEffect( ParticleSystem TheExplosionTemplate, bool bSpawnLight )
	{
		local UTExplosionLight L;

		if (TheExplosionTemplate != None)
		{
			DeathExplosion = Spawn(class'UTEmitter', self);
			if (BigExplosionSocket != 'None')
			{
				DeathExplosion.SetBase(self,, Mesh, BigExplosionSocket);
			}
			DeathExplosion.SetTemplate(TheExplosionTemplate, true);
			DeathExplosion.ParticleSystemComponent.SetFloatParameter('Velocity', VSize(Velocity) / GroundSpeed);

			if (bSpawnLight && ExplosionLightClass != None && !WorldInfo.bDropDetail && ShouldSpawnExplosionLight(Location, vect(0,0,1)))
			{
				L = new(DeathExplosion) ExplosionLightClass;
				DeathExplosion.AttachComponent(L);
			}
		}
	}

	/** This does the secondary explosion of the vehicle (e.g. from reserve fuel tanks finally blowing / ammo blowing up )**/
	simulated function SecondaryVehicleExplosion()
	{
		// here we need to check to see if we are a vehicle which is falling down from the sky!
		// if we are then we want to push the actual burn out til after we have hit the ground (and don secondary explosion)
		if( Velocity.Z < -100.0f )
		{
			SetTimer( 1.0f, false, 'SecondaryVehicleExplosion' );
			LifeSpan += 1.0f;

			return;
		}
		// we are just going to have vehicles do a "secondary explosion" of dust and rock based on RigidBodyCollision
		//PerformSecondaryVehicleExplosion();
	}

	simulated function PerformSecondaryVehicleExplosion()
	{
		local UTPlayerController UTPC;
		local bool bIsVisible;

		Mesh.SetNotifyRigidBodyCollision( FALSE );

		// only actually do secondary explosion if being rendered
		foreach LocalPlayerControllers(class'UTPlayerController', UTPC)
		{
			if ( (LocalPlayer(UTPC.Player) != None) && LocalPlayer(UTPC.Player).GetActorVisibility(self)
				&& (UTPC.ViewTarget != None) )
			{
				bIsVisible = (UTPC == KillerController) || (VSizeSq(UTPC.ViewTarget.Location - Location) < 25000000.0);
				break;
			}
		}
		if ( bIsVisible )
		{
			DoVehicleExplosion(true);
		}
	}

	simulated event RigidBodyCollision( PrimitiveComponent HitComponent, PrimitiveComponent OtherComponent, const out CollisionImpactData Collision, int ContactIndex )
	{
		Super.RigidBodyCollision(HitComponent, OtherComponent, Collision, ContactIndex);

		if( IsTimerActive( 'SecondaryVehicleExplosion' ) )
		{
			ClearTimer( 'SecondaryVehicleExplosion' );
			PerformSecondaryVehicleExplosion();
		}
	}


	simulated event TakeDamage(int Damage, Controller EventInstigator, vector HitLocation, vector Momentum, class<DamageType> DamageType, optional TraceHitInfo HitInfo, optional Actor DamageCauser)
	{
		if (DamageType != None)
		{
			Damage *= DamageType.static.VehicleDamageScalingFor(self);

			Health -= Damage;
			AddVelocity(Momentum, HitLocation, DamageType, HitInfo);

			if (DamageType == class'UTDmgType_VehicleCollision')
			{
				if ( EffectIsRelevant(Location, false) )
				{
					WorldInfo.MyEmitterPool.SpawnEmitter(ExplosionTemplate, HitLocation, rotator(vect(0,0,1)));
				}
				if (ExplosionSound != None)
				{
					PlaySound(ExplosionSound, true);
				}
			}
		}
	}

	/**
	*	Calculate camera view point, when viewing this pawn.
	*
	* @param	fDeltaTime	delta time seconds since last update
	* @param	out_CamLoc	Camera Location
	* @param	out_CamRot	Camera Rotation
	* @param	out_FOV		Field of View
	*
	* @return	true if Pawn should provide the camera point of view.
	*/
	simulated function VehicleCalcCamera(float fDeltaTime, int SeatIndex, out vector out_CamLoc, out rotator out_CamRot, out vector CamStart, optional bool bPivotOnly)
	{
 		Global.VehicleCalcCamera(fDeltaTime, SeatIndex, out_CamLoc, out_CamRot, CamStart, bPivotOnly);
		bStopDeathCamera = bStopDeathCamera || (out_CamLoc.Z < WorldInfo.KillZ);
		if ( bStopDeathCamera && (OldCameraPosition != vect(0,0,0)) )
		{
			// Don't allow camera to go below killz, by re-using old camera position once dead vehicle falls below killz
		   	out_CamLoc = OldCameraPosition;
			out_CamRot = rotator(CamStart - out_CamLoc);
		}
		OldCameraPosition = out_CamLoc;
	}

	simulated function BeginState(name PreviousStateName)
	{
		local int i;

		StopVehicleSounds();

		// make sure smoke/fire are on
		DamageSmokeThreshold = 0.0; //VehicleEvent('DamageSmoke');
		CheckDamageSmoke();
		// fully destroy all morph targets
		for (i = 0; i < DamageMorphTargets.length; i++)
		{
			DamageMorphTargets[i].Health = 0;
			if(DamageMorphTargets[i].MorphNode != none)
			{
				DamageMorphTargets[i].MorphNode.SetNodeWeight(1.0);
			}
		}

		UpdateDamageMaterial();
		ClientHealth = Min(ClientHealth, 0);

		LastCollisionSoundTime = WorldInfo.TimeSeconds;
		DoVehicleExplosion(false);

		if( TimeTilSecondaryVehicleExplosion > 0.0f )
		{
			SetTimer( TimeTilSecondaryVehicleExplosion, FALSE, 'SecondaryVehicleExplosion' );
		}

		for(i=0; i<DamageSkelControls.length; i++)
		{
			DamageSkelControls[i].HealthPerc = 0.f;
		}

		if (WorldInfo.NetMode != NM_DedicatedServer)
		{
			PerformDeathEffects();
		}
		SetBurnOut();

		if (Controller != None)
		{
			if (Controller.bIsPlayer)
			{
				DetachFromController();
			}
			else
			{
				Controller.Destroy();
			}
		}

		for (i = 0; i < Attached.length; i++)
		{
			if (Attached[i] != None)
			{
				Attached[i].PawnBaseDied();
			}
		}
	}

	simulated function PerformDeathEffects()
	{
		if (bHasTurretExplosion)
		{
			TurretExplosion();
		}
	}


}

simulated function TurretExplosion()
{
	local vector SpawnLoc;
	local rotator SpawnRot;
	local SkelControlBase SK;
	local vector Force;

	Mesh.GetSocketWorldLocationAndRotation(TurretSocketName,SpawnLoc,SpawnRot);

	WorldInfo.MyEmitterPool.SpawnEmitter( class'UTEmitter'.static.GetTemplateForDistance(DistanceTurretExplosionTemplates, SpawnLoc, WorldInfo),Location, Rotation );

	DestroyedTurret = Spawn(class'UTVehicleDeathPiece',self,,SpawnLoc+TurretOffset,SpawnRot,,true);
	if(DestroyedTurret != none)
	{
		StaticMeshComponent(DestroyedTurret.GibMeshComp).SetStaticMesh(DestroyedTurretTemplate);
		//DestroyedTurret.SetCollision( FALSE, FALSE, TRUE );
		DestroyedTurret.GibMeshComp.SetBlockRigidBody( FALSE );
	// @todo make a RBChannelContainer function to do all this
		DestroyedTurret.GibMeshComp.SetRBChannel( RBCC_Nothing ); // nothing will request to collide with us
		DestroyedTurret.GibMeshComp.SetRBCollidesWithChannel( RBCC_Default, FALSE );
		DestroyedTurret.GibMeshComp.SetRBCollidesWithChannel( RBCC_Pawn, FALSE );
		DestroyedTurret.GibMeshComp.SetRBCollidesWithChannel( RBCC_Vehicle, FALSE );
		DestroyedTurret.GibMeshComp.SetRBCollidesWithChannel( RBCC_GameplayPhysics, FALSE );
		DestroyedTurret.GibMeshComp.SetRBCollidesWithChannel( RBCC_EffectPhysics, FALSE );

		DestroyedTurret.SetTimer( 0.100f, FALSE, 'TurnOnCollision' );

		SK = Mesh.FindSkelControl(TurretScaleControlName);
		if(SK != none)
		{
			SK.boneScale = 0.0f;
		}
		Force = Vect(0,0,1);
		Force *= TurretExplosiveForce;
		// Let's at least try and go off in some direction
		Force.X = FRand()*1000.0f + 400.0f;
		Force.Y = FRand()*1000.0f + 400.0f;
		DestroyedTurret.GibMeshComp.AddImpulse(Force);
		DestroyedTurret.GibMeshComp.SetRBAngularVelocity(VRand()*500.0f);
	}
}

simulated function StopVehicleSounds()
{
	local int seatIdx;
	Super.StopVehicleSounds();
	for(seatIdx=0;seatIdx < Seats.Length; ++seatIdx)
	{
		if(Seats[seatIdx].SeatMotionAudio != none)
		{
			Seats[seatIdx].SeatMotionAudio.Stop();
		}
	}
}

simulated function CheckDamageSmoke()
{
	if (WorldInfo.NetMode != NM_DedicatedServer)
	{
		VehicleEvent((float(Health) / float(HealthMax) < DamageSmokeThreshold) ? 'DamageSmoke' : 'NoDamageSmoke');
	}
}

simulated function AttachDriver( Pawn P )
{
	local UTPawn UTP;

	// reset vehicle camera
	OldPositions.remove(0,OldPositions.Length);
	Eyeheight = BaseEyeheight;

	UTP = UTPawn(P);
	if (UTP != None)
	{
		UTP.SetWeaponAttachmentVisibility(false);
		UTP.SetHandIKEnabled(false);
		if (bAttachDriver)
		{
			UTP.SetCollision( false, false);
			UTP.bCollideWorld = false;
			UTP.SetBase(none);
			UTP.SetHardAttach(true);
			UTP.SetLocation( Location );
			UTP.SetPhysics( PHYS_None );

			SitDriver( UTP, 0);
		}
	}
}

simulated function SitDriver( UTPawn UTP, int SeatIndex)
{
	local float ClampedTranslation;

	if (Seats[SeatIndex].SeatBone != '')
	{
		UTP.SetBase( Self, , Mesh, Seats[SeatIndex].SeatBone);
	}
	else
	{
		UTP.SetBase( Self );
	}
	SetMovementEffect(SeatIndex,true, UTP);

	// Shut down physics when getting in vehicle.
	if(UTP.Mesh.PhysicsAssetInstance != None)
	{
		UTP.Mesh.PhysicsAssetInstance.SetAllBodiesFixed(TRUE);
	}
	UTP.Mesh.bUpdateKinematicBonesFromAnimation = FALSE;
	UTP.Mesh.PhysicsWeight = 0.0;

	if ( Seats[SeatIndex].bSeatVisible )
	{
		if ( (UTP.Mesh != None) && (Mesh != None) )
		{
			UTP.Mesh.SetShadowParent(Mesh);
			UTP.Mesh.SetLightEnvironment(LightEnvironment);
		}
		UTP.SetMeshVisibility(true);
		UTP.SetRelativeLocation( Seats[SeatIndex].SeatOffset );
		UTP.SetRelativeRotation( Seats[SeatIndex].SeatRotation );
		UTP.Mesh.SetCullDistance(5000);

		//HACK - don't let this translation get too large (for Liandri riding high)
		ClampedTranslation = Clamp(UTP.BaseTranslationOffset, -7.0, 7.0);
		UTP.Mesh.SetTranslation(vect(0,0,1) * ClampedTranslation);
		UTP.SetHidden(false);
	}
	else
	{
		UTP.SetHidden(True);
	}
}

/** Allows a vehicle to do specific physics setup on a driver when physics asset changes. */
simulated function OnDriverPhysicsAssetChanged(UTPawn UTP);

simulated function String GetHumanReadableName()
{
	if (VehicleNameString == "")
	{
		return ""$Class;
	}
	else
	{
		return VehicleNameString;
	}
}


event OnPropertyChange(name PropName)
{
	local int i;

	for (i=0;i<Seats.Length;i++)
	{
		if ( Seats[i].bSeatVisible )
		{
			Seats[i].StoragePawn.SetRelativeLocation( Seats[i].SeatOffset );
			Seats[i].StoragePawn.SetRelativeRotation( Seats[i].SeatRotation );
		}
	}
}

simulated function int GetHealth(int SeatIndex)
{
	return Health;
}

function float GetCollisionDamageModifier(const out array<RigidBodyContactInfo> ContactInfos)
{
	local float Angle;
	local vector X, Y, Z;

	if (bReducedFallingCollisionDamage)
	{
		GetAxes(Rotation, X, Y, Z);
		Angle = ContactInfos[0].ContactNormal Dot Z;
		return (Angle < 0.f) ? Square(CollisionDamageMult * (1.0+Angle)) : Square(CollisionDamageMult);
	}
	else
	{
		return Square(CollisionDamageMult);
	}
}

simulated event RigidBodyCollision( PrimitiveComponent HitComponent, PrimitiveComponent OtherComponent,
								   const out CollisionImpactData Collision, int ContactIndex )
{
	local int Damage;
	local UTVehicle V;
	local Controller InstigatorController;

	if (LastCollisionDamageTime != WorldInfo.TimeSeconds)
	{
		Super.RigidBodyCollision(HitComponent, OtherComponent, Collision, ContactIndex);

		if (OtherComponent != None && UTPawn(OtherComponent.Owner) != None && OtherComponent.Owner.Physics == PHYS_RigidBody)
		{
			RanInto(OtherComponent.Owner);
		}
		else if(Mesh != None)
		{
			// take impact damage
			Damage = int(VSizeSq(Mesh.GetRootBodyInstance().PreviousVelocity) * GetCollisionDamageModifier(Collision.ContactInfos));
			if (Damage > 1)
			{
				// if rammed other vehicle, give that vehicle's Instigator credit for the damage
				if (OtherComponent != None)
				{
					V = UTVehicle(OtherComponent.Owner);
					if (V != None)
					{
						InstigatorController = V.GetCollisionDamageInstigator();
					}
				}
				if (InstigatorController == None)
				{
					InstigatorController = GetCollisionDamageInstigator();
				}
				TakeDamage(Damage, InstigatorController, Collision.ContactInfos[0].ContactPosition, vect(0,0,0), class'UTDmgType_VehicleCollision');
				LastCollisionDamageTime = WorldInfo.TimeSeconds;
			}
		}
	}
}

/** Called when a contact with a large penetration occurs. */
event RBPenetrationDestroy()
{
	if (Health > 0)
	{
		//`log("Penetration Death:"@self@Penetration);
		TakeDamage(10000, GetCollisionDamageInstigator(), Location, vect(0,0,0), class'UTDmgType_VehicleCollision');
	}
}

/************************************************************************************
 * Morphs
 ***********************************************************************************/

/**
 * Initialize the damage modeling system
 */
simulated function InitializeMorphs()
{
	local int i,j;

	for (i=0;i<DamageMorphTargets.Length;i++)
	{
		// Find this node

		if(DamageMorphTargets[i].MorphNodeName != 'None')
		{
			DamageMorphTargets[i].MorphNode 	  = MorphNodeWeight( Mesh.FindMorphNode(DamageMorphTargets[i].MorphNodeName) );
			if (DamageMorphTargets[i].MorphNode == None)
			{
				WarnInternal("Failed to find Morph node named" @ DamageMorphTargets[i].MorphNodeName @ "in" @ Mesh.SkeletalMesh);
			}
		}

		// Fix up all linked references to this node.

		for (j=0;j<DamageMorphTargets.Length;j++)
		{
			if ( DamageMorphTargets[j].LinkedMorphNodeName == DamageMorphTargets[i].MorphNodeName )
			{
				DamageMorphTargets[j].LinkedMorphNodeIndex = i;
			}
		}
	}
	InitDamageSkel();

}

native simulated function InitDamageSkel();

/**
 * Whenever the morph system adjusts a health, it should call UpdateDamageMaterial() so that
 * any associated skins can be adjusted.  This is also native
 */
native simulated function UpdateDamageMaterial();

/**
 * When damage occur, we need to apply it to any MorphTargets.  We do this natively for speed
 *
 * @param	HitLocation		Where did the hit occured
 * @param	Damage			How much damage occured
 */
native function ApplyMorphDamage(vector HitLocation, int Damage, vector Momentum);

/** called when the client receives a change to Health
 * if LastTakeHitInfo changed in the same received bunch, always called *after* PlayTakeHitEffects()
 * (this is so we can use the damage info first for more accurate modelling and only use the direct health change for corrections)
 */
simulated event ReceivedHealthChange()
{
	local int Diff;

	Diff = Health - ClientHealth;
	if (Diff > 0)
	{
		ApplyMorphHeal(Diff);
	}
	else
	{
		ApplyRandomMorphDamage(Diff);
	}
	ClientHealth = Health;

	CheckDamageSmoke();
}

/**
 * Since vehicles can be healed, we need to apply the healing to each MorphTarget.  Since damage modeling is
 * client-side and healing is server-side, we evenly apply healing to all nodes
 *
 * @param	Amount		How much health to heal
 */
simulated event ApplyMorphHeal(int Amount)
{
	local int Individual, Total, Remaining;
	local int i;
	local float Weight;

	if (Health >= HealthMax)
	{
		// fully heal everything
		for (i = 0; i < DamageMorphTargets.length; i++)
		{
			DamageMorphTargets[i].Health = default.DamageMorphTargets[i].Health;
			if(DamageMorphTargets[i].MorphNode != none)
			{
				DamageMorphTargets[i].MorphNode.SetNodeWeight(0.0);
			}
		}
		for(i=0; i< DamageSkelControls.length; i++)
		{
			DamageSkelControls[i].RestorePart();
		}
	}
	else
	{
		// Find out the total amount of health needed for all nodes that have been "hurt"
		for ( i = 0; i < DamageMorphTargets.Length; i++)
		{
			if ( DamageMorphTargets[i].Health < Default.DamageMorphTargets[i].Health )
			{
				Total += Default.DamageMorphTargets[i].Health;
			}
		}

		// Deal out health evenly
		if (Amount > 0 && Total > 0)
		{
			Remaining = Amount;
			for (i = 0; i < DamageMorphTargets.length; i++)
			{
				Individual = Min( default.DamageMorphTargets[i].Health - DamageMorphTargets[i].Health,
						int(float(Amount) * float(Default.DamageMorphTargets[i].Health) / float(Total)) );
				DamageMorphTargets[i].Health += Individual;
				Remaining -= Individual;
			}

			// deal out any leftovers and update node weights
			for (i = 0; i < DamageMorphTargets.length; i++)
			{
				if (Remaining > 0)
				{
					Individual = Min(Remaining, default.DamageMorphTargets[i].Health - DamageMorphTargets[i].Health);
					DamageMorphTargets[i].Health += Individual;
					Remaining -= Individual;
				}
				Weight = 1.0 - (float(DamageMorphTargets[i].Health) / float(Default.DamageMorphTargets[i].Health));
				if(DamageMorphTargets[i].MorphNode != none)
				{
					DamageMorphTargets[i].MorphNode.SetNodeWeight(Weight);
				}
			}
		}

		// heal skel controls up one at a time.
		Total = 0;
		for( i = 0; i < DamageSkelControls.length; i++ )
		{
			if( Total < Amount)
			{
				Total += (1-DamageSkelControls[i].HealthPerc)*DamageSkelControls[i].DamageMax;
				// either we can cover the whole heal, or we fix the percentage left on this loop:
				DamageSkelControls[i].HealthPerc = Total<Amount?DamageSkelControls[i].RestorePart() : DamageSkelControls[i].HealthPerc + (float(Amount)-float(Total))/float(DamageSkelControls[i].DamageMax);
			}
			else
			{
				break;
			}
		}
	}

	UpdateDamageMaterial();
}

/** called to apply morph damage where we don't know what was actually hit
 * (i.e. because the client detected it by receiving a new Health value from the server)
 */
simulated function ApplyRandomMorphDamage(int Amount)
{
	local int min, minindex;
	local int i;
	local float MinAmt;
	local float Weight;

	// Search for the skel control to damage (if any)
	for(i=0;i<DamageSkelControls.Length;i++)
	{
		if(DamageSkelControls[i].HealthPerc > 0 && minindex < 0)
		{
			MinAmt = FMin(Amount/(DamageSkelControls[i].DamageMax*DamageSkelControls.Length),DamageSkelControls[i].HealthPerc);
			DamageSkelControls[i].HealthPerc -= MinAmt;
		}
	}
	while (Amount > 0)
	{
		minindex = -1;

		// Search for the node with the least amount of health
		minindex=-1;
		for (i=0;i<DamageMorphTargets.Length;i++)
		{
			if ((DamageMorphTargets[i].Health > 0) && (minindex < 0 || DamageMorphTargets[i].Health < min))
			{
				min = DamageMorphTargets[i].Health;
				minindex = i;
			}
		}

		// Deal out damage to that node
		if (minindex>=0)
		{
			if (min < Amount)
			{
				DamageMorphTargets[minindex].Health = 0;
				Amount -= min;
			}
			else
			{
				DamageMorphTargets[minindex].Health -= Amount;
				Amount = 0;
			}

			// Adjust the target
			Weight = 1.0 - ( FLOAT(DamageMorphTargets[minindex].Health) / FLOAT(Default.DamageMorphTargets[minindex].Health) );
			if(DamageMorphTargets[minindex].MorphNode != none)
			{
				DamageMorphTargets[minindex].MorphNode.SetNodeWeight(Weight);
			}
		}
		else
		{
			break;
		}

	}

	UpdateDamageMaterial();
}

/**
 * The event is called from the native function ApplyMorphDamage when a node is destroyed (health <= 0).
 *
 * @param	MorphNodeIndex 		The Index of the node that was destroyed
 */
simulated event MorphTargetDestroyed(int MorphNodeIndex);

/**
 * We use this function as the UTPawn's spawngib as for our vehicles we are spawning the gibs at specific locations based on the
 * skelcontrollers and the placement of meshes on the exterior of the vehicle
 **/
simulated function UTGib SpawnGibVehicle(vector SpawnLocation, rotator SpawnRotation, StaticMesh TheMesh, vector HitLocation, bool bSpinGib, vector ImpulseDirection, ParticleSystem PS_OnBreak, ParticleSystem PS_Trail)
{
	local UTGib_Vehicle Gib;
	local float GibPerterbation;
	local rotator VelRotation;
	local vector X, Y, Z;

	//`log("SpawnGibVehicle "$TheMesh);
	Gib = Spawn(VehiclePieceClass, self,, SpawnLocation, SpawnRotation,, TRUE );

	if ( Gib != None )
	{
		Gib.SetGibStaticMesh( TheMesh );
		//Gib.SetCollision( FALSE, FALSE, TRUE );
		Gib.GibMeshComp.SetBlockRigidBody( FALSE );
		Gib.GibMeshComp.SetRBChannel( RBCC_Nothing ); // nothing will request to collide with us
	// @todo make a RBChannelContainer function to do all this
		Gib.GibMeshComp.SetRBCollidesWithChannel( RBCC_Default, FALSE );
		Gib.GibMeshComp.SetRBCollidesWithChannel( RBCC_Pawn, FALSE );
		Gib.GibMeshComp.SetRBCollidesWithChannel( RBCC_Vehicle, FALSE );
		Gib.GibMeshComp.SetRBCollidesWithChannel( RBCC_GameplayPhysics, FALSE );
		Gib.GibMeshComp.SetRBCollidesWithChannel( RBCC_EffectPhysics, FALSE );

		Gib.SetTimer( 0.100f, FALSE, 'TurnOnCollision' );

		// add initial impulse
		GibPerterbation = 30000;
		VelRotation = rotator(Gib.Location - HitLocation);
		VelRotation.Pitch += (FRand() * 2.0 * GibPerterbation) - GibPerterbation;
		VelRotation.Yaw += (FRand() * 2.0 * GibPerterbation) - GibPerterbation;
		VelRotation.Roll += (FRand() * 2.0 * GibPerterbation) - GibPerterbation;
		GetAxes(VelRotation, X, Y, Z);

		// use the passed in impulse dir if it is decently big enough
		if( VSize(ImpulseDirection) > 100.0f )
		{
			Gib.Velocity = Velocity + ImpulseDirection;
		}
		else
		{
			if( VSize(Velocity) > 10.0f )
			{
				Gib.Velocity = Velocity + (Z * ( FRand() * 100 )) + vect(0,0,1000);
			}
			else
			{
				Gib.Velocity = (vect(1,0,0) * ( (FRand() * 400) ) )
					+ (vect(0,1,0) * ( (FRand() * 400) ) )
					+ (Z * ( FRand() * 300 )) + vect(0,0,1000);
			}
		}


		Gib.GibMeshComp.WakeRigidBody();
		Gib.GibMeshComp.SetRBLinearVelocity( Gib.Velocity, FALSE );

		if( bSpinGib )
		{
			Gib.GibMeshComp.SetRBAngularVelocity( VRand() * 500, FALSE );
		}

		Gib.LifeSpan = Gib.LifeSpan + (2.0 * FRand());

		Gib.OwningClass = Class;


		if( PS_OnBreak != none )
		{
			Gib.PS_GibExplosionEffect = PS_OnBreak;
		}

		if( PS_Trail != none )
		{
			Gib.PS_GibTrailEffect = PS_Trail;
		}

		Gib.SetTimer( class'UTGib_Vehicle'.default.TimeBeforeGibExplosionEffect, FALSE, 'ActivateGibExplosionEffect' );
	}

	return Gib;
}


/**
 * We extend GetSVehicleDebug to include information about the seats array
 *
 * @param	DebugInfo		We return the text to display here
 */

simulated function GetSVehicleDebug( out Array<String> DebugInfo )
{
	local int i;

	Super.GetSVehicleDebug(DebugInfo);

	if (UTVehicleSimCar(SimObj) != None)
	{
		DebugInfo[DebugInfo.Length] = "ActualThrottle: "$UTVehicleSimCar(SimObj).ActualThrottle;
	}

	DebugInfo[DebugInfo.Length] = "";
	DebugInfo[DebugInfo.Length] = "----Seats----: ";
	for (i=0;i<Seats.Length;i++)
	{
		DebugInfo[DebugInfo.Length] = "Seat"@i$":"@Seats[i].Gun @ "Rotation" @ SeatWeaponRotation(i,,true) @ "FiringMode" @ SeatFiringMode(i,,true) @ "Barrel" @ Seats[i].BarrelIndex;
		if (Seats[i].Gun != None)
		{
			DebugInfo[DebugInfo.length - 1] @= "IsAimCorrect" @ Seats[i].Gun.IsAimCorrect();
		}
	}
}

/** Kismet hook for kicking a pawn out of a vehicle */
function OnExitVehicle(UTSeqAct_ExitVehicle Action)
{
	local int i;

	for (i = 0; i < Seats.length; i++)
	{
		if (Seats[i].SeatPawn != None && Seats[i].SeatPawn.Driver != None)
		{
			Seats[i].SeatPawn.DriverLeave(true);
		}
	}
}

/** stub for vehicles with shield firemodes */
function SetShieldActive(int SeatIndex, bool bActive);

simulated function SetHoverBoardAttachPointInUse(name PointName, bool bInUse)
{
	local int i;
	local bool bFound;

	bIsTowingHoverboard = false;
	for (i=0; i<HoverBoardAttachSockets.length; i++)
	{
		if( HoverBoardAttachSockets[i] == PointName )
		{
			HoverBoardSocketInUse[i] = bInUse;
			bFound = true;
		}
		bIsTowingHoverboard = bIsTowingHoverboard || HoverBoardSocketInUse[i];
	}

	if ( !bFound )
	{
		LogInternal("WARNING: "@PointName@" not found on"@self);
	}
}

simulated function name GetHoverBoardAttachPoint(vector HoverBoardLocation)
{
	local name Result;
	local float Dist, MinDist;
	local vector v;
	local int i;

	if ( HoverBoardAttachSockets.Length > 0 )
	{
		for (i=0;i<HoverBoardAttachSockets.Length;i++)
		{
			if( !HoverBoardSocketInUse[i] )
			{
				Mesh.GetSocketWorldLocationAndRotation(HoverBoardAttachSockets[i],v);
				Dist = VSize( HoverBoardLocation - v );
				if ( i==0 || Dist < MinDist )
				{
					Result = HoverBoardAttachSockets[i];
					MinDist = Dist;
				}
			}
		}
	}

	return result;
}

function SetSeatStoragePawn(int SeatIndex, Pawn PawnToSit)
{
	local int Mask;

	Seats[SeatIndex].StoragePawn = PawnToSit;
	if ( (SeatIndex == 1) && (Role == ROLE_Authority) )
	{
		PassengerPRI = (PawnToSit == None) ? None : UTPlayerReplicationInfo(Seats[SeatIndex].SeatPawn.PlayerReplicationInfo);
	}

	Mask = 1 << SeatIndex;

	if ( PawnToSit != none )
	{
		SeatMask = SeatMask | Mask;
	}
	else
	{
		if ( (SeatMask & Mask) > 0)
		{
			SeatMask = SeatMask ^ Mask;
		}
	}

}

simulated function SetMovementEffect(int SeatIndex, bool bSetActive, optional UTPawn UTP)
{
	local bool bIsLocal;

	if (bSetActive && ReferenceMovementMesh != None)
	{
		bIsLocal = UTP==none? IsLocallyControlled():UTP.IsLocallyControlled();
		if(bIsLocal && WorldInfo.Netmode != NM_DEDICATEDSERVER)
		{
			// Should never happen, but just in case:
			if(Seats[SeatIndex].SeatMovementEffect != none)
			{
				Seats[SeatIndex].SeatMovementEffect.Destroy();
			}
			Seats[SeatIndex].SeatMovementEffect = Spawn(class'VehicleMovementEffect',Seats[SeatIndex].SeatPawn,,Location,Rotation);
			if(Seats[SeatIndex].SeatMovementEffect != none)
			{
				Seats[SeatIndex].SeatMovementEffect.SetBase(self);
				Seats[SeatIndex].SeatMovementEffect.AirEffect.SetStaticMesh(ReferenceMovementMesh);
			}
		}
	}
	else if (Seats[SeatIndex].SeatMovementEffect != None)
	{
		Seats[SeatIndex].SeatMovementEffect.Destroy();
	}
}

simulated function DetachDriver(Pawn P)
{
	Super.DetachDriver(P);

	SetMovementEffect(0, false);
}

/** @return Actor that can be locked on to by weapons as if it were this vehicle */
native function Actor GetAlternateLockTarget();

function bool CanAttack(Actor Other)
{
	local float MaxRange;
	local Weapon W;

	if ( bShouldLeaveForCombat && Driver != None && Driver.InvManager != None && Controller != None &&
		!WorldInfo.GRI.OnSameTeam(self, Other) && !IsHumanControlled() )
	{
		// return whether can attack with handheld weapons (assume bot will leave if it actually decides to attack)
		foreach Driver.InvManager.InventoryActors(class'Weapon', W)
		{
			MaxRange = FMax(MaxRange, W.MaxRange());
		}
		return (VSize(Location - Other.Location) <= MaxRange && Controller.LineOfSightTo(Other));
	}
	else
	{
		return Super.CanAttack(Other);
	}
}

function bool CanDeployedAttack(Actor Other)
{
	return false;
}

simulated function bool IsDeployed()
{
	return true;
}

function name GetVehicleKillStatName()
{
	local name VehicleKillStatName;

    //Convert Gold content properly
	if (Class.Name == 'UTVehicle_StealthbenderGold_Content')
	{
		VehicleKillStatName = 'VEHICLEKILL_UTVEHICLE_STEALTHBENDER_CONTENT';
	}
	else
	{
		VehicleKillStatName = name('VEHICLEKILL_'$Class.Name);	
	}

	return VehicleKillStatName;
}

simulated function DisplayHud(UTHud Hud, Canvas Canvas, vector2D HudPOS, optional int SeatIndex)
{
	local vector2D POS;
	local float W,H, PercValue, PosX, PosY, XL, YL;
	local int VHealth;
	local linearcolor MissingHealthColor;

	// Figure out dims and resolve the hud position
	W = Abs(HudCoords.UL) * HUD.ResolutionScale;
	H = Abs(HudCoords.VL) * HUD.ResolutionScale;
	PosX = Canvas.ClipX - W;
	PosY = Canvas.ClipY - H - (HUD.AmmoBarOffsetY*HUD.ResolutionScale);

	// Draw the Vehicle icon, showing health pct
	VHealth = Max(0, Health);
	PercValue = FClamp(float(VHealth)/float(HealthMax), 0.0, 1.0);
	Canvas.SetPos(PosX, PosY);
	if ( PercValue < 1.0 )
	{
		MissingHealthColor = Hud.WhiteLinearColor;
		MissingHealthColor.A = 0.3;
		Canvas.DrawColorizedTile(HUD.UT3GHudTexture, W, H*(1.0-PercValue), HudCoords.U, HudCoords.V, HudCoords.UL, HudCoords.VL*(1.0-PercValue), MissingHealthColor);
		Canvas.SetPos(PosX, PosY+H*(1.0-PercValue));
	}
	Canvas.DrawColorizedTile(HUD.UT3GHudTexture, W, H*PercValue, HudCoords.U, HudCoords.V+HudCoords.VL*(1.0-PercValue), HudCoords.UL, HudCoords.VL*PercValue, Hud.TeamHudColor);

	// Draw the Seats.
	DisplaySeats(HUD, Canvas, PosX, PosY, W,H, SeatIndex);

	if ( HUD.bShowVehicleArmorCount )
	{
		// Recalc the Positions given the health bar
		PosX = PosX - (HUD.AmmoBGCoords.UL * HUD.ResolutionScale);
		PosY = Canvas.ClipY - (HUD.AmmoBGCoords.VL + HUD.AmmoBarOffsetY) * HUD.ResolutionScale;
		Canvas.SetPos(PosX,PosY);
		Canvas.DrawColorizedTile(HUD.AltHudTexture, (HUD.AmmoBGCoords.UL * HUD.ResolutionScale), HUD.AmmoBGCoords.VL * HUD.ResolutionScale, HUD.AmmoBGCoords.U, HUD.AmmoBGCoords.V, HUD.AmmoBGCoords.UL, HUD.AmmoBGCoords.VL, HUD.TeamHUDColor);

		// Pulse if health is being added
		if ( Health > LastHealth )
		{
			HealthPulseTime = WorldInfo.TimeSeconds;
		}
		LastHealth = Health;

		//Some magic contained inside DrawGlowText that isn't in StrLen
		Canvas.StrLen(string(VHealth), XL, YL);
		XL *= (58 / YL);

		//Center the vehicle health text
		Hud.DrawGlowText( string(VHealth), PosX + (HUD.AmmoBGCoords.UL - XL) * 0.5 * HUD.ResolutionScale, PosY - (HUD.AmmoTextOffsetY * HUD.ResolutionScale), 58 * Hud.ResolutionScale, HealthPulseTime, false);

		// Draw any extra data.  We pass in the full bounds of the widget as well as the full X/Y
		W += (HUD.AmmoBGCoords.UL * HUD.ResolutionScale);
		POS.X = PosX;
		POS.Y = PosY;
		DisplayExtraHud(Hud, Canvas, POS, W, H, SeatIndex);
	}

	// If we have a bar graph display, do it here
	if ( (Seats[SeatIndex].Gun != None) && (Seats[SeatIndex].Gun.AmmoDisplayType != EAWDS_Numeric) )
	{
		bHasBarGraph = true;
		PercValue = Seats[SeatIndex].Gun.GetPowerPerc();
		ChargeBarHeight = H - (2 * ChargeBarPosY * HUD.ResolutionScale);
		PosX = Canvas.ClipX - (Abs(HudCoords.UL) - ChargeBarPosX) * HUD.ResolutionScale;
		PosY = Canvas.ClipY - (Abs(HudCoords.VL) - ChargeBarPosY + HUD.AmmoBarOffsetY) * HUD.ResolutionScale;
		DrawBarGraph(PosX, PosY, ChargeBarWidth * HUD.ResolutionScale, ChargeBarHeight, PercValue, HUD.ResolutionScale, Canvas);
	}
	else
	{
		bHasBarGraph = false;
	}
}

simulated function DrawBarGraph(float X, float Y, float Width, float Height, float PercentFilled, float ResolutionScale, Canvas DrawCanvas)
{
	local float PosX, PosY;
	local float TrueHeight, EndCapHeight;
	local float myV, myVL;

	EndCapHeight = ChargeBarEndCapCoords.VL * ResolutionScale;

	//Height of just the part that grows (no endcaps)
	TrueHeight = Height - (2 * EndCapHeight);

	//Find the position of the lower part of the bar
	PosX = X;
	PosY = Y + EndCapHeight + (1.0 - PercentFilled) * TrueHeight;
	TrueHeight *= PercentFilled;
	
	//Add back the bottom cap
	TrueHeight += EndCapHeight;

	//Figure out the length of the moving bar
	myV = ChargeBarCoords.V + ChargeBarEndCapCoords.VL + (1.0 - PercentFilled) * (ChargeBarCoords.VL - (2.0 * ChargeBarEndCapCoords.VL));
	myVL = PercentFilled * (ChargeBarCoords.VL - (2.0 * ChargeBarEndCapCoords.VL));

    //Add back space for the bottom cap
	myVL += ChargeBarEndCapCoords.VL;
	
	// draw the bar
	DrawCanvas.DrawColor = class'UTHUD'.default.WhiteColor;
	DrawCanvas.DrawColor.B = 16;
	DrawCanvas.SetPos(PosX, PosY);
	DrawCanvas.DrawTile(class'UTHUD'.default.IconHudTexture, Width, TrueHeight, ChargeBarCoords.U, myV, ChargeBarCoords.UL, myVL);

	// draw the fixed size end cap
	DrawCanvas.SetPos(PosX, PosY - EndCapHeight);
	DrawCanvas.DrawTile(class'UTHUD'.default.IconHudTexture, Width, EndCapHeight, ChargeBarEndCapCoords.U, ChargeBarEndCapCoords.V, ChargeBarEndCapCoords.UL, ChargeBarEndCapCoords.VL);
}


simulated function DisplayExtraHud(UTHud Hud, Canvas Canvas, vector2D POS, float Width, float Height, int SIndex);

simulated function DisplaySeats(UTHud Hud, Canvas Canvas, float PosX, float PosY, float Width, float Height, int SIndex)
{
	local int i;
	local float X,Y;

	for (i=0;i<Seats.Length;i++)
	{
		X = PosX + (Width * (Seats[i].SeatIconPOS.X + Hud.TX));
		Y = PosY + (Height * (Seats[i].SeatIconPOS.Y + Hud.TY));
		Canvas.SetPos(X,Y);
		Hud.DrawTileCentered(Hud.AltHudTexture, 18 * Hud.ResolutionScale, 18 * Hud.ResolutionScale, 268,0,20,20, GetSeatColor(i, i == SIndex) );
	}
}

simulated function LinearColor GetSeatColor(int SeatIndex, bool bIsPlayersSeat)
{
	local byte TestMask;
	if (!bIsPlayersSeat)
	{
		TestMask = 1 << SeatIndex;
		if ( (SeatMask & TestMask) > 0)
		{
			return class'UTHUD'.Default.WhiteLinearColor;
		}
		else
		{
			return MakeLinearColor(0.5,0.5,0.5,1.0);
		}
	}
	else
	{
		return class'UTHUD'.Default.GoldLinearColor;
	}
}

simulated function ApplyWeaponEffects(int OverlayFlags, optional int SeatIndex)
{
	local int i, OverlayIndex;
	local UTGameReplicationInfo GRI;

	OverlayIndex = INDEX_NONE;
	GRI = UTGameReplicationInfo(WorldInfo.GRI);
	if (GRI != None)
	{
		for (i = 0; i < GRI.VehicleWeaponEffects.length; i++)
		{
			if (GRI.VehicleWeaponEffects[i].Mesh != None && bool(OverlayFlags & (1 << i)))
			{
				OverlayIndex = i;
				break;
			}
		}
	}

	if (OverlayIndex == INDEX_NONE)
	{
		for (i = 0; i < Seats[SeatIndex].WeaponEffects.length; i++)
		{
			if (Seats[SeatIndex].WeaponEffects[i].Effect != None && Seats[SeatIndex].WeaponEffects[i].Effect.bAttached)
			{
				Mesh.DetachComponent(Seats[SeatIndex].WeaponEffects[i].Effect);
			}
		}
	}
	else
	{
		for (i = 0; i < Seats[SeatIndex].WeaponEffects.length; i++)
		{
			if (Seats[SeatIndex].WeaponEffects[i].Effect == None)
			{
				// unique name is for use with 'editudmgfx' console command
				Seats[SeatIndex].WeaponEffects[i].Effect = new(self, string(self) $ "_WeaponEffect_" $ i) class'StaticMeshComponent';
				Seats[SeatIndex].WeaponEffects[i].Effect.SetTranslation(Seats[SeatIndex].WeaponEffects[i].Offset);
				Seats[SeatIndex].WeaponEffects[i].Effect.SetScale3D(Seats[SeatIndex].WeaponEffects[i].Scale3D);
			}
			Seats[SeatIndex].WeaponEffects[i].Effect.SetStaticMesh(GRI.VehicleWeaponEffects[OverlayIndex].Mesh);
			Seats[SeatIndex].WeaponEffects[i].Effect.SetMaterial(0, GRI.VehicleWeaponEffects[OverlayIndex].Material);
			if (!Seats[SeatIndex].WeaponEffects[i].Effect.bAttached)
			{
				Mesh.AttachComponentToSocket(Seats[SeatIndex].WeaponEffects[i].Effect, Seats[SeatIndex].WeaponEffects[i].SocketName);
			}
		}
	}
}


exec function EditUDmgFX(optional int Index)
{
	if (WorldInfo.NetMode == NM_Standalone)
	{
		class<UTInventory>(DynamicLoadObject("UTGameContent.UTUDamage", class'Class')).static.AddWeaponOverlay(UTGameReplicationInfo(WorldInfo.GRI));
		ApplyWeaponEffects(1, 0);
		ConsoleCommand("EditObject name=" $ string(self) $ "_WeaponEffect_" $ Index);
	}
}


/** Notification that this vehicle has hit a ForcedDirVolume. If it returns FALSE, volume will not affect it. */
function bool OnTouchForcedDirVolume(ForcedDirVolume Vol)
{
	return TRUE;
}

/** @return if this vehicle is being towed, return the vehicle that is towing it */
function UTVehicle GetTowingVehicle();

/** @return a list of vehicles this one is towing */
function GetTowedVehicles(out array<UTVehicle> TowedVehicles)
{
	local UTVehicle V;

	if (bIsTowingHoverboard)
	{
		foreach WorldInfo.AllPawns(class'UTVehicle', V)
		{
			if (V.GetTowingVehicle() == self)
			{
				TowedVehicles.AddItem(V);
			}
		}
	}
}

/** if TowingVehicle is a valid vehicle to tow, tell bot how to hook up to it
 * @return whether the bot was given instructions
 */
function bool TryAttachingTowCable(UTBot B, UTVehicle TowingVehicle);

/** detach this vehicle's tow cable (used by AI) */
function DetachTowCable();

/** @return whether bot should leave this vehicle if it encounters combat */
function bool ShouldLeaveForCombat(UTBot B)
{
	return bShouldLeaveForCombat;
}

/** returns true if vehicle should charge attack this node (also responsible for setting up charge */
function bool ChargeAttackObjective(UTBot B, UTGameObjective O)
{
	return false;
}

defaultproperties
{
   bTeamLocked=True
   bValidLinkTarget=True
   bEnteringUnlocks=True
   bUseAlternatePaths=True
   bEjectPassengersWhenFlipped=True
   bMustBeUpright=True
   bShouldAutoCenterViewPitch=True
   bDrawHealthOnHUD=True
   bAllowedExit=True
   bFindGroundExit=True
   bTakeWaterDamageWhileDriving=True
   bNoZSmoothing=True
   bNoZDampingInAir=True
   bDisplayHealthBar=True
   VehicleLockedSound=SoundCue'A_Vehicle_Generic.Vehicle.VehicleNoEntry01Cue'
   Team=128
   Begin Object Class=DynamicLightEnvironmentComponent Name=MyLightEnvironment ObjName=MyLightEnvironment Archetype=DynamicLightEnvironmentComponent'Engine.Default__DynamicLightEnvironmentComponent'
      AmbientGlow=(R=0.200000,G=0.200000,B=0.200000,A=1.000000)
      Name="MyLightEnvironment"
      ObjectArchetype=DynamicLightEnvironmentComponent'Engine.Default__DynamicLightEnvironmentComponent'
   End Object
   LightEnvironment=MyLightEnvironment
   RespawnTime=30.000000
   LinkHealMult=0.350000
   LinkedToCue=SoundCue'A_Vehicle_Generic.Vehicle.VehicleChargeLoopCue'
   LinkedEndSound=SoundCue'A_Vehicle_Generic.Vehicle.VehicleChargeCompleteCue'
   DriverStatusChangedWaveform=ForceFeedbackWaveform'UTGame.Default__UTVehicle:ForceFeedbackWaveformVehicleEnter'
   MaxDesireability=0.500000
   ObjectiveGetOutDist=1000.000000
   HornSounds(0)=SoundCue'A_Vehicle_Hellbender.SoundCues.A_Vehicle_Hellbender_Horn'
   HornSounds(1)=SoundCue'A_Vehicle_Generic.Vehicle.VehicleHornCue'
   HornSounds(2)=SoundCue'A_Vehicle_Generic.Vehicle.Vehicle_Horn_SmallNecris01Cue'
   HornSounds(3)=SoundCue'A_Vehicle_Generic.Vehicle.Vehicle_Horn_LargeNecris03Cue'
   HornAIRadius=800.000000
   VehicleIndex=-1
   LookSteerSensitivity=2.000000
   ConsoleSteerScale=1.500000
   LockedOnSound=SoundCue'A_Weapon_Avril.WAV.A_Weapon_AVRiL_Lock01Cue'
   RanOverDamageType=Class'UTGame.UTDmgType_RanOver'
   MinRunOverSpeed=250.000000
   StolenAnnouncementIndex=4
   MinRunOverWarningAim=0.880000
   VehiclePositionString="in a vehicle"
   VehicleNameString="Vehicle"
   NeedToPickUpAnnouncement=(AnnouncementText="Man the Key Vehicle!")
   TeamBeaconMaxDist=5000.000000
   TeamBeaconPlayerInfoMaxDist=3000.000000
   HUDExtent=100.000000
   WaterDamage=20.000000
   VehicleDrowningDamType=Class'UTGame.UTDmgType_Drowned'
   ExplosionLightClass=Class'UTGame.UTTankShellExplosionLight'
   MaxExplosionLightDistance=4000.000000
   TimeTilSecondaryVehicleExplosion=2.000000
   VehicleSounds(0)=(SoundStartTag="DamageSmoke",SoundEndTag="NoDamageSmoke",SoundTemplate=SoundCue'A_Vehicle_Generic.Vehicle.Vehicle_Damage_FireLoop_Cue')
   VehiclePieceClass=Class'UTGame.UTGib_VehiclePiece'
   DamageSmokeThreshold=0.650000
   FireDamageThreshold=0.400000
   FireDamagePerSec=2.000000
   UpsideDownDamagePerSec=500.000000
   OccupiedUpsideDownDamagePerSec=200.000000
   ExplosionDamageType=Class'UTGame.UTDmgType_VehicleExplosion'
   MaxImpactEffectDistance=6000.000000
   MaxFireEffectDistance=7000.000000
   ExplosionTemplate=ParticleSystem'FX_VehicleExplosions.Effects.P_FX_GeneralExplosion'
   BigExplosionTemplates(0)=(Template=ParticleSystem'FX_VehicleExplosions.Effects.P_FX_VehicleDeathExplosion')
   SecondaryExplosion=ParticleSystem'Envy_Effects.VH_Deaths.P_VH_Death_Dust_Secondary'
   MaxWheelEffectDistSq=16000000.000000
   WaterEffectType="Water"
   BurnOutTime=2.500000
   DeadVehicleLifeSpan=9.000000
   ExplosionDamage=100.000000
   ExplosionRadius=300.000000
   ExplosionMomentum=60000.000000
   ExplosionInAirAngVel=1.500000
   DeathExplosionShake=CameraAnim'Envy_Effects.Camera_Shakes.C_VH_Death_Shake'
   InnerExplosionShakeRadius=400.000000
   OuterExplosionShakeRadius=1000.000000
   TurretScaleControlName="TurretScale"
   TurretSocketName="VH_Death"
   DistanceTurretExplosionTemplates(0)=(Template=ParticleSystem'Envy_Effects.VH_Deaths.P_VH_Death_SpecialCase_1_Base_Near',MinDistance=1500.000000)
   DistanceTurretExplosionTemplates(1)=(Template=ParticleSystem'Envy_Effects.VH_Deaths.P_VH_Death_SpecialCase_1_Base_Far')
   TurretOffset=(X=0.000000,Y=0.000000,Z=200.000000)
   TurretExplosiveForce=10000.000000
   ImpactHitSound=SoundCue'A_Weapon_ImpactHammer.ImpactHammer.A_Weapon_ImpactHammer_FireImpactVehicle_Cue'
   LargeChunkImpactSound=SoundCue'A_Vehicle_Generic.Vehicle.VehicleImpact_MetalLargeCue'
   MediumChunkImpactSound=SoundCue'A_Vehicle_Generic.Vehicle.VehicleImpact_MetalMediumCue'
   SmallChunkImpactSound=SoundCue'A_Vehicle_Generic.Vehicle.VehicleImpact_MetalSmallCue'
   BurnTimeParameterName="BurnTime"
   SpawnRadius=320.000000
   DrivingAnim="manta_idle_sitting"
   SpawnInSound=SoundCue'A_Vehicle_Generic.Vehicle.VehicleFadeIn01Cue'
   SpawnOutSound=SoundCue'A_Vehicle_Generic.Vehicle.VehicleFadeOut01Cue'
   FlagOffset=(X=0.000000,Y=0.000000,Z=120.000000)
   FlagRotation=(Pitch=0,Yaw=32768,Roll=0)
   MapSize=0.750000
   IconCoords=(U=831.000000,V=21.000000,UL=38.000000,VL=30.000000)
   FlipToolTipIconCoords=(U=2.000000,V=766.000000,UL=79.000000,VL=71.000000)
   EnterToolTipIconCoords=(U=96.000000,V=249.000000,UL=77.000000,VL=64.000000)
   DropFlagIconCoords=(U=85.000000,V=767.000000,UL=66.000000,VL=48.000000)
   DropOrbIconCoords=(U=109.000000,V=815.000000,UL=55.000000,VL=38.000000)
   ChargeBarCoords=(U=276.000000,V=407.000000,UL=9.000000,VL=63.000000)
   ChargeBarEndCapCoords=(U=276.000000,V=407.000000,UL=9.000000,VL=6.000000)
   ChargeBarPosX=2.000000
   ChargeBarWidth=10.000000
   ShowLockedMaxDist=3000.000000
   TeamBeaconOffset=(X=0.000000,Y=0.000000,Z=100.000000)
   PassengerTeamBeaconOffset=(X=0.000000,Y=0.000000,Z=100.000000)
   SpawnInTemplates(0)=ParticleSystem'VH_All.Effects.P_VH_All_Spawn_Red'
   SpawnInTemplates(1)=ParticleSystem'VH_All.Effects.P_VH_All_Spawn_Blue'
   SpawnMaterialParameterName="ResInAmount"
   SpawnMaterialParameterCurve=(Points=(,(InVal=4.000000,OutVal=2.500000)))
   SpawnInTime=4.000000
   CollisionDamageMult=0.002000
   DestroyOnPenetrationThreshold=50.000000
   DestroyOnPenetrationDuration=1.000000
   SeatCameraScale=1.000000
   CameraSmoothingFactor=2.000000
   DefaultFOV=75.000000
   CameraLag=0.120000
   MinCameraDistSq=1.000000
   DisabledTime=20.000000
   DisabledTemplate=ParticleSystem'PICKUPS.Deployables.Effects.P_Deployables_EMP_Mine_VehicleDisabled'
   LastEnemyWarningTime=-100.000000
   GreedCoinBonus=2
   bCanFlip=False
   Begin Object Class=RB_StayUprightSetup Name=MyStayUprightSetup ObjName=MyStayUprightSetup Archetype=RB_StayUprightSetup'UTGame.Default__UTVehicleBase:MyStayUprightSetup'
      ObjectArchetype=RB_StayUprightSetup'UTGame.Default__UTVehicleBase:MyStayUprightSetup'
   End Object
   StayUprightConstraintSetup=RB_StayUprightSetup'UTGame.Default__UTVehicle:MyStayUprightSetup'
   Begin Object Class=RB_ConstraintInstance Name=MyStayUprightConstraintInstance ObjName=MyStayUprightConstraintInstance Archetype=RB_ConstraintInstance'UTGame.Default__UTVehicleBase:MyStayUprightConstraintInstance'
      ObjectArchetype=RB_ConstraintInstance'UTGame.Default__UTVehicleBase:MyStayUprightConstraintInstance'
   End Object
   StayUprightConstraintInstance=RB_ConstraintInstance'UTGame.Default__UTVehicle:MyStayUprightConstraintInstance'
   MomentumMult=2.000000
   CrushedDamageType=Class'UTGame.UTDmgType_Pancake'
   MinCrushSpeed=100.000000
   BaseEyeHeight=30.000000
   EyeHeight=30.000000
   Begin Object Class=SkeletalMeshComponent Name=SVehicleMesh ObjName=SVehicleMesh Archetype=SkeletalMeshComponent'UTGame.Default__UTVehicleBase:SVehicleMesh'
      bOverrideAttachmentOwnerVisibility=True
      LightEnvironment=DynamicLightEnvironmentComponent'UTGame.Default__UTVehicle:MyLightEnvironment'
      ObjectArchetype=SkeletalMeshComponent'UTGame.Default__UTVehicleBase:SVehicleMesh'
   End Object
   Mesh=SVehicleMesh
   Begin Object Class=CylinderComponent Name=CollisionCylinder ObjName=CollisionCylinder Archetype=CylinderComponent'UTGame.Default__UTVehicleBase:CollisionCylinder'
      CollideActors=False
      BlockActors=False
      BlockZeroExtent=False
      BlockNonZeroExtent=False
      ObjectArchetype=CylinderComponent'UTGame.Default__UTVehicleBase:CollisionCylinder'
   End Object
   CylinderComponent=CollisionCylinder
   ViewPitchMin=-15000.000000
   InventoryManagerClass=Class'UTGame.UTInventoryManager'
   Components(0)=CollisionCylinder
   Components(1)=SVehicleMesh
   Components(2)=MyLightEnvironment
   bPushedByEncroachers=False
   bAlwaysRelevant=True
   CollisionComponent=SVehicleMesh
   Name="Default__UTVehicle"
   ObjectArchetype=UTVehicleBase'UTGame.Default__UTVehicleBase'
}

Overview Package Class Source Class tree Glossary
previous class      next class frames      no frames
Class file time: tr 31-1-2018 17:18:26.000 - Creation time: sk 18-3-2018 10:01:28.004 - Created with UnCodeX