-
Notifications
You must be signed in to change notification settings - Fork 2
/
physics.pas
3148 lines (2890 loc) · 133 KB
/
physics.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
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit physics;
interface
uses
storable, lists, grammarian, thingdim, messages, textstream, properties;
type
TAtom = class;
TAtomClass = class of TAtom;
TInternalAtomList = specialize TStorableList<TAtom>;
TThing = class;
TInternalThingList = specialize TStorableList<TThing>;
TThingClass = class of TThing;
TLocation = class;
TLocationList = specialize TStorableList<TLocation>; // @RegisterStorableClass
TAvatar = class;
type
PAtomList = ^TAtomList;
TAtomList = class(TInternalAtomList) // @RegisterStorableClass
function GetIndefiniteString(Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
function GetDefiniteString(Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
function GetLongDefiniteString(Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
function IsPlural(Perspective: TAvatar): Boolean;
function GetPossessiveAdjective(Perspective: TAvatar): UTF8String;
end;
TThingList = class(TInternalThingList) // @RegisterStorableClass
function GetIndefiniteString(Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
function GetDefiniteString(Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
function GetLongDefiniteString(Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
function IsPlural(Perspective: TAvatar): Boolean;
function GetPossessiveAdjective(Perspective: TAvatar): UTF8String;
end;
function GetIndefiniteString(const List: array of TAtom; StartIndex, EndIndex: Cardinal; Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
function GetDefiniteString(const List: array of TAtom; StartIndex, EndIndex: Cardinal; Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
function GetLongDefiniteString(const List: array of TAtom; StartIndex, EndIndex: Cardinal; Perspective: TAvatar; const Conjunction: UTF8String): UTF8String;
type
TReachablePosition = (rpReachable, rpNotReachable);
TReachablePositionSet = set of TReachablePosition;
TNavigationAbility = (naWalk, naJump, naFly, naDebugTeleport);
TNavigationAbilities = set of TNavigationAbility;
TSubjectiveInformation = record
Directions: TCardinalDirectionSet;
Reachable: TReachablePositionSet;
RequiredAbilitiesToNavigate: TNavigationAbilities;
procedure Reset();
end;
TTravelType = (ttNone, ttByPosition, ttByDirection);
TNavigationInstruction = record
RequiredAbilities: TNavigationAbilities;
case TravelType: TTravelType of
ttNone: ();
ttByPosition: (PositionTarget: TAtom; Position: TThingPosition);
ttByDirection: (DirectionTarget: TAtom; Direction: TCardinalDirection);
end;
TTransportationInstruction = record
case TravelType: TTravelType of
ttNone: ();
ttByPosition: (TargetThing: TThing; Position: TThingPosition; RequiredAbilities: TNavigationAbilities);
ttByDirection: (Direction: TCardinalDirection);
end;
type
TThingFeature = (tfDiggable, tfCanDig, tfExaminingReads, tfOpenable, tfClosable,
tfCanHaveThingsPushedOn, { e.g. it has a ramp, or a surface flush with its container -- e.g. holes can have things pushed onto them }
tfCanHaveThingsPushedIn); { e.g. it has its entrance flush with its base, or has a lip flush with its container -- holes, bags; but not boxes }
TThingFeatures = set of TThingFeature; // as returned by GetFeatures()
TFindMatchingThingsOption = (fomIncludePerspectiveChildren, // whether to include the player's children; e.g. not used by "take all"
fomIncludeNonImplicits, // whether to include things normally excluded because IsImplicitlyReferenceable returns true; e.g. used by "debug things" to make the avatars be included in the list; not used by "take all" so that avatars aren't picked up
fomFromOutside); // if set, the search is from the perspective of something outside the atom (e.g. it's parent, or something on it); otherwise, it's from the perspective of something inside (tpContained in) the atom
TFindMatchingThingsOptions = set of TFindMatchingThingsOption;
TFindThingOption = (foFindAnywhere, // treat loAutoDescribe as loThreshold - used when locating a perspective so that doorways can find us even when we can't implicitly see them
foFromOutside,
foWithPreciseDirections); // indicate we want to ignore loConsiderDirectionUnimportantWhenFindingChildren, we really want to know the direction
TFindThingOptions = set of TFindThingOption;
TLeadingPhraseOption = (lpMandatory, lpNamesTarget);
TLeadingPhraseOptions = set of TLeadingPhraseOption;
const
tfEverything = []; { an empty TThingFeatures set, because thing features _limit_ what can be returned }
type
TGetDescriptionOnOptions = set of (optDeepOn, optPrecise);
TGetDescriptionChildrenOptions = set of (optDeepChildren, optFar, optThorough, optOmitPerspective); { deep = bag and inside bag; far = door and inside door }
TGetPresenceStatementMode = (psThereIsAThingHere { look },
psThereIsAThingThere { look north },
psOnThatThingIsAThing { nested look },
psTheThingIsOnThatThing { find },
psOnThatSpecialThing { find (something far away) -- only if parent is TThing, not TLocation });
type
TStreamedChildren = record
private
FChildren: array of TThing;
FPositions: array of TThingPosition;
public
procedure AddChild(Child: TThing; Position: TThingPosition);
procedure Apply(Parent: TAtom);
end;
TLandmarkOption = (loAutoDescribe, // include landmark in descriptions of the room (works for locations; works for things if their position is in tpAutoDescribeDirectional) [1]
loPermissibleNavigationTarget, // whether you can travel that way; direction navigation uses the first landmark with this flag
loThreshold, // whether FindThing and FindMatchingThings should traverse (ExplicitlyReferenced logic doesn't use this since it looks everywhere) [1]
loVisibleFromFarAway, // whether to traverse multiple locations; for e.g. mountains
loNotVisibleFromBehind, // for e.g. surfaces so that they're not visible from below
loConsiderDirectionUnimportantWhenFindingChildren); // so that "find hole" doesn't say "below" and "find stairs" doesn't say "above" (ignored if foWithPreciseDirections)
// [1]: Don't include a landmark in more than one direction at a time if they are marked with either of these
TLandmarkOptions = set of TLandmarkOption;
TStreamedLandmarks = record
private
FDirections: array of TCardinalDirection;
FLandmarks: array of TAtom;
FOptions: array of TLandmarkOptions;
public
procedure AddLandmark(Direction: TCardinalDirection; Atom: TAtom; Options: TLandmarkOptions);
procedure Apply(Parent: TLocation);
end;
type
TPlacementStyle = (psRoughly, psCarefully);
TThingReporter = procedure (Thing: TThing; Count: Cardinal; GrammaticalNumber: TGrammaticalNumber) of object;
TThingCallback = procedure (Thing: TThing) is nested;
TAtom = class(TStorable)
{$IFDEF DEBUG}
private
FIntegritySelf: PtrUInt; // set to nil on allocation, PtrUInt(Self) by constructors, High(PtrUInt) by destructor
{$ENDIF}
protected
FChildren: TThingList;
class function CreateFromProperties(Properties: TTextStreamProperties): TAtom; virtual; abstract;
class function HandleChildProperties(Properties: TTextStreamProperties; var Values: TStreamedChildren): Boolean;
procedure Removed(Thing: TThing); virtual;
function IsChildTraversable(Child: TThing; Perspective: TAvatar; FromOutside: Boolean): Boolean; virtual;
{$IFOPT C+} procedure AssertChildPositionOk(Thing: TThing; Position: TThingPosition); virtual; {$ENDIF}
public
constructor Create();
destructor Destroy(); override;
constructor Read(Stream: TReadStream); override;
procedure Write(Stream: TWriteStream); override;
class procedure DescribeProperties(Describer: TPropertyDescriber); virtual;
// Moving things around
function GetChildren(const PositionFilter: TThingPositionFilter): TThingList; // these are the children that can be shaken loose
procedure EnumerateChildren(List: TThingList; const PositionFilter: TThingPositionFilter); virtual;
procedure Add(Thing: TThing; Position: TThingPosition); // use Put() if it's during gameplay
procedure Add(Thing: TThingList.TEnumerator; Position: TThingPosition);
procedure Remove(Thing: TThing);
procedure Remove(Thing: TThingList.TEnumerator);
function CanPut(Thing: TThing; ThingPosition: TThingPosition; Care: TPlacementStyle; Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // whether Thing can be put on/in this Atom (only supports tpOn, tpIn) without things falling
procedure Put(Thing: TThing; Position: TThingPosition; Care: TPlacementStyle; Perspective: TAvatar); virtual;
function GetMassManifest(): TThingMassManifest; virtual; { self and children }
function GetOutsideSizeManifest(): TThingSizeManifest; virtual; { external size of the object (e.g. to decide if it fits inside another): self and children that are tpOutside; add tpContained children if container is flexible }
function GetInsideSizeManifest(): TThingSizeManifest; virtual; { only children that are tpContained }
function GetSurfaceSizeManifest(): TThingSizeManifest; virtual; { children that are tpSurface (e.g. to decide if something else can be added to the object's surface or if the surface is full already) }
function GetRepresentative(): TAtom; virtual; { the TAtom that is responsible for high-level dealings for this one (opposite of GetSurface, maybe a TLocation); this must not be a descendant, since otherwise we'll loop forever in GetContext }
function GetSurface(): TThing; virtual; { the TThing that is responsible for the minutiae of where things dropped on this one actually go (opposite of GetRepresentative); can be null, e.g. for a wall or the air }
function CanSurfaceHold(const Manifest: TThingSizeManifest; const ManifestCount: Integer): Boolean; virtual; abstract;
function GetInside(var PositionOverride: TThingPosition): TThing; virtual; { returns nil if there's no inside to speak of }
function CanInsideHold(const Manifest: TThingSizeManifest; const ManifestCount: Integer): Boolean; virtual;
function GetDefaultDestination(var Position: TThingPosition): TAtom; virtual; // resolve object to actual destination for moving things; Position must be tpOn, tpIn, or tpAt when it's ambiguous (e.g. "move bar to foo")
procedure HandlePassedThrough(Traveller: TThing; AFrom, ATo: TAtom; AToPosition: TThingPosition; Perspective: TAvatar); virtual; { use this for magic doors, falling down tunnels, etc }
procedure HandleAdd(Thing: TThing; Perspective: TAvatar); virtual; { use this to fumble things or to cause things to fall off other things }
function GetNavigationInstructions(Direction: TCardinalDirection; Child: TThing; Perspective: TAvatar; var Message: TMessage): TNavigationInstruction; virtual; abstract; // Perspective is the traveller; Child is the ancestor of Perspective (originally Perspective itself) that's a child of Self that we're dealing with now
function GetEntrance(Traveller: TThing; Direction: TCardinalDirection; Perspective: TAvatar; var PositionOverride: TThingPosition; var DisambiguationOpening: TThing; var Message: TMessage; NotificationList: TAtomList): TAtom; virtual; abstract;
// Finding things
procedure GetNearbyThingsByClass(List: TThingList; FromOutside: Boolean; Filter: TThingClass); virtual;
function GetSurroundingsRoot(out FromOutside: Boolean): TAtom; virtual;
procedure FindMatchingThings(Perspective: TAvatar; Options: TFindMatchingThingsOptions; PositionFilter: TThingPositionFilter; PropertyFilter: TThingFeatures; List: TThingList); virtual;
procedure ProxiedFindMatchingThings(Perspective: TAvatar; Options: TFindMatchingThingsOptions; PositionFilter: TThingPositionFilter; PropertyFilter: TThingFeatures; List: TThingList); virtual; // see note [proxy]
function FindThing(Thing: TThing; Perspective: TAvatar; Options: TFindThingOptions; out SubjectiveInformation: TSubjectiveInformation): Boolean; virtual; // used by CanReach() and Locate()
function FindThingTraverser(Thing: TThing; Perspective: TAvatar; Options: TFindThingOptions): Boolean; virtual;
function ProxiedFindThingTraverser(Thing: TThing; Perspective: TAvatar; Options: TFindThingOptions): Boolean; virtual; // see note [proxy]
procedure EnumerateExplicitlyReferencedThings(Tokens: TTokens; Start: Cardinal; Perspective: TAvatar; FromOutside, FromFarAway: Boolean; Directions: TCardinalDirectionSet; Reporter: TThingReporter); virtual;
procedure ProxiedEnumerateExplicitlyReferencedThings(Tokens: TTokens; Start: Cardinal; Perspective: TAvatar; FromOutside, FromFarAway: Boolean; Directions: TCardinalDirectionSet; Reporter: TThingReporter); virtual; // see note [proxy]
// Atom identity
function IsPlural(Perspective: TAvatar): Boolean; virtual; abstract;
function GetName(Perspective: TAvatar): UTF8String; virtual; abstract;
function GetLongName(Perspective: TAvatar): UTF8String; virtual; { if you reply to other terms, put as many as possible here; this is shown to disambiguate }
function GetIndefiniteName(Perspective: TAvatar): UTF8String; virtual; abstract;
function GetDefiniteName(Perspective: TAvatar): UTF8String; virtual;
function GetLongDefiniteName(Perspective: TAvatar): UTF8String; virtual;
function GetSubjectPronoun(Perspective: TAvatar): UTF8String; virtual; // I
function GetObjectPronoun(Perspective: TAvatar): UTF8String; virtual; // me
function GetReflexivePronoun(Perspective: TAvatar): UTF8String; virtual; // myself
function GetPossessivePronoun(Perspective: TAvatar): UTF8String; virtual; // mine
function GetPossessiveAdjective(Perspective: TAvatar): UTF8String; virtual; // my
function GetTitle(Perspective: TAvatar): UTF8String; virtual;
function GetContext(Perspective: TAvatar): UTF8String; virtual;
function GetContextFragment(Perspective: TAvatar; PertinentPosition: TThingPosition; Context: TAtom = nil): UTF8String; virtual; // see note [context]
function GetPresenceStatementFragment(Perspective: TAvatar; PertinentPosition: TThingPosition): UTF8String; virtual; // used by children to implement psTheThingIsOnThatThing in GetPresenceStatement
// Atom descriptions
// comment gives the default implementation, if it's not the empty string or abstract
function GetLook(Perspective: TAvatar): UTF8String; virtual; // title + basic + horizon + on + children
function GetLookTowardsDirection(Perspective: TAvatar; Direction: TCardinalDirection): UTF8String; virtual; abstract;
function GetBasicDescription(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Directions: TCardinalDirectionSet = cdAllDirections; Context: TAtom = nil): UTF8String; virtual; // self + state + here // see note [context]
function GetHorizonDescription(Perspective: TAvatar): UTF8String; virtual; // component of GetLook, typically defers to parent's GetDescriptionRemoteHorizon
function GetDescriptionSelf(Perspective: TAvatar): UTF8String; virtual; abstract;
function GetDescriptionState(Perspective: TAvatar): UTF8String; virtual; { e.g. 'The bottle is open.' }
function GetDescriptionHere(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Directions: TCardinalDirectionSet = cdAllDirections; Context: TAtom = nil): UTF8String; virtual; abstract; // see note [context]
function GetDescriptionOn(Perspective: TAvatar; Options: TGetDescriptionOnOptions; Prefix: UTF8String = ''): UTF8String; virtual; // presence + state for each child, plus on for each child if optDeepOn
function GetDescriptionChildren(Perspective: TAvatar; Options: TGetDescriptionChildrenOptions; Prefix: UTF8String = ''): UTF8String; virtual;
function GetDescriptionRemoteHorizon(Perspective: TAvatar; Context: TThing; Depth: Cardinal): UTF8String; virtual; // what to display in a Depth-deep descendant's GetLook for the horizon component (0=child) // see note [context]
function GetDescriptionRemoteBrief(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Direction: TCardinalDirection): UTF8String; virtual; abstract; // used by locations to include their loAutoDescribe landmarks in their Here description
function GetDescriptionRemoteDetailed(Perspective: TAvatar; Direction: TCardinalDirection; LeadingPhrase: UTF8String; Options: TLeadingPhraseOptions): UTF8String; virtual; abstract; // used for things like "look north"
{$IFDEF DEBUG} function Debug(Perspective: TAvatar): UTF8String; virtual; {$ENDIF}
procedure WalkChildren(Callback: TThingCallback); virtual;
end;
TThing = class(TAtom)
protected
FParent: TAtom;
FPosition: TThingPosition;
function IsChildTraversable(Child: TThing; Perspective: TAvatar; FromOutside: Boolean): Boolean; override;
function IsImplicitlyReferenceable(Perspective: TAvatar; PropertyFilter: TThingFeatures): Boolean; virtual;
function IsExplicitlyReferenceable(Perspective: TAvatar): Boolean; virtual;
public
constructor Read(Stream: TReadStream); override;
procedure Write(Stream: TWriteStream); override;
class function HandleUniqueThingProperty(Properties: TTextStreamProperties; PossibleName: UTF8String; var Value: TThing; Superclass: TThingClass): Boolean;
// Moving things around
procedure GetNearbyThingsByClass(List: TThingList; FromOutside: Boolean; Filter: TThingClass); override;
function GetSurroundingsRoot(out FromOutside: Boolean): TAtom; override;
function CanReach(Subject: TAtom; Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // whether we can manipulate Subject
function HasAbilityToTravelTo(Destination: TAtom; RequiredAbilities: TNavigationAbilities; Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // [travel]
function CanPut(Thing: TThing; ThingPosition: TThingPosition; Care: TPlacementStyle; Perspective: TAvatar; var Message: TMessage): Boolean; override;
function CanMove(Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // Perspective can be nil for internal checks
function CanTake(Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // Perspective can be nil for internal checks
function CanShake(Perspective: TAvatar; var Message: TMessage): Boolean; virtual;
function GetIntrinsicMass(): TThingMass; virtual; abstract;
function GetIntrinsicSize(): TThingSize; virtual; abstract;
function GetMassManifest(): TThingMassManifest; override;
function GetOutsideSizeManifest(): TThingSizeManifest; override;
function GetSurface(): TThing; override;
function CanSurfaceHold(const Manifest: TThingSizeManifest; const ManifestCount: Integer): Boolean; override;
procedure HandleAdd(Thing: TThing; Perspective: TAvatar); override;
function GetDefaultDestination(var Position: TThingPosition): TAtom; override;
function GetEntrance(Traveller: TThing; Direction: TCardinalDirection; Perspective: TAvatar; var PositionOverride: TThingPosition; var DisambiguationOpening: TThing; var Message: TMessage; NotificationList: TAtomList): TAtom; override;
function GetTransportationDestination(Perspective: TAvatar): TTransportationInstruction; virtual; // for "take stairs" or "take train" or "travel by boat", where do we end up? nil means this TThing is not a form of transportation.
// Identification
function GetIndefiniteName(Perspective: TAvatar): UTF8String; override;
function GetDefiniteName(Perspective: TAvatar): UTF8String; override;
function GetLongDefiniteName(Perspective: TAvatar): UTF8String; override;
function IsPlural(Perspective: TAvatar): Boolean; override;
function GetTitle(Perspective: TAvatar): UTF8String; override;
// Descriptions
function GetHorizonDescription(Perspective: TAvatar): UTF8String; override; // defers to parent's GetDescriptionRemoteHorizon
function GetDescriptionRemoteHorizon(Perspective: TAvatar; Context: TThing; Depth: Cardinal): UTF8String; override; // what to display in a Depth-deep descendant's GetLook (0=child) // see note [context]
function GetExamine(Perspective: TAvatar): UTF8String; virtual; // basic + writing + on + children
function GetLookUnder(Perspective: TAvatar): UTF8String; virtual; // by default, just gives the name of the parent
function GetLookTowardsDirection(Perspective: TAvatar; Direction: TCardinalDirection): UTF8String; override; // various
function GetLookIn(Perspective: TAvatar): UTF8String; virtual; // various
function GetLookAt(Perspective: TAvatar): UTF8String; virtual; // basic + on + children
function GetDescriptionEmpty(Perspective: TAvatar): UTF8String; virtual; // '...empty' { only called for optThorough searches }
function GetDescriptionNoInside(Perspective: TAvatar): UTF8String; virtual; // 'can't get in' if no inside, else ...Closed() { used both from inside and outside }
function GetDescriptionClosed(Perspective: TAvatar): UTF8String; virtual; // '...closed' { used both from inside and outside }
function GetInventory(Perspective: TAvatar): UTF8String; virtual; // carried
function GetDescriptionHere(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Directions: TCardinalDirectionSet = cdAllDirections; Context: TAtom = nil): UTF8String; override; // presence statement and state for each child // see note [context]
function GetDescriptionDirectional(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Direction: TCardinalDirection): UTF8String; virtual; // name + state; used by GetDescriptionRemoteBrief to do the self-description.
function GetDescriptionChildren(Perspective: TAvatar; Options: TGetDescriptionChildrenOptions; Prefix: UTF8String = ''): UTF8String; override; // in + carried
function GetDescriptionRemoteBrief(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Direction: TCardinalDirection): UTF8String; override; // various; includes GetDescriptionDirectional and children.
function GetDescriptionRemoteDetailed(Perspective: TAvatar; Direction: TCardinalDirection; LeadingPhrase: UTF8String; Options: TLeadingPhraseOptions): UTF8String; override; // basic
function GetDescriptionIn(Perspective: TAvatar; Options: TGetDescriptionChildrenOptions; Prefix: UTF8String = ''): UTF8String; virtual; // in title, plus name and in of each child
function GetDescriptionInTitle(Perspective: TAvatar; Options: TGetDescriptionChildrenOptions): UTF8String; virtual; // '...contains:'
function GetDescriptionCarried(Perspective: TAvatar; DeepCarried: Boolean; Prefix: UTF8String = ''): UTF8String; virtual; // carried title, plus name, on, children for each child
function GetDescriptionCarriedTitle(Perspective: TAvatar; DeepCarried: Boolean): UTF8String; virtual; // '...is carrying:'
function GetPresenceStatement(Perspective: TAvatar; Mode: TGetPresenceStatementMode): UTF8String; virtual; // various
function GetDescriptionWriting(Perspective: TAvatar): UTF8String; virtual; // 'there is no...'
// Misc (these should be organised at some point)
function GetNavigationInstructions(Direction: TCardinalDirection; Child: TThing; Perspective: TAvatar; var Message: TMessage): TNavigationInstruction; override;
procedure FindMatchingThings(Perspective: TAvatar; Options: TFindMatchingThingsOptions; PositionFilter: TThingPositionFilter; PropertyFilter: TThingFeatures; List: TThingList); override;
function FindThingTraverser(Thing: TThing; Perspective: TAvatar; Options: TFindThingOptions): Boolean; override;
function IsExplicitlyReferencedThing(Tokens: TTokens; Start: Cardinal; Perspective: TAvatar; out Count: Cardinal; out GrammaticalNumber: TGrammaticalNumber): Boolean; virtual; abstract; // compares Tokens to FName, essentially
procedure EnumerateExplicitlyReferencedThings(Tokens: TTokens; Start: Cardinal; Perspective: TAvatar; FromOutside, FromFarAway: Boolean; Directions: TCardinalDirectionSet; Reporter: TThingReporter); override;
procedure Moved(OldParent: TAtom; Care: TPlacementStyle; Perspective: TAvatar); virtual;
procedure Shake(Perspective: TAvatar); virtual;
procedure Press(Perspective: TAvatar); virtual;
function GetFeatures(): TThingFeatures; virtual;
function CanDig(Target: TThing; Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // can this be used as a digging tool to dig the given target?
function Dig(Spade: TThing; Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // can this be dug by the given spade? if so, do it
procedure Dug(Target: TThing; Perspective: TAvatar; var Message: TMessage); virtual; // this was used as a digging tool to dig the given target
function IsOpen(): Boolean; virtual;
function CanSeeIn(): Boolean; virtual; // must return true if IsOpen() is true
function CanSeeOut(): Boolean; virtual; // must return true if IsOpen() is true
function Open(Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // can this be opened? if so, do it
function Close(Perspective: TAvatar; var Message: TMessage): Boolean; virtual; // can this be closed? if so, do it
// XXX eventually we should add opening and closing tools, just like we have digging tools
{$IFDEF DEBUG} function Debug(Perspective: TAvatar): UTF8String; override; {$ENDIF}
property Parent: TAtom read FParent;
property Position: TThingPosition read FPosition write FPosition;
end;
{ Thing that can move of its own volition }
TAvatar = class(TThing)
protected
function IsImplicitlyReferenceable(Perspective: TAvatar; PropertyFilter: TThingFeatures): Boolean; override;
class function CreateFromProperties(Properties: TTextStreamProperties): TAtom; override;
public
procedure DoLook(); virtual; abstract;
procedure AvatarMessage(Message: TMessage); virtual; abstract;
procedure AnnounceAppearance(); virtual; abstract;
procedure AnnounceDisappearance(); virtual; abstract;
procedure AnnounceDeparture(Destination: TAtom; Direction: TCardinalDirection); virtual; abstract;
procedure AnnounceDeparture(Destination: TAtom); virtual; abstract;
procedure AnnounceArrival(Source: TAtom); virtual; abstract;
procedure AnnounceArrival(Source: TAtom; Direction: TCardinalDirection); virtual; abstract;
procedure AutoDisambiguated(Message: UTF8String); virtual; abstract;
function HasConnectedPlayer(): Boolean; virtual; abstract;
function IsReadyForRemoval(): Boolean; virtual; abstract;
procedure RemoveFromWorld(); virtual;
function Locate(Thing: TThing; Options: TFindThingOptions = [foFindAnywhere]): TSubjectiveInformation; // foFromOutside will be added automatically if necessary
end;
{$IFDEF DEBUG} // used by AssertDirectionHasDestination()
TDummyAvatar = class(TAvatar) // @RegisterStorableClass IFDEF DEBUG
public
function IsPlural(Perspective: TAvatar): Boolean; override;
function GetName(Perspective: TAvatar): UTF8String; override;
function GetDescriptionSelf(Perspective: TAvatar): UTF8String; override;
function CanSurfaceHold(const Manifest: TThingSizeManifest; const ManifestCount: Integer): Boolean; override;
function GetIntrinsicMass(): TThingMass; override;
function GetIntrinsicSize(): TThingSize; override;
function IsExplicitlyReferencedThing(Tokens: TTokens; Start: Cardinal; Perspective: TAvatar; out Count: Cardinal; out GrammaticalNumber: TGrammaticalNumber): Boolean; override;
procedure DoLook(); override;
procedure AvatarMessage(Message: TMessage); override;
procedure AnnounceAppearance(); override;
procedure AnnounceDisappearance(); override;
procedure AnnounceDeparture(Destination: TAtom; Direction: TCardinalDirection); override;
procedure AnnounceDeparture(Destination: TAtom); override;
procedure AnnounceArrival(Source: TAtom); override;
procedure AnnounceArrival(Source: TAtom; Direction: TCardinalDirection); override;
procedure AutoDisambiguated(Message: UTF8String); override;
function HasConnectedPlayer(): Boolean; override;
function IsReadyForRemoval(): Boolean; override;
end;
{$ENDIF}
TLocation = class(TAtom)
protected
type
TDirectionalLandmark = record
Direction: TCardinalDirection; // XXX we should make this a set
Options: TLandmarkOptions;
Atom: TAtom; // may or may not be a TThing in this room; often a remote TLocation or TThing
end;
var
FLandmarks: array of TDirectionalLandmark;
class function HandleLandmarkProperties(Properties: TTextStreamProperties; var Values: TStreamedLandmarks): Boolean;
function CanFindInDirection(Direction: TCardinalDirection; Atom: TAtom): Boolean;
function FindThingDirectionalTraverser(Thing: TThing; Perspective: TAvatar; Distance: Cardinal; Direction: TCardinalDirection; Options: TFindThingOptions; var SubjectiveInformation: TSubjectiveInformation): Boolean; virtual;
{$IFDEF DEBUG} procedure AssertDirectionHasDestination(Direction: TCardinalDirection; Atom: TAtom); {$ENDIF}
public
constructor Create();
destructor Destroy(); override;
constructor Read(Stream: TReadStream); override;
procedure Write(Stream: TWriteStream); override;
class function HandleUniqueLocationProperty(Properties: TTextStreamProperties; PossibleName: UTF8String; var Value: TLocation): Boolean;
function HasLandmark(Direction: TCardinalDirection): Boolean;
procedure AddLandmark(Direction: TCardinalDirection; Atom: TAtom; Options: TLandmarkOptions);
procedure AddSurroundings(Atom: TAtom; const Directions: TCardinalDirectionSet = cdCompassDirection);
function GetAtomForDirectionalNavigation(Direction: TCardinalDirection): TAtom; virtual; // returns first landmark in given direction that is loPermissibleNavigationTarget
function IsPlural(Perspective: TAvatar): Boolean; override;
function GetLookTowardsDirection(Perspective: TAvatar; Direction: TCardinalDirection): UTF8String; override;
function GetLookTowardsDirectionDefault(Perspective: TAvatar; Direction: TCardinalDirection): UTF8String; virtual;
function GetDescriptionSelf(Perspective: TAvatar): UTF8String; override;
function GetDescriptionLandmarks(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Directions: TCardinalDirectionSet = cdAllDirections; Context: TAtom = nil): UTF8String; virtual; // this describes the landmarks; used by GetDescriptionHere and GetDescriptionRemoteHorizon; see also note [context]
function GetDescriptionHere(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Directions: TCardinalDirectionSet = cdAllDirections; Context: TAtom = nil): UTF8String; override; // see note [context]
function GetDescriptionRemoteHorizon(Perspective: TAvatar; Context: TThing; Depth: Cardinal): UTF8String; override; // includes our major landmarks in descendant GetLooks // see note [context]
function GetDescriptionRemoteBrief(Perspective: TAvatar; Mode: TGetPresenceStatementMode; Direction: TCardinalDirection): UTF8String; override;
function GetDescriptionRemoteDetailed(Perspective: TAvatar; Direction: TCardinalDirection; LeadingPhrase: UTF8String; Options: TLeadingPhraseOptions): UTF8String; override;
function GetNavigationInstructions(Direction: TCardinalDirection; Child: TThing; Perspective: TAvatar; var Message: TMessage): TNavigationInstruction; override;
procedure FailNavigation(Direction: TCardinalDirection; Perspective: TAvatar; out Message: TMessage); { also called when trying to dig in and push something in this direction }
function GetEntrance(Traveller: TThing; Direction: TCardinalDirection; Perspective: TAvatar; var PositionOverride: TThingPosition; var DisambiguationOpening: TThing; var Message: TMessage; NotificationList: TAtomList): TAtom; override;
function CanSurfaceHold(const Manifest: TThingSizeManifest; const ManifestCount: Integer): Boolean; override;
procedure EnumerateExplicitlyReferencedThings(Tokens: TTokens; Start: Cardinal; Perspective: TAvatar; FromOutside, FromFarAway: Boolean; Directions: TCardinalDirectionSet; Reporter: TThingReporter); override;
procedure FindMatchingThings(Perspective: TAvatar; Options: TFindMatchingThingsOptions; PositionFilter: TThingPositionFilter; PropertyFilter: TThingFeatures; List: TThingList); override;
function FindThing(Thing: TThing; Perspective: TAvatar; Options: TFindThingOptions; out SubjectiveInformation: TSubjectiveInformation): Boolean; override;
{$IFDEF DEBUG} function Debug(Perspective: TAvatar): UTF8String; override; {$ENDIF}
end;
function MakeAtomFromStream(AClass: TClass; Stream: TTextStream): TObject;
function GetRegisteredAtomClass(AClassName: UTF8String): TClass;
procedure ForceTravel(Traveller: TThing; Destination: TAtom; Direction: TCardinalDirection; Perspective: TAvatar);
procedure ForceTravel(Traveller: TThing; Destination: TAtom; Position: TThingPosition; Perspective: TAvatar); // only tpOn and tpIn allowed
{ Note [travel]:
Navigation works as follows:
avEnter, avClimbOn, and avUseTransportation actions invoke the Position-based ForceTravel() above directly.
avGo actions first invoke the player's parent's GetNavigationInstructions() method to find out what to do
GetNavigationInstructions() then typicially defers up until you reach the location.
The TLocation.GetNavigationInstructions() looks in the appropriate direction.
The THole.GetNavigationInstructions() turns 'up' and 'out' into a location
Then, if that returns something, it calls ForceTravel().
ForceTravel() calls...
- GetSurface() (for avClimbOn and avUseTransportationSubject, via tpOn), or
- GetEntrance() (for avEnter, via tpIn, and avGo, via the TCardinalDirection version of ForceTravel).
- TThing.GetEntrance() looks for the child that is a tpOpening and defers to it, else defers to GetInside()
- TLocation.GetEntrance() calls GetSurface().
- TThresholdLocation.GetEntrance() fast-forwards you to the other side.
}
{ Note [context]:
Several of the description methods have a Context argument.
This represents the (child) object from which we are getting a
description. For example, if you are next to a pedestal and you
look around, and the pedestal is a key factor in the description
of the surrounding area, then it may be included in the room's
description as a key point. However, if you are on the pedestal,
then the pedestal will talk about itself and it's important that
the pedestal not be mentioned again by the room when the room
gives its "horizon" description.
The Context can be nil if the horizon description was requested
without having previously described anything. }
{ Note [proxy]:
Some of the APIs have "Proxy" in their name and, by default, just
defer to the same APIs without "Proxy" in their name. These are
methods whose non-proxy versions walk down the tree. The proxy
versions are used when crossing from one tree to another (e.g.
when dealing with landmarks), in particular when crossing from a
location to another, or from within a proxy method of a location
to a specific object within that location (e.g. room -> landmark
threshold -> doorway). This allows you to further fork at that
point. The regular methods should not go back up the tree, since
that risks an infinite loop (or at least a lot of redundant work). }
procedure ConnectLocations(SourceLocation: TLocation; Direction: TCardinalDirection; Destination: TLocation; Options: TLandmarkOptions = [loPermissibleNavigationTarget]); // Calls AddLandmark in both directions. Verifies that a symmetric connection has been made.
procedure QueueForDisposal(Atom: TAtom);
procedure EmptyDisposalQueue();
implementation
uses
sysutils, broadcast, exceptions, typinfo {$IFOPT C+}, typedump {$ENDIF};
procedure TSubjectiveInformation.Reset();
begin
Directions := [];
Reachable := [];
RequiredAbilitiesToNavigate := [];
end;
procedure ForceTravel(Traveller: TThing; Destination: TAtom; Direction: TCardinalDirection; Perspective: TAvatar);
var
SpecificDestination, Source: TAtom;
SourceAncestor, DestinationAncestor: TAtom;
Message: TMessage;
Position: TThingPosition;
NotificationList: TAtomList;
NotificationTarget: TAtom;
DisambiguationOpening: TThing;
begin
Assert(Assigned(Destination), 'ForceTravel requires a non-nil destination.');
Assert(Assigned(Traveller), 'ForceTravel requires a non-nil traveller.');
Source := Traveller.Parent;
SourceAncestor := Source;
while (SourceAncestor is TThing) do
SourceAncestor := (SourceAncestor as TThing).Parent;
DestinationAncestor := Destination;
while (DestinationAncestor is TThing) do
DestinationAncestor := (DestinationAncestor as TThing).Parent;
if (SourceAncestor <> DestinationAncestor) then
Source := SourceAncestor;
Position := tpOn;
DisambiguationOpening := nil;
Message := TMessage.Create();
NotificationList := TAtomList.Create();
try
SpecificDestination := Destination.GetEntrance(Traveller, Direction, Perspective, Position, DisambiguationOpening, Message, NotificationList);
if (Assigned(SpecificDestination)) then
begin
Assert(Message.AsKind = mkSuccess, 'Selected destination yet simultaneously failed.');
Assert(Message.AsText = '', 'Succeeded but with an explicit error message.');
if (Assigned(DisambiguationOpening) and (DisambiguationOpening <> SpecificDestination)) then
Perspective.AutoDisambiguated('through ' + DisambiguationOpening.GetDefiniteName(Perspective));
if (Perspective = Traveller) then
Perspective.AnnounceDeparture(Destination, Direction);
for NotificationTarget in NotificationList do
NotificationTarget.HandlePassedThrough(Traveller, Source, SpecificDestination, Position, Perspective);
if ((Traveller.Parent = SpecificDestination) and (Traveller.Position = Position)) then
begin
if (Perspective = Traveller) then
begin
Message := TMessage.Create(mkNoOp, '_ _ back where _ started, _ _.',
[Capitalise(Traveller.GetDefiniteName(Perspective)),
IsAre(Perspective.IsPlural(Perspective)),
Traveller.GetSubjectPronoun(Perspective),
ThingPositionToString(Position),
SpecificDestination.GetDefiniteName(Perspective)]);
Perspective.AvatarMessage(Message);
end;
end
else
begin
SpecificDestination.Put(Traveller, Position, psCarefully, Perspective);
if (Perspective = Traveller) then
begin
Perspective.AnnounceArrival(Source.GetRepresentative(), ReverseCardinalDirection(Direction));
Perspective.DoLook();
end;
end;
end
else
begin
Assert(Message.AsKind <> mkSuccess, 'Failed to get a specific destination yet still succeeded.');
Assert(Message.AsText <> '', 'Failed without an explicit message.');
Message.PrefaceFailureTopic('_ cannot go _.',
[Capitalise(Traveller.GetDefiniteName(Perspective)),
CardinalDirectionToString(Direction)]);
Perspective.AvatarMessage(Message);
end;
finally
NotificationList.Free();
end;
end;
procedure ForceTravel(Traveller: TThing; Destination: TAtom; Position: TThingPosition; Perspective: TAvatar);
var
SpecificDestination, Source: TAtom;
Message: TMessage;
Success: Boolean;
Ancestor: TAtom;
NotificationList: TAtomList;
NotificationTarget: TAtom;
DisambiguationOpening: TThing;
Direction: TCardinalDirection;
begin
Assert(Assigned(Destination));
Assert(Assigned(Traveller));
Assert(Position in [tpOn, tpIn]);
Source := Traveller.Parent;
Ancestor := Destination;
while ((Ancestor is TThing) and (Ancestor <> Traveller)) do
Ancestor := (Ancestor as TThing).Parent;
if (Ancestor = Traveller) then
begin
Perspective.AvatarMessage(TMessage.Create(mkCannotMoveBecauseLocation, 'That would prove rather challenging given where _ _ relative to _.',
[Destination.GetDefiniteName(Perspective),
IsAre(Destination.IsPlural(Perspective)),
Traveller.GetReflexivePronoun(Perspective)]));
end
else
if ((Position = tpOn) or (Destination is TLocation)) then
begin
SpecificDestination := Destination.GetSurface();
if (Assigned(SpecificDestination)) then
Destination := SpecificDestination;
Assert(Assigned(Destination));
Assert(Destination is TThing, 'if you want to be "on" a TLocation, give it a surface available from GetSurface()');
Message := TMessage.Create();
Success := Destination.CanPut(Traveller, tpOn, psCarefully, Perspective, Message);
if (Success) then
begin
Assert(Message.AsKind = mkSuccess);
Assert(Message.AsText = '');
if ((Traveller.Parent = Destination) and (Traveller.Position = tpOn)) then
begin
if (Perspective = Traveller) then
begin
Message := TMessage.Create(mkNoOp, '_ _ back where _ started, _ _.',
[Capitalise(Traveller.GetDefiniteName(Perspective)),
IsAre(Perspective.IsPlural(Perspective)),
Traveller.GetSubjectPronoun(Perspective),
ThingPositionToString(tpOn),
Destination.GetDefiniteName(Perspective)]);
Perspective.AvatarMessage(Message);
end;
end
else
begin
Destination.Put(Traveller, tpOn, psCarefully, Perspective);
if (Perspective = Traveller) then
begin
// XXX announcements, like AnnounceArrival() and co
Perspective.DoLook();
end;
end;
end
else
begin
Assert(Message.AsKind <> mkSuccess);
Assert(Message.AsText <> '');
Message.PrefaceFailureTopic('_ cannot get onto _.',
[Capitalise(Traveller.GetDefiniteName(Perspective)),
Destination.GetDefiniteName(Perspective)]);
Perspective.AvatarMessage(Message);
end;
end
else
if (Position = tpIn) then
begin
Assert(Destination is TThing);
DisambiguationOpening := nil;
Message := TMessage.Create();
NotificationList := TAtomList.Create();
try
Ancestor := Source;
while ((Ancestor is TThing) and (Ancestor <> Destination)) do
Ancestor := (Ancestor as TThing).Parent;
if (Ancestor = Destination) then
Direction := cdOut
else
Direction := cdIn;
SpecificDestination := Destination.GetEntrance(Traveller, Direction, Perspective, Position, DisambiguationOpening, Message, NotificationList);
if (Assigned(SpecificDestination)) then
begin
Assert(Message.AsKind = mkSuccess);
Assert(Message.AsText = '');
if (Assigned(DisambiguationOpening) and (DisambiguationOpening <> SpecificDestination)) then
Perspective.AutoDisambiguated('through ' + DisambiguationOpening.GetDefiniteName(Perspective));
if (Perspective = Traveller) then
Perspective.AnnounceDeparture(Destination);
for NotificationTarget in NotificationList do
NotificationTarget.HandlePassedThrough(Traveller, Source, SpecificDestination, Position, Perspective);
if ((Traveller.Parent = SpecificDestination) and (Traveller.Position = Position)) then
begin
if (Perspective = Traveller) then
begin
Message := TMessage.Create(mkNoOp, '_ _ back where _ started, _ _.',
[Capitalise(Traveller.GetDefiniteName(Perspective)),
IsAre(Perspective.IsPlural(Perspective)),
Traveller.GetSubjectPronoun(Perspective),
ThingPositionToString(Position),
SpecificDestination.GetDefiniteName(Perspective)]);
Perspective.AvatarMessage(Message);
end;
end
else
begin
SpecificDestination.Put(Traveller, Position, psCarefully, Perspective);
if (Perspective = Traveller) then
begin
Perspective.AnnounceArrival(Source.GetRepresentative());
Perspective.DoLook();
end;
end;
end
else
begin
Assert(Message.AsKind <> mkSuccess);
Assert(Message.AsText <> '');
Message.PrefaceFailureTopic('_ cannot enter _.',
[Capitalise(Traveller.GetDefiniteName(Perspective)),
Destination.GetDefiniteName(Perspective)]);
Perspective.AvatarMessage(Message);
end;
finally
NotificationList.Free();
end;
end
else
Assert(False, 'unexpected position for navigation: ' + IntToStr(Cardinal(Position)));
end;
{$INCLUDE atomlisthelper.inc} // generated by regen.pl
var
DisposalQueue: TAtomList;
procedure InitDisposalQueue();
begin
if (not Assigned(DisposalQueue)) then
DisposalQueue := TAtomList.Create([slOwner]);
end;
procedure QueueForDisposal(Atom: TAtom);
begin
Assert(Assigned(DisposalQueue));
DisposalQueue.AppendItem(Atom);
end;
procedure EmptyDisposalQueue();
begin
Assert(Assigned(DisposalQueue));
DisposalQueue.FreeItems();
end;
procedure TStreamedChildren.AddChild(Child: TThing; Position: TThingPosition);
begin
Assert(Length(FChildren) = Length(FPositions));
SetLength(FChildren, Length(FChildren) + 1);
SetLength(FPositions, Length(FPositions) + 1);
FChildren[High(FChildren)] := Child;
FPositions[High(FPositions)] := Position;
Assert(Length(FChildren) = Length(FPositions));
end;
procedure TStreamedChildren.Apply(Parent: TAtom);
var
Index: Cardinal;
begin
Assert(Length(FChildren) = Length(FPositions));
if (Length(FChildren) > 0) then
for Index := Low(FChildren) to High(FChildren) do
Parent.Add(FChildren[Index], FPositions[Index]);
SetLength(FChildren, 0);
SetLength(FPositions, 0);
end;
procedure TStreamedLandmarks.AddLandmark(Direction: TCardinalDirection; Atom: TAtom; Options: TLandmarkOptions);
begin
Assert(Length(FLandmarks) = Length(FDirections));
Assert(Length(FLandmarks) = Length(FOptions));
SetLength(FDirections, Length(FDirections) + 1);
SetLength(FLandmarks, Length(FLandmarks) + 1);
SetLength(FOptions, Length(FOptions) + 1);
FDirections[High(FDirections)] := Direction;
FLandmarks[High(FLandmarks)] := Atom;
FOptions[High(FOptions)] := Options;
Assert(Length(FLandmarks) = Length(FDirections));
Assert(Length(FLandmarks) = Length(FOptions));
end;
procedure TStreamedLandmarks.Apply(Parent: TLocation);
var
Index: Cardinal;
begin
Assert(Length(FLandmarks) = Length(FDirections));
Assert(Length(FLandmarks) = Length(FOptions));
if (Length(FLandmarks) > 0) then
for Index := Low(FLandmarks) to High(FLandmarks) do // $R-
Parent.AddLandmark(FDirections[Index], FLandmarks[Index], FOptions[Index]);
SetLength(FDirections, 0);
SetLength(FLandmarks, 0);
SetLength(FOptions, 0);
end;
constructor TAtom.Create();
begin
{$IFDEF DEBUG}
FIntegritySelf := PtrUInt(Self);
{$ENDIF}
inherited;
FChildren := TThingList.Create([slOwner]);
end;
destructor TAtom.Destroy();
begin
{$IFDEF DEBUG}
if (FIntegritySelf > 0) then
begin
Assert(FIntegritySelf < High(PtrUInt), 'Tried to free an already-freed TAtom');
Assert(FIntegritySelf = PtrUInt(Self), 'Evidence of heap corruption detected');
FIntegritySelf := High(PtrUInt);
end;
{$ENDIF}
FChildren.Free();
inherited;
end;
constructor TAtom.Read(Stream: TReadStream);
begin
{$IFDEF DEBUG}
FIntegritySelf := PtrUInt(Self);
{$ENDIF}
inherited;
FChildren := Stream.ReadObject() as TThingList;
end;
procedure TAtom.Write(Stream: TWriteStream);
begin
inherited;
Stream.WriteObject(FChildren);
end;
class function TAtom.HandleChildProperties(Properties: TTextStreamProperties; var Values: TStreamedChildren): Boolean;
var
Position: TThingPosition;
Child: TThing;
Stream: TTextStream;
begin
if (Properties.Name = pnChild) then
begin
Stream := Properties.Accept();
Position := Stream.specialize GetEnum<TThingPosition>();
Stream.ExpectPunctuation(',');
Child := Stream.specialize GetObject<TThing>();
Values.AddChild(Child, Position);
Properties.Advance();
Result := False;
end
else
Result := True;
end;
class procedure TAtom.DescribeProperties(Describer: TPropertyDescriber);
begin
end;
function MakeAtomFromStream(AClass: TClass; Stream: TTextStream): TObject;
var
Atom: TAtom;
Properties: TTextStreamProperties;
begin
Assert(Assigned(AClass));
if (not AClass.InheritsFrom(TAtom)) then
Stream.Fail(AClass.ClassName + ' is not a TAtom');
Properties := TTextStreamProperties.Create(Stream);
try
Atom := TAtomClass(AClass).CreateFromProperties(Properties);
if (not Properties.Done) then
Stream.Fail('Could not parse property "' + Properties.Name + '"');
finally
Properties.Free();
end;
Result := Atom;
end;
{$IFDEF DEBUG}
function GetRegisteredAtomClass(AClassName: UTF8String): TClass;
var
Candidate: StorableClass;
begin
Result := nil;
Candidate := GetRegisteredClass(AClassName);
if ((Candidate <> nil) and Candidate.InheritsFrom(TAtom)) then
Result := TAtomClass(Candidate);
end;
{$ENDIF}
{$IFOPT C+}
procedure TAtom.AssertChildPositionOk(Thing: TThing; Position: TThingPosition);
var
TempPosition: TThingPosition;
Child: TThing;
begin
TempPosition := tpIn;
Assert((Position <> tpIn) or (GetInside(TempPosition) <> nil), 'Tried to put something inside something without an inside (use CanPut!)');
TempPosition := tpIn;
Assert((Position <> tpIn) or (GetInside(TempPosition) = Self), 'Tried to put something inside something but the inside is something else (use GetInside!)');
if (Position in tpOpening) then
for Child in FChildren do
Assert(not (Child.FPosition in tpOpening), 'Can''t have two things that are the tpOpening of another thing (see note in grammarian.pas)');
end;
{$ENDIF}
function TAtom.GetChildren(const PositionFilter: TThingPositionFilter): TThingList;
begin
Result := TThingList.Create([slDropDuplicates]);
EnumerateChildren(Result, PositionFilter);
end;
procedure TAtom.EnumerateChildren(List: TThingList; const PositionFilter: TThingPositionFilter);
var
Child: TThing;
begin
for Child in FChildren do
if (Child.FPosition in PositionFilter) then
List.AppendItem(Child);
end;
procedure TAtom.Add(Thing: TThing; Position: TThingPosition);
{$IFOPT C+}
var
ParentSearch: TAtom;
{$ENDIF}
begin
{$IFOPT C+} AssertChildPositionOk(Thing, Position); {$ENDIF}
if (Assigned(Thing.FParent)) then
Thing.FParent.Remove(Thing);
Assert(not Assigned(Thing.FParent));
FChildren.AppendItem(Thing);
Thing.FParent := Self;
Thing.FPosition := Position;
{$IFOPT C+}
// check for cycles
ParentSearch := Thing;
Assert(ParentSearch is TThing);
repeat
ParentSearch := (ParentSearch as TThing).Parent;
Assert(ParentSearch <> Thing, 'Cycle in world involving ' + Thing.GetLongDefiniteName(nil));
until (not (ParentSearch is TThing));
{$ENDIF}
end;
procedure TAtom.Add(Thing: TThingList.TEnumerator; Position: TThingPosition);
var
OldParent: TAtom;
ActualThing: TThing;
{$IFOPT C+}
ParentSearch: TAtom;
{$ENDIF}
begin
Assert(Thing.FList <> FChildren);
ActualThing := Thing.Current;
{$IFOPT C+} AssertChildPositionOk(ActualThing, Position); {$ENDIF}
Assert(Assigned(ActualThing));
OldParent := ActualThing.FParent;
FChildren.AdoptItem(Thing);
ActualThing.FParent := Self;
ActualThing.FPosition := Position;
if (Assigned(OldParent)) then
OldParent.Removed(ActualThing);
{$IFOPT C+}
// check for cycles
ParentSearch := ActualThing;
Assert(ParentSearch is TThing);
repeat
ParentSearch := (ParentSearch as TThing).Parent;
Assert(ParentSearch <> ActualThing);
until (not (ParentSearch is TThing));
{$ENDIF}
end;
procedure TAtom.Remove(Thing: TThing);
begin
FChildren.RemoveItem(Thing);
Thing.FParent := nil;
Removed(Thing);
end;
procedure TAtom.Remove(Thing: TThingList.TEnumerator);
var
OldThing: TThing;
begin
Assert(Thing.FList = FChildren);
OldThing := Thing.Current;
Thing.Remove();
OldThing.FParent := nil;
Removed(OldThing);
end;
procedure TAtom.Removed(Thing: TThing);
begin
end;
function TAtom.CanPut(Thing: TThing; ThingPosition: TThingPosition; Care: TPlacementStyle; Perspective: TAvatar; var Message: TMessage): Boolean;
begin
Assert(Message.IsValid);
if (ThingPosition = tpOn) then
begin
Result := CanSurfaceHold(Thing.GetIntrinsicSize(), 1);
if (not Result) then
Message := TMessage.Create(mkTooBig, 'There is not enough room on _ for _.',
[GetDefiniteName(Perspective),
Thing.GetDefiniteName(Perspective)]);
end
else
if (ThingPosition = tpIn) then
begin
Result := CanInsideHold(Thing.GetOutsideSizeManifest(), 1);
if (not Result) then
begin
if ((not Assigned(GetInside(ThingPosition))) and (Self is TThing)) then
Message := TMessage.Create(mkNoOpening, '_ _ not appear to have an opening.',
[Capitalise(GetDefiniteName(Perspective)),
TernaryConditional('does', 'do', IsPlural(Perspective))])
else
Message := TMessage.Create(mkTooBig, 'There is not enough room in _ for _.',
[GetDefiniteName(Perspective),
Thing.GetDefiniteName(Perspective)]);;
end;
end
else
begin
Assert(False, 'Unexpected position ' + IntToStr(Cardinal(ThingPosition)));
Result := False;
end;
end;
procedure TAtom.Put(Thing: TThing; Position: TThingPosition; Care: TPlacementStyle; Perspective: TAvatar);
var
OldParent: TAtom;
begin
OldParent := Thing.FParent;
Assert((OldParent <> Self) or (Position <> Thing.FPosition)); // added this late, so callers might still need updating
Add(Thing, Position);
Thing.Moved(OldParent, Care, Perspective);
HandleAdd(Thing, Perspective);
end;
function TAtom.GetMassManifest(): TThingMassManifest;
var
Child: TThing;
begin
Zero(Result);
for Child in FChildren do
Result := Result + Child.GetMassManifest();