-
Notifications
You must be signed in to change notification settings - Fork 3
/
RN_DetourCrowd.pas
1884 lines (1538 loc) · 60.2 KB
/
RN_DetourCrowd.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
{$POINTERMATH ON}
unit RN_DetourCrowd;
interface
uses Math, SysUtils, RN_DetourNavMesh, RN_DetourNavMeshHelper, RN_DetourNavMeshQuery, RN_DetourObstacleAvoidance,
RN_DetourLocalBoundary, RN_DetourPathCorridor, RN_DetourProximityGrid, RN_DetourPathQueue;
/// The maximum number of neighbors that a crowd agent can take into account
/// for steering decisions.
/// @ingroup crowd
const DT_CROWDAGENT_MAX_NEIGHBOURS = 6;
/// The maximum number of corners a crowd agent will look ahead in the path.
/// This value is used for sizing the crowd agent corner buffers.
/// Due to the behavior of the crowd manager, the actual number of useful
/// corners will be one less than this number.
/// @ingroup crowd
const DT_CROWDAGENT_MAX_CORNERS = 4;
/// The maximum number of crowd avoidance configurations supported by the
/// crowd manager.
/// @ingroup crowd
/// @see dtObstacleAvoidanceParams, dtCrowd::setObstacleAvoidanceParams(), dtCrowd::getObstacleAvoidanceParams(),
/// dtCrowdAgentParams::obstacleAvoidanceType
const DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS = 8;
/// The maximum number of query filter types supported by the crowd manager.
/// @ingroup crowd
/// @see dtQueryFilter, dtCrowd::getFilter() dtCrowd::getEditableFilter(),
/// dtCrowdAgentParams::queryFilterType
const DT_CROWD_MAX_QUERY_FILTER_TYPE = 16;
/// Provides neighbor data for agents managed by the crowd.
/// @ingroup crowd
/// @see dtCrowdAgent::neis, dtCrowd
type
PdtCrowdNeighbour = ^TdtCrowdNeighbour;
TdtCrowdNeighbour = record
idx: Integer; ///< The index of the neighbor in the crowd.
dist: Single; ///< The distance between the current agent and the neighbor.
end;
/// The type of navigation mesh polygon the agent is currently traversing.
/// @ingroup crowd
TCrowdAgentState =
(
DT_CROWDAGENT_STATE_INVALID, ///< The agent is not in a valid state.
DT_CROWDAGENT_STATE_WALKING, ///< The agent is traversing a normal navigation mesh polygon.
DT_CROWDAGENT_STATE_OFFMESH ///< The agent is traversing an off-mesh connection.
);
/// Configuration parameters for a crowd agent.
/// @ingroup crowd
PdtCrowdAgentParams = ^TdtCrowdAgentParams;
TdtCrowdAgentParams = record
radius: Single; ///< Agent radius. [Limit: >= 0]
height: Single; ///< Agent height. [Limit: > 0]
maxAcceleration: Single; ///< Maximum allowed acceleration. [Limit: >= 0]
maxSpeed: Single; ///< Maximum allowed speed. [Limit: >= 0]
/// Defines how close a collision element must be before it is considered for steering behaviors. [Limits: > 0]
collisionQueryRange: Single;
pathOptimizationRange: Single; ///< The path visibility optimization range. [Limit: > 0]
/// How aggresive the agent manager should be at avoiding collisions with this agent. [Limit: >= 0]
separationWeight: Single;
/// Flags that impact steering behavior. (See: #UpdateFlags)
updateFlags: Byte;
/// The index of the avoidance configuration to use for the agent.
/// [Limits: 0 <= value <= #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
obstacleAvoidanceType: Byte;
/// The index of the query filter used by this agent.
queryFilterType: Byte;
/// User defined data attached to the agent.
userData: Pointer;
end;
TMoveRequestState =
(
DT_CROWDAGENT_TARGET_NONE = 0,
DT_CROWDAGENT_TARGET_FAILED,
DT_CROWDAGENT_TARGET_VALID,
DT_CROWDAGENT_TARGET_REQUESTING,
DT_CROWDAGENT_TARGET_WAITING_FOR_QUEUE,
DT_CROWDAGENT_TARGET_WAITING_FOR_PATH,
DT_CROWDAGENT_TARGET_VELOCITY
);
/// Represents an agent managed by a #dtCrowd object.
/// @ingroup crowd
PPdtCrowdAgent = ^PdtCrowdAgent;
PdtCrowdAgent = ^TdtCrowdAgent;
TdtCrowdAgent = record
/// True if the agent is active, false if the agent is in an unused slot in the agent pool.
active: Boolean;
/// The type of mesh polygon the agent is traversing. (See: #CrowdAgentState)
state: TCrowdAgentState;
/// True if the agent has valid path (targetState == DT_CROWDAGENT_TARGET_VALID) and the path does not lead to the requested position, else false.
partial: Boolean;
/// The path corridor the agent is using.
corridor: TdtPathCorridor;
/// The local boundary data for the agent.
boundary: TdtLocalBoundary;
/// Time since the agent's path corridor was optimized.
topologyOptTime: Single;
/// The known neighbors of the agent.
neis: array [0..DT_CROWDAGENT_MAX_NEIGHBOURS-1] of TdtCrowdNeighbour;
/// The number of neighbors.
nneis: Integer;
/// The desired speed.
desiredSpeed: Single;
npos: array [0..2] of Single; ///< The current agent position. [(x, y, z)]
disp: array [0..2] of Single;
dvel: array [0..2] of Single; ///< The desired velocity of the agent. [(x, y, z)]
nvel: array [0..2] of Single;
vel: array [0..2] of Single; ///< The actual velocity of the agent. [(x, y, z)]
/// The agent's configuration parameters.
params: TdtCrowdAgentParams;
/// The local path corridor corners for the agent. (Staight path.) [(x, y, z) * #ncorners]
cornerVerts: array [0..DT_CROWDAGENT_MAX_CORNERS*3-1] of Single;
/// The local path corridor corner flags. (See: #dtStraightPathFlags) [(flags) * #ncorners]
cornerFlags: array [0..DT_CROWDAGENT_MAX_CORNERS-1] of Byte;
/// The reference id of the polygon being entered at the corner. [(polyRef) * #ncorners]
cornerPolys: array [0..DT_CROWDAGENT_MAX_CORNERS-1] of TdtPolyRef;
/// The number of corners.
ncorners: Integer;
targetState: TMoveRequestState; ///< State of the movement request.
targetRef: TdtPolyRef; ///< Target polyref of the movement request.
targetPos: array [0..2] of Single; ///< Target position of the movement request (or velocity in case of DT_CROWDAGENT_TARGET_VELOCITY).
targetPathqRef: TdtPathQueueRef; ///< Path finder ref.
targetReplan: Boolean; ///< Flag indicating that the current path is being replanned.
targetReplanTime: Single; /// <Time since the agent's target was replanned.
end;
PdtCrowdAgentAnimation = ^TdtCrowdAgentAnimation;
TdtCrowdAgentAnimation = record
active: Boolean;
initPos, startPos, endPos: array [0..2] of Single;
polyRef: TdtPolyRef;
t, tmax: Single;
end;
/// Crowd agent update flags.
/// @ingroup crowd
/// @see dtCrowdAgentParams::updateFlags
const
DT_CROWD_ANTICIPATE_TURNS = 1;
DT_CROWD_OBSTACLE_AVOIDANCE = 2;
DT_CROWD_SEPARATION = 4;
DT_CROWD_OPTIMIZE_VIS = 8; ///< Use #dtPathCorridor::optimizePathVisibility() to optimize the agent path.
DT_CROWD_OPTIMIZE_TOPO = 16; ///< Use dtPathCorridor::optimizePathTopology() to optimize the agent path.
type
PdtCrowdAgentDebugInfo = ^TdtCrowdAgentDebugInfo;
TdtCrowdAgentDebugInfo = record
idx: Integer;
optStart, optEnd: array [0..2] of Single;
vod: TdtObstacleAvoidanceDebugData;
end;
/// Provides local steering behaviors for a group of agents.
/// @ingroup crowd
TdtCrowd = class
private
m_maxAgents: Integer;
m_agents: PdtCrowdAgent;
m_activeAgents: PPdtCrowdAgent;
m_agentAnims: PdtCrowdAgentAnimation;
m_pathq: TdtPathQueue;
m_obstacleQueryParams: array [0..DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS-1] of TdtObstacleAvoidanceParams;
m_obstacleQuery: TdtObstacleAvoidanceQuery;
m_grid: TdtProximityGrid;
m_pathResult: PdtPolyRef;
m_maxPathResult: Integer;
m_ext: array [0..2] of Single;
m_filters: array [0..DT_CROWD_MAX_QUERY_FILTER_TYPE-1] of TdtQueryFilter;
m_maxAgentRadius: Single;
m_velocitySampleCount: Integer;
m_navquery: TdtNavMeshQuery;
procedure updateTopologyOptimization(agents: PPdtCrowdAgent; const nagents: Integer; const dt: Single);
procedure updateMoveRequest(const dt: Single);
procedure checkPathValidity(agents: PPdtCrowdAgent; const nagents: Integer; const dt: Single);
function getAgentIndex(agent: PdtCrowdAgent): Integer; { return (int)(agent - m_agents); }
function requestMoveTargetReplan(const idx: Integer; ref: TdtPolyRef; const pos: PSingle): Boolean;
procedure purge();
public
constructor Create;
destructor Destroy; override;
/// Initializes the crowd.
/// @param[in] maxAgents The maximum number of agents the crowd can manage. [Limit: >= 1]
/// @param[in] maxAgentRadius The maximum radius of any agent that will be added to the crowd. [Limit: > 0]
/// @param[in] nav The navigation mesh to use for planning.
/// @return True if the initialization succeeded.
function init(const maxAgents: Integer; const maxAgentRadius: Single; nav: TdtNavMesh): Boolean;
/// Sets the shared avoidance configuration for the specified index.
/// @param[in] idx The index. [Limits: 0 <= value < #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
/// @param[in] params The new configuration.
procedure setObstacleAvoidanceParams(const idx: Integer; const params: PdtObstacleAvoidanceParams);
/// Gets the shared avoidance configuration for the specified index.
/// @param[in] idx The index of the configuration to retreive.
/// [Limits: 0 <= value < #DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS]
/// @return The requested configuration.
function getObstacleAvoidanceParams(const idx: Integer): PdtObstacleAvoidanceParams;
/// Gets the specified agent from the pool.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @return The requested agent.
function getAgent(const idx: Integer): PdtCrowdAgent;
/// Gets the specified agent from the pool.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @return The requested agent.
function getEditableAgent(const idx: Integer): PdtCrowdAgent;
/// The maximum number of agents that can be managed by the object.
/// @return The maximum number of agents.
function getAgentCount(): Integer;
/// Adds a new agent to the crowd.
/// @param[in] pos The requested position of the agent. [(x, y, z)]
/// @param[in] params The configutation of the agent.
/// @return The index of the agent in the agent pool. Or -1 if the agent could not be added.
function addAgent(const pos: PSingle; const params: PdtCrowdAgentParams): Integer;
/// Updates the specified agent's configuration.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @param[in] params The new agent configuration.
procedure updateAgentParameters(const idx: Integer; const params: PdtCrowdAgentParams);
/// Removes the agent from the crowd.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
procedure removeAgent(const idx: Integer);
/// Submits a new move request for the specified agent.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @param[in] ref The position's polygon reference.
/// @param[in] pos The position within the polygon. [(x, y, z)]
/// @return True if the request was successfully submitted.
function requestMoveTarget(const idx: Integer; ref: TdtPolyRef; const pos: PSingle): Boolean;
/// Submits a new move request for the specified agent.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @param[in] vel The movement velocity. [(x, y, z)]
/// @return True if the request was successfully submitted.
function requestMoveVelocity(const idx: Integer; const vel: PSingle): Boolean;
/// Resets any request for the specified agent.
/// @param[in] idx The agent index. [Limits: 0 <= value < #getAgentCount()]
/// @return True if the request was successfully reseted.
function resetMoveTarget(const idx: Integer): Boolean;
/// Gets the active agents int the agent pool.
/// @param[out] agents An array of agent pointers. [(#dtCrowdAgent *) * maxAgents]
/// @param[in] maxAgents The size of the crowd agent array.
/// @return The number of agents returned in @p agents.
function getActiveAgents(agents: PPdtCrowdAgent; const maxAgents: Integer): Integer;
/// Updates the steering and positions of all agents.
/// @param[in] dt The time, in seconds, to update the simulation. [Limit: > 0]
/// @param[out] debug A debug object to load with debug information. [Opt]
procedure update(const dt: Single; debug: PdtCrowdAgentDebugInfo);
/// Gets the filter used by the crowd.
/// @return The filter used by the crowd.
function getFilter(const i: Integer): TdtQueryFilter; { return (i >= 0 && i < DT_CROWD_MAX_QUERY_FILTER_TYPE) ? &m_filters[i] : 0; }
/// Gets the filter used by the crowd.
/// @return The filter used by the crowd.
function getEditableFilter(const i: Integer): TdtQueryFilter; { return (i >= 0 && i < DT_CROWD_MAX_QUERY_FILTER_TYPE) ? &m_filters[i] : 0; }
/// Gets the search extents [(x, y, z)] used by the crowd for query operations.
/// @return The search extents used by the crowd. [(x, y, z)]
function getQueryExtents(): PSingle; { return m_ext; }
/// Gets the velocity sample count.
/// @return The velocity sample count.
property getVelocitySampleCount: Integer read m_velocitySampleCount;
/// Gets the crowd's proximity grid.
/// @return The crowd's proximity grid.
property getGrid: TdtProximityGrid read m_grid;
/// Gets the crowd's path request queue.
/// @return The crowd's path request queue.
property getPathQueue: TdtPathQueue read m_pathq;
/// Gets the query object used by the crowd.
property getNavMeshQuery: TdtNavMeshQuery read m_navquery;
end;
/// Allocates a crowd object using the Detour allocator.
/// @return A crowd object that is ready for initialization, or null on failure.
/// @ingroup crowd
function dtAllocCrowd(): TdtCrowd;
/// Frees the specified crowd object using the Detour allocator.
/// @param[in] ptr A crowd object allocated using #dtAllocCrowd
/// @ingroup crowd
procedure dtFreeCrowd(var ptr: TdtCrowd);
//Delphi. Added to be accessible from outside this unit, for debug render
procedure calcSmoothSteerDirection(const ag: PdtCrowdAgent; dir: PSingle);
///////////////////////////////////////////////////////////////////////////
// This section contains detailed documentation for members that don't have
// a source file. It reduces clutter in the main section of the header.
(**
@defgroup crowd Crowd
Members in this module implement local steering and dynamic avoidance features.
The crowd is the big beast of the navigation features. It not only handles a
lot of the path management for you, but also local steering and dynamic
avoidance between members of the crowd. I.e. It can keep your agents from
running into each other.
Main class: #dtCrowd
The #dtNavMeshQuery and #dtPathCorridor classes provide perfectly good, easy
to use path planning features. But in the end they only give you points that
your navigation client should be moving toward. When it comes to deciding things
like agent velocity and steering to avoid other agents, that is up to you to
implement. Unless, of course, you decide to use #dtCrowd.
Basically, you add an agent to the crowd, providing various configuration
settings such as maximum speed and acceleration. You also provide a local
target to more toward. The crowd manager then provides, with every update, the
new agent position and velocity for the frame. The movement will be
constrained to the navigation mesh, and steering will be applied to ensure
agents managed by the crowd do not collide with each other.
This is very powerful feature set. But it comes with limitations.
The biggest limitation is that you must give control of the agent's position
completely over to the crowd manager. You can update things like maximum speed
and acceleration. But in order for the crowd manager to do its thing, it can't
allow you to constantly be giving it overrides to position and velocity. So
you give up direct control of the agent's movement. It belongs to the crowd.
The second biggest limitation revolves around the fact that the crowd manager
deals with local planning. So the agent's target should never be more than
256 polygons aways from its current position. If it is, you risk
your agent failing to reach its target. So you may still need to do long
distance planning and provide the crowd manager with intermediate targets.
Other significant limitations:
- All agents using the crowd manager will use the same #dtQueryFilter.
- Crowd management is relatively expensive. The maximum agents under crowd
management at any one time is between 20 and 30. A good place to start
is a maximum of 25 agents for 0.5ms per frame.
@note This is a summary list of members. Use the index or search
feature to find minor members.
@struct dtCrowdAgentParams
@see dtCrowdAgent, dtCrowd::addAgent(), dtCrowd::updateAgentParameters()
@var dtCrowdAgentParams::obstacleAvoidanceType
@par
#dtCrowd permits agents to use different avoidance configurations. This value
is the index of the #dtObstacleAvoidanceParams within the crowd.
@see dtObstacleAvoidanceParams, dtCrowd::setObstacleAvoidanceParams(),
dtCrowd::getObstacleAvoidanceParams()
@var dtCrowdAgentParams::collisionQueryRange
@par
Collision elements include other agents and navigation mesh boundaries.
This value is often based on the agent radius and/or maximum speed. E.g. radius * 8
@var dtCrowdAgentParams::pathOptimizationRange
@par
Only applicalbe if #updateFlags includes the #DT_CROWD_OPTIMIZE_VIS flag.
This value is often based on the agent radius. E.g. radius * 30
@see dtPathCorridor::optimizePathVisibility()
@var dtCrowdAgentParams::separationWeight
@par
A higher value will result in agents trying to stay farther away from each other at
the cost of more difficult steering in tight spaces.
*)
implementation
uses RN_DetourCommon, RN_DetourStatus;
function dtAllocCrowd(): TdtCrowd;
begin
Result := TdtCrowd.Create;
end;
procedure dtFreeCrowd(var ptr: TdtCrowd);
begin
FreeAndNil(ptr);
end;
const MAX_ITERS_PER_UPDATE = 100;
const MAX_PATHQUEUE_NODES = 4096;
const MAX_COMMON_NODES = 512;
function tween(const t, t0, t1: Single): Single;
begin
Result := dtClamp((t-t0) / (t1-t0), 0.0, 1.0);
end;
procedure integrate(ag: PdtCrowdAgent; const dt: Single);
var maxDelta, ds: Single; dv: array [0..2] of Single;
begin
// Fake dynamic constraint.
maxDelta := ag.params.maxAcceleration * dt;
dtVsub(@dv[0], @ag.nvel[0], @ag.vel[0]);
ds := dtVlen(@dv[0]);
if (ds > maxDelta) then
dtVscale(@dv[0], @dv[0], maxDelta/ds);
dtVadd(@ag.vel[0], @ag.vel[0], @dv[0]);
// Integrate
if (dtVlen(@ag.vel[0]) > 0.0001) then
dtVmad(@ag.npos[0], @ag.npos[0], @ag.vel[0], dt)
else
dtVset(@ag.vel[0],0,0,0);
end;
function overOffmeshConnection(const ag: PdtCrowdAgent; const radius: Single): Boolean;
var offMeshConnection: Boolean; distSq: Single;
begin
if (ag.ncorners = 0) then
Exit(false);
offMeshConnection := (ag.cornerFlags[ag.ncorners-1] and Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION)) <> 0;
if (offMeshConnection) then
begin
distSq := dtVdist2DSqr(@ag.npos[0], @ag.cornerVerts[(ag.ncorners-1)*3]);
if (distSq < radius*radius) then
Exit(true);
end;
Result := false;
end;
function getDistanceToGoal(const ag: PdtCrowdAgent; const range: Single): Single;
var endOfPath: Boolean;
begin
if (ag.ncorners = 0) then
Exit(range);
endOfPath := (ag.cornerFlags[ag.ncorners-1] and Byte(DT_STRAIGHTPATH_END)) <> 0;
if (endOfPath) then
Exit(dtMin(dtVdist2D(@ag.npos[0], @ag.cornerVerts[(ag.ncorners-1)*3]), range));
Result := range;
end;
procedure calcSmoothSteerDirection(const ag: PdtCrowdAgent; dir: PSingle);
var ip0, ip1: Integer; p0, p1: PSingle; dir0, dir1: array [0..2] of Single; len0, len1: Single;
begin
if (ag.ncorners = 0) then
begin
dtVset(dir, 0,0,0);
Exit;
end;
ip0 := 0;
ip1 := dtMin(1, ag.ncorners-1);
p0 := @ag.cornerVerts[ip0*3];
p1 := @ag.cornerVerts[ip1*3];
dtVsub(@dir0[0], p0, @ag.npos[0]);
dtVsub(@dir1[0], p1, @ag.npos[0]);
dir0[1] := 0;
dir1[1] := 0;
len0 := dtVlen(@dir0[0]);
len1 := dtVlen(@dir1[0]);
if (len1 > 0.001) then
dtVscale(@dir1[0],@dir1[0],1.0/len1);
dir[0] := dir0[0] - dir1[0]*len0*0.5;
dir[1] := 0;
dir[2] := dir0[2] - dir1[2]*len0*0.5;
dtVnormalize(dir);
end;
procedure calcStraightSteerDirection(const ag: PdtCrowdAgent; dir: PSingle);
begin
if (ag.ncorners = 0) then
begin
dtVset(dir, 0,0,0);
Exit;
end;
dtVsub(dir, @ag.cornerVerts[0], @ag.npos[0]);
dir[1] := 0;
dtVnormalize(dir);
end;
function addNeighbour(const idx: Integer; const dist: Single;
neis: PdtCrowdNeighbour; const nneis, maxNeis: Integer): Integer;
var nei: PdtCrowdNeighbour; i, tgt, n: Integer;
begin
// Insert neighbour based on the distance.
if (nneis = 0) then
begin
nei := @neis[nneis];
end
else if (dist >= neis[nneis-1].dist) then
begin
if (nneis >= maxNeis) then
Exit(nneis);
nei := @neis[nneis];
end
else
begin
for i := 0 to nneis - 1 do
if (dist <= neis[i].dist) then
break;
tgt := i+1;
n := dtMin(nneis-i, maxNeis-tgt);
Assert(tgt+n <= maxNeis);
if (n > 0) then
Move(neis[i], neis[tgt], sizeof(TdtCrowdNeighbour)*n);
nei := @neis[i];
end;
FillChar(nei^, sizeof(TdtCrowdNeighbour), 0);
nei.idx := idx;
nei.dist := dist;
Result := dtMin(nneis+1, maxNeis);
end;
function getNeighbours(const pos: PSingle; const height, range: Single;
const skip: PdtCrowdAgent; reslt: PdtCrowdNeighbour; const maxResult: Integer;
agents: PPdtCrowdAgent; const nagents: Integer; grid: TdtProximityGrid): Integer;
const MAX_NEIS = 32;
var n, nids, i: Integer; ids: array [0..MAX_NEIS-1] of Word; ag: PdtCrowdAgent; diff: array [0..2] of Single; distSqr: Single;
begin
n := 0;
nids := grid.queryItems(pos[0]-range, pos[2]-range,
pos[0]+range, pos[2]+range,
@ids[0], MAX_NEIS);
for i := 0 to nids - 1 do
begin
ag := agents[ids[i]];
if (ag = skip) then continue;
// Check for overlap.
dtVsub(@diff[0], pos, @ag.npos[0]);
if (Abs(diff[1]) >= (height+ag.params.height)/2.0) then
continue;
diff[1] := 0;
distSqr := dtVlenSqr(@diff[0]);
if (distSqr > Sqr(range)) then
continue;
n := addNeighbour(ids[i], distSqr, reslt, n, maxResult);
end;
Result := n;
end;
function addToOptQueue(newag: PdtCrowdAgent; agents: PPdtCrowdAgent; const nagents, maxAgents: Integer): Integer;
var slot, i, tgt, n: Integer;
begin
// Insert neighbour based on greatest time.
if (nagents = 0) then
begin
slot := nagents;
end
else if (newag.topologyOptTime <= agents[nagents-1].topologyOptTime) then
begin
if (nagents >= maxAgents) then
Exit(nagents);
slot := nagents;
end
else
begin
for i := 0 to nagents - 1 do
if (newag.topologyOptTime >= agents[i].topologyOptTime) then
break;
tgt := i+1;
n := dtMin(nagents-i, maxAgents-tgt);
Assert(tgt+n <= maxAgents);
if (n > 0) then
Move(agents[i], agents[tgt], sizeof(PdtCrowdAgent)*n);
slot := i;
end;
agents[slot] := newag;
Result := dtMin(nagents+1, maxAgents);
end;
function addToPathQueue(newag: PdtCrowdAgent; agents: PPdtCrowdAgent; const nagents, maxAgents: Integer): Integer;
var slot, i, tgt, n: Integer;
begin
// Insert neighbour based on greatest time.
if (nagents = 0) then
begin
slot := nagents;
end
else if (newag.targetReplanTime <= agents[nagents-1].targetReplanTime) then
begin
if (nagents >= maxAgents) then
Exit(nagents);
slot := nagents;
end
else
begin
for i := 0 to nagents - 1 do
if (newag.targetReplanTime >= agents[i].targetReplanTime) then
break;
tgt := i+1;
n := dtMin(nagents-i, maxAgents-tgt);
Assert(tgt+n <= maxAgents);
if (n > 0) then
Move(agents[i], agents[tgt], sizeof(PdtCrowdAgent)*n);
slot := i;
end;
agents[slot] := newag;
Result := dtMin(nagents+1, maxAgents);
end;
(**
@class dtCrowd
@par
This is the core class of the @ref crowd module. See the @ref crowd documentation for a summary
of the crowd features.
A common method for setting up the crowd is as follows:
-# Allocate the crowd using #dtAllocCrowd.
-# Initialize the crowd using #init().
-# Set the avoidance configurations using #setObstacleAvoidanceParams().
-# Add agents using #addAgent() and make an initial movement request using #requestMoveTarget().
A common process for managing the crowd is as follows:
-# Call #update() to allow the crowd to manage its agents.
-# Retrieve agent information using #getActiveAgents().
-# Make movement requests using #requestMoveTarget() when movement goal changes.
-# Repeat every frame.
Some agent configuration settings can be updated using #updateAgentParameters(). But the crowd owns the
agent position. So it is not possible to update an active agent's position. If agent position
must be fed back into the crowd, the agent must be removed and re-added.
Notes:
- Path related information is available for newly added agents only after an #update() has been
performed.
- Agent objects are kept in a pool and re-used. So it is important when using agent objects to check the value of
#dtCrowdAgent::active to determine if the agent is actually in use or not.
- This class is meant to provide 'local' movement. There is a limit of 256 polygons in the path corridor.
So it is not meant to provide automatic pathfinding services over long distances.
@see dtAllocCrowd(), dtFreeCrowd(), init(), dtCrowdAgent
*)
constructor TdtCrowd.Create;
var i: Integer;
begin
m_maxAgents := 0;
m_agents := nil;
m_activeAgents := nil;
m_agentAnims := nil;
m_obstacleQuery := nil;
m_grid := nil;
m_pathResult := nil;
m_maxPathResult := 0;
m_maxAgentRadius := 0;
m_velocitySampleCount := 0;
m_navquery := nil;
m_pathq := TdtPathQueue.Create; // Delphi: Assume C++ invokes constructor
for i := 0 to DT_CROWD_MAX_QUERY_FILTER_TYPE-1 do
m_filters[i] := TdtQueryFilter.Create;
end;
destructor TdtCrowd.Destroy;
var i: Integer;
begin
purge();
m_pathq.Free; // Delphi: Assume C++ invokes destructor
for i := 0 to DT_CROWD_MAX_QUERY_FILTER_TYPE-1 do
m_filters[i].Free;
inherited;
end;
procedure TdtCrowd.purge();
var i: Integer;
begin
// Delphi: Release objects we have created in Init (see m_agents comments there)
for i := 0 to m_maxAgents - 1 do
begin
FreeAndNil(m_agents[i].corridor);
FreeAndNil(m_agents[i].boundary);
end;
FreeMem(m_agents);
m_agents := nil;
m_maxAgents := 0;
FreeMem(m_activeAgents);
m_activeAgents := nil;
FreeMem(m_agentAnims);
m_agentAnims := nil;
FreeMem(m_pathResult);
m_pathResult := nil;
dtFreeProximityGrid(m_grid);
m_grid := nil;
dtFreeObstacleAvoidanceQuery(m_obstacleQuery);
m_obstacleQuery := nil;
dtFreeNavMeshQuery(m_navquery);
m_navquery := nil;
end;
/// @par
///
/// May be called more than once to purge and re-initialize the crowd.
function TdtCrowd.init(const maxAgents: Integer; const maxAgentRadius: Single; nav: TdtNavMesh): Boolean;
var i: Integer; params: PdtObstacleAvoidanceParams;
begin
purge();
m_maxAgents := maxAgents;
m_maxAgentRadius := maxAgentRadius;
dtVset(@m_ext[0], m_maxAgentRadius*2.0,m_maxAgentRadius*1.5,m_maxAgentRadius*2.0);
m_grid := dtAllocProximityGrid();
if (m_grid = nil) then
Exit(false);
if (not m_grid.init(m_maxAgents*4, maxAgentRadius*3)) then
Exit(false);
m_obstacleQuery := dtAllocObstacleAvoidanceQuery();
if (m_obstacleQuery = nil) then
Exit(false);
if (not m_obstacleQuery.init(6, 8)) then
Exit(false);
// Init obstacle query params.
FillChar(m_obstacleQueryParams[0], sizeof(m_obstacleQueryParams), 0);
for i := 0 to DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS - 1 do
begin
params := @m_obstacleQueryParams[i];
params.velBias := 0.4;
params.weightDesVel := 2.0;
params.weightCurVel := 0.75;
params.weightSide := 0.75;
params.weightToi := 2.5;
params.horizTime := 2.5;
params.gridSize := 33;
params.adaptiveDivs := 7;
params.adaptiveRings := 2;
params.adaptiveDepth := 5;
end;
// Allocate temp buffer for merging paths.
m_maxPathResult := 256;
GetMem(m_pathResult, sizeof(TdtPolyRef)*m_maxPathResult);
if (not m_pathq.init(m_maxPathResult, MAX_PATHQUEUE_NODES, nav)) then
Exit(false);
GetMem(m_agents, sizeof(TdtCrowdAgent)*m_maxAgents);
GetMem(m_activeAgents, sizeof(PdtCrowdAgent)*m_maxAgents);
GetMem(m_agentAnims, sizeof(TdtCrowdAgentAnimation)*m_maxAgents);
for i := 0 to m_maxAgents - 1 do
begin
// Delphi: Objects are auto-created in C++ struct, so I've been told and so does the code below expects
m_agents[i].corridor := TdtPathCorridor.Create;
m_agents[i].boundary := TdtLocalBoundary.Create;
m_agents[i].active := false;
if (not m_agents[i].corridor.init(m_maxPathResult)) then
Exit(false);
end;
for i := 0 to m_maxAgents - 1 do
begin
m_agentAnims[i].active := false;
end;
// The navquery is mostly used for local searches, no need for large node pool.
m_navquery := dtAllocNavMeshQuery();
if (dtStatusFailed(m_navquery.init(nav, MAX_COMMON_NODES))) then
Exit(false);
Result := true;
end;
procedure TdtCrowd.setObstacleAvoidanceParams(const idx: Integer; const params: PdtObstacleAvoidanceParams);
begin
if (idx >= 0) and (idx < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS)then
Move(params^, m_obstacleQueryParams[idx], sizeof(TdtObstacleAvoidanceParams));
end;
function TdtCrowd.getObstacleAvoidanceParams(const idx: Integer): PdtObstacleAvoidanceParams;
begin
if (idx >= 0) and (idx < DT_CROWD_MAX_OBSTAVOIDANCE_PARAMS) then
Exit(@m_obstacleQueryParams[idx]);
Result := nil;
end;
function TdtCrowd.getAgentCount(): Integer;
begin
Result := m_maxAgents;
end;
/// @par
///
/// Agents in the pool may not be in use. Check #dtCrowdAgent.active before using the returned object.
function TdtCrowd.getAgent(const idx: Integer): PdtCrowdAgent;
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit(nil);
Result := @m_agents[idx];
end;
///
/// Agents in the pool may not be in use. Check #dtCrowdAgent.active before using the returned object.
function TdtCrowd.getEditableAgent(const idx: Integer): PdtCrowdAgent;
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit(nil);
Result := @m_agents[idx];
end;
procedure TdtCrowd.updateAgentParameters(const idx: Integer; const params: PdtCrowdAgentParams);
begin
if (idx < 0) or (idx >= m_maxAgents) then
Exit;
Move(params^, m_agents[idx].params, sizeof(TdtCrowdAgentParams));
end;
/// @par
///
/// The agent's position will be constrained to the surface of the navigation mesh.
function TdtCrowd.addAgent(const pos: PSingle; const params: PdtCrowdAgentParams): Integer;
var idx, i: Integer; ag: PdtCrowdAgent; nearest: array [0..2] of Single; ref: TdtPolyRef; status: TdtStatus;
begin
// Find empty slot.
idx := -1;
for i := 0 to m_maxAgents - 1 do
begin
if (not m_agents[i].active) then
begin
idx := i;
break;
end;
end;
if (idx = -1) then
Exit(-1);
ag := @m_agents[idx];
updateAgentParameters(idx, params);
// Find nearest position on navmesh and place the agent there.
ref := 0;
dtVcopy(@nearest[0], pos);
status := m_navquery.findNearestPoly(pos, @m_ext[0], m_filters[ag.params.queryFilterType], @ref, @nearest[0]);
if (dtStatusFailed(status)) then
begin
dtVcopy(@nearest[0], pos);
ref := 0;
end;
ag.corridor.reset(ref, @nearest[0]);
ag.boundary.reset();
ag.partial := false;
ag.topologyOptTime := 0;
ag.targetReplanTime := 0;
ag.nneis := 0;
dtVset(@ag.dvel[0], 0,0,0);
dtVset(@ag.nvel[0], 0,0,0);
dtVset(@ag.vel[0], 0,0,0);
dtVcopy(@ag.npos[0], @nearest[0]);
ag.desiredSpeed := 0;
if (ref <> 0) then
ag.state := DT_CROWDAGENT_STATE_WALKING
else
ag.state := DT_CROWDAGENT_STATE_INVALID;
ag.targetState := DT_CROWDAGENT_TARGET_NONE;
ag.active := true;
Result := idx;
end;
/// @par
///
/// The agent is deactivated and will no longer be processed. Its #dtCrowdAgent object
/// is not removed from the pool. It is marked as inactive so that it is available for reuse.
procedure TdtCrowd.removeAgent(const idx: Integer);
begin
if (idx >= 0) and (idx < m_maxAgents) then
begin