| 1 |
{ |
| 2 |
Copyright 2006-2023 Michalis Kamburelis. |
| 3 |
|
| 4 |
This file is part of "Castle Game Engine". |
| 5 |
|
| 6 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 7 |
included in this distribution, for details about the copyright. |
| 8 |
|
| 9 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 |
|
| 13 |
---------------------------------------------------------------------------- |
| 14 |
} |
| 15 |
|
| 16 |
{ Loading of typical 3D game level with placeholders (TLevel), |
| 17 |
management of available game levels (TLevelInfo, @link(Levels)). } |
| 18 |
unit CastleLevels |
| 19 |
deprecated 'design levels as a collection of TCastleTransform descendans, like TCastleScene, without resource.xml necessary'; |
| 20 |
|
| 21 |
{$I castleconf.inc} |
| 22 |
|
| 23 |
interface |
| 24 |
|
| 25 |
{$warnings off} // using deprecated in deprecated unit |
| 26 |
|
| 27 |
uses Classes, DOM, Generics.Collections, |
| 28 |
CastleVectors, CastleSceneCore, CastleScene, CastleBoxes, X3DNodes, |
| 29 |
X3DFields, CastleCameras, CastleSectors, CastleUtils, CastleClassUtils, |
| 30 |
CastlePlayer, CastleResources, CastleProgress, CastleInputs, |
| 31 |
CastleSoundEngine, CastleTransform, CastleShapes, CastleXMLConfig, CastleImages, |
| 32 |
CastleTimeUtils, CastleViewport, CastleFindFiles, CastleKeysMouse; |
| 33 |
|
| 34 |
{$warnings on} |
| 35 |
|
| 36 |
type |
| 37 |
TLevelLogic = class; |
| 38 |
TLevelLogicClass = class of TLevelLogic; |
| 39 |
|
| 40 |
TLevelInfo = class |
| 41 |
private |
| 42 |
FLogicClass: TLevelLogicClass; |
| 43 |
FName: string; |
| 44 |
FSceneUrl: String; |
| 45 |
FTitle: string; |
| 46 |
FTitleHint: string; |
| 47 |
FNumber: Integer; |
| 48 |
FDemo: boolean; |
| 49 |
FPlayed: boolean; |
| 50 |
FDefaultPlayed: boolean; |
| 51 |
FLoadingImage: TRGBImage; |
| 52 |
FLoadingBarYPosition: Single; |
| 53 |
FPlaceholderName: TPlaceholderName; |
| 54 |
FPlaceholderReferenceDirection: TVector3; |
| 55 |
FMusicSound: TCastleSound; |
| 56 |
{ We keep XML Document reference through the lifetime of this object, |
| 57 |
to allow the particular level logic (TLevelLogic descendant) |
| 58 |
to read some level-logic-specific variables from it. } |
| 59 |
Document: TXMLDocument; |
| 60 |
DocumentBaseUrl: String; |
| 61 |
LevelResources: T3DResourceList; |
| 62 |
procedure LoadFromDocument; |
| 63 |
protected |
| 64 |
Element: TDOMElement; |
| 65 |
public |
| 66 |
constructor Create; |
| 67 |
destructor Destroy; override; |
| 68 |
|
| 69 |
(*Level logic class. This is indicated by the "type" attribute in level.xml |
| 70 |
file. By default level logic uses a base TLevelLogic class, |
| 71 |
which corresponds to using @code(type="Level") in level.xml file. |
| 72 |
|
| 73 |
Changing this allows to use a different ObjectPascal class to implement |
| 74 |
the level behavior. |
| 75 |
You can create your own TLevelLogic descendants and register them |
| 76 |
like |
| 77 |
|
| 78 |
@longCode(# |
| 79 |
type |
| 80 |
TMyLevelLogic = class(TLevelLogic) |
| 81 |
{ ... override whatever you want ... } |
| 82 |
end; |
| 83 |
|
| 84 |
... |
| 85 |
LevelLogicClasses['MyLevel'] := TMyLevelLogic; |
| 86 |
#) |
| 87 |
|
| 88 |
And then you can use @code(type="MyLevel") inside level.xml |
| 89 |
to use your class. |
| 90 |
Many advanced tricks are possible by implementing your own TLevelLogic |
| 91 |
descendant. See Castle1 GameLevelSpecific.pas unit for some examples. |
| 92 |
*) |
| 93 |
property LogicClass: TLevelLogicClass read FLogicClass write FLogicClass; |
| 94 |
|
| 95 |
{ Unique identifier of this level. This name may be useful in scripts, |
| 96 |
as @link(TLevel.Load) parameter and such. |
| 97 |
|
| 98 |
For all (current and future) uses it should be a valid VRML/X3D |
| 99 |
and ObjectPascal identifier, so use only (English) letters, |
| 100 |
underscores and digits (and don't start with a digit). } |
| 101 |
property Name: string read FName write FName; |
| 102 |
|
| 103 |
{ Main level 3D model. When the level is loaded, this scene will be set |
| 104 |
as TCastleRootTransform.MainScene, |
| 105 |
so it determines the default viewpoint, background and such. |
| 106 |
|
| 107 |
Usually it also contains the most (if not all) of the visible level geometry, |
| 108 |
scripts and such. Although level logic (TLevelLogic descendant determined |
| 109 |
by LevelClass) may also add any number of additional objects |
| 110 |
(TCastleTransform instances) to the world. } |
| 111 |
property SceneUrl: String read FSceneUrl write FSceneUrl; |
| 112 |
|
| 113 |
{$ifdef FPC} |
| 114 |
{ @deprecated Deprecated name for SceneUrl. } |
| 115 |
property SceneFileName: string read FSceneUrl write FSceneUrl; deprecated; |
| 116 |
{$endif} |
| 117 |
|
| 118 |
{ Nice name of the level for user. This should be user-friendly, |
| 119 |
so it can use spaces, non-English letters and such. |
| 120 |
|
| 121 |
The core engine (like this CastleLevels unit) doesn't use this title |
| 122 |
much, it's only for progress bars and log messages. |
| 123 |
|
| 124 |
It is up to the final game code to use this title in more interesting |
| 125 |
ways. For example to show a choice of starting level to the user. |
| 126 |
The core engine doesn't make such "New Game" menus automatically |
| 127 |
(because various games may have widly different ideas how to make it |
| 128 |
and how to show it). But we give the developer tools to make such |
| 129 |
menus easily, for example you can use TCastleOnScreenMenu for this. } |
| 130 |
property Title: string read FTitle write FTitle; |
| 131 |
|
| 132 |
{ Additional text that may be displayed near level title. |
| 133 |
|
| 134 |
The engine doesn't use this property at all, it's only loaded from level.xml |
| 135 |
file. It is available for your "New Game" (or similar screen) implementation |
| 136 |
(see @link(Title) for more comments about this). } |
| 137 |
property TitleHint: string read FTitleHint write FTitleHint; |
| 138 |
|
| 139 |
{ Level number. |
| 140 |
|
| 141 |
The engine doesn't use this property at all, it's only loaded from level.xml |
| 142 |
file. It is available for your "New Game" (or similar screen) implementation |
| 143 |
(see @link(Title) for more comments about this). |
| 144 |
|
| 145 |
For example level number may be used to order levels in the menu. |
| 146 |
This @italic(does not) determine the order in which levels are played, |
| 147 |
as levels do not have to be played in a linear order. } |
| 148 |
property Number: Integer read FNumber write FNumber default 0; |
| 149 |
|
| 150 |
{ Is it a demo level. |
| 151 |
|
| 152 |
The engine doesn't use this property at all, it's only loaded from level.xml |
| 153 |
file. It is available for your "New Game" (or similar screen) implementation |
| 154 |
(see @link(Title) for more comments about this). } |
| 155 |
property Demo: boolean read FDemo write FDemo default false; |
| 156 |
|
| 157 |
{ Was the level played. |
| 158 |
|
| 159 |
This is automatically managed. Basically, we set it to @true |
| 160 |
when the level is played, and we save it to user preferences. |
| 161 |
|
| 162 |
Details: |
| 163 |
@unorderedList( |
| 164 |
@item(It is set to @true when loading level.) |
| 165 |
|
| 166 |
@item(It is saved to disk (user preferences file) when game exits, |
| 167 |
and loaded when game starts. As long as you call @code(Config.Load), |
| 168 |
@code(Config.Save) from CastleConfig unit. To load, you must |
| 169 |
also call explicitly @link(TLevelInfoList.LoadFromConfig Levels.LoadFromConfig) now.) |
| 170 |
|
| 171 |
@item(The default value comes from DefaultPlayed property, |
| 172 |
which in turn is loaded from level.xml file, and by default is @false. |
| 173 |
To allows you to artificially mark some levels as "Played" on |
| 174 |
the first game run, which may be helpful if you use this property |
| 175 |
e.g. to filter the levels in "New Game" menu.) |
| 176 |
) |
| 177 |
|
| 178 |
The engine doesn't look at this property for anything, |
| 179 |
whether the level is played or not has no influence over how we work. |
| 180 |
It is just available for your game, for example to use in your |
| 181 |
"New Game" (or similar screen) implementation |
| 182 |
(see @link(Title) for more comments about this). } |
| 183 |
property Played: boolean read FPlayed write FPlayed; |
| 184 |
|
| 185 |
{ Should the level be initially considered "played". |
| 186 |
This determines the initial value of @link(Played) property |
| 187 |
(if nothing was stored in user preferences about this level, |
| 188 |
see TLevelInfoList.LoadFromConfig; or if TLevelInfoList.LoadFromConfig |
| 189 |
is not called by the game). |
| 190 |
|
| 191 |
How is this information useful, depends on a particular game. |
| 192 |
For example, some games may decide to show in the "New Game" |
| 193 |
menu levels only with Played=true. Some games may simply ignore it. } |
| 194 |
property DefaultPlayed: boolean read FDefaultPlayed write FDefaultPlayed; |
| 195 |
|
| 196 |
{ Background image shown when loading the level, @nil if none. |
| 197 |
This is loaded from URL indicated by attribute loading_image |
| 198 |
in level.xml. } |
| 199 |
property LoadingImage: TRGBImage read FLoadingImage write FLoadingImage; |
| 200 |
|
| 201 |
{ Vertical position of progress bar when loading the level. |
| 202 |
Between 0 and 1, default value 0.5 means "middle of the screen". |
| 203 |
Should be synchronized with how LoadingImage looks (if you set it), |
| 204 |
to make the progress when loading level look nice. |
| 205 |
|
| 206 |
Technically, this is used for TProgressUserInterface.BarYPosition. } |
| 207 |
property LoadingBarYPosition: Single |
| 208 |
read FLoadingBarYPosition write FLoadingBarYPosition |
| 209 |
{$ifdef FPC}default TProgressUserInterface.DefaultBarYPosition{$endif}; |
| 210 |
|
| 211 |
{ Placeholder detection method. See TPlaceholderName, and see |
| 212 |
@link(TLevel.Load) for a description when we use placeholders. |
| 213 |
Default value is @code(PlaceholderNames['x3dshape']). } |
| 214 |
property PlaceholderName: TPlaceholderName |
| 215 |
read FPlaceholderName write FPlaceholderName; |
| 216 |
|
| 217 |
{ How to interpret the placeholders direction (like the initial |
| 218 |
creature direction on the level). |
| 219 |
Some placeholders (currently, only creatures) may be used to determine |
| 220 |
initial direction of the resource. For example, the direction |
| 221 |
the creature is initially facing. |
| 222 |
This direction is calculated as the transformation |
| 223 |
of given placeholder applied to this 3D vector. |
| 224 |
|
| 225 |
The correct value may depend on the exporter you used to create 3D models, |
| 226 |
and on the exporter settings (how and if it rotates the model when exporting, |
| 227 |
and is this rotation recorded in placeholder transformation |
| 228 |
or applied directly to mesh coordinates). It may also depend on personal |
| 229 |
preference, as it determines how you set resources in your 3D modelling tool |
| 230 |
(like Blender). |
| 231 |
|
| 232 |
Fortunately, the default value (+X vector) is suitable for at least |
| 233 |
2 common situations: |
| 234 |
|
| 235 |
@orderedList( |
| 236 |
@item(If your exporter rotates the world to turn +Z up into +Y up. |
| 237 |
(This is the case of default Blender X3D exporter with default settings.)) |
| 238 |
|
| 239 |
@item(If your exporter doesn't rotate the world. |
| 240 |
(You can configure Blender exporter to behave like this. |
| 241 |
You may also then configure engine to use +Z as up vector for everything, |
| 242 |
see "Which way is up?" on https://castle-engine.io/manual_up.php .)) |
| 243 |
) |
| 244 |
|
| 245 |
In Blender it's useful to enable the "Display -> Wire" option for placeholder |
| 246 |
objects, then Blender will show arrows inside the placeholder. |
| 247 |
+X of the arrow determines the default direction understood by our engine. } |
| 248 |
property PlaceholderReferenceDirection: TVector3 |
| 249 |
read FPlaceholderReferenceDirection write FPlaceholderReferenceDirection; |
| 250 |
|
| 251 |
{ Music played when entering the level. |
| 252 |
None (nil) by default. } |
| 253 |
property MusicSound: TCastleSound read FMusicSound write FMusicSound; |
| 254 |
end; |
| 255 |
|
| 256 |
TLevelInfoList = class({$ifdef FPC}specialize{$endif} TObjectList<TLevelInfo>) |
| 257 |
private |
| 258 |
{ How many TLevel have references to our children by |
| 259 |
TLevel.Info? } |
| 260 |
References: Cardinal; |
| 261 |
procedure AddFromInfo(const Info: TFileInfo; var StopSearch: boolean); |
| 262 |
public |
| 263 |
{ raises Exception if such Name is not on the list. } |
| 264 |
function FindName(const AName: string): TLevelInfo; |
| 265 |
|
| 266 |
{ Add all available levels found by scanning for level.xml inside data |
| 267 |
directory. |
| 268 |
Overloaded version without parameter just looks inside 'castle-data:/'. |
| 269 |
For the specification of level.xml format see |
| 270 |
[https://castle-engine.io/creating_data_levels.php] . |
| 271 |
|
| 272 |
This should be called after resources (creatures and items) are known, |
| 273 |
as they may be referenced by level.xml files. |
| 274 |
So call @link(T3DResourceList.LoadFromFiles Resources.LoadFromFiles) |
| 275 |
@italic(before) calling this (if you |
| 276 |
want to use any creatures / items at all, of course). |
| 277 |
|
| 278 |
All TLevelInfo.Played values are initially set to @false. |
| 279 |
You must call LoadFromConfig @italic(after) calling this |
| 280 |
to read TLevelInfo.Played values from user preferences file. |
| 281 |
|
| 282 |
@groupBegin } |
| 283 |
procedure LoadFromFiles(const LevelsPath: string); overload; |
| 284 |
procedure LoadFromFiles; overload; |
| 285 |
{ @groupEnd } |
| 286 |
|
| 287 |
{ Add a single level information from the XML file at given location. |
| 288 |
The given XML file must have <level> root element and be written |
| 289 |
according to |
| 290 |
https://castle-engine.io/creating_data_levels.php . } |
| 291 |
procedure AddFromFile(const Url: String); |
| 292 |
|
| 293 |
{ Sort by @link(TLevelInfo.Number). |
| 294 |
Done automatically at the end of @link(LoadFromFiles), |
| 295 |
you may want to call it explicitly after doing @link(AddFromFile). } |
| 296 |
procedure SortByNumber; |
| 297 |
|
| 298 |
{ For all available levels, read their TLevelInfo.Played |
| 299 |
from config file (like @link(UserConfig)). |
| 300 |
|
| 301 |
This is useful only if you actually look at |
| 302 |
TLevelInfo.Played for any purpose (for example, |
| 303 |
to decide which levels are displayed in the menu). By default, |
| 304 |
our engine doesn't look at TLevelInfo.Played for anything. } |
| 305 |
procedure LoadFromConfig(const Config: TCastleConfig); |
| 306 |
|
| 307 |
{ Save Played properties of every level |
| 308 |
to a config file (like @link(UserConfig)). } |
| 309 |
procedure SaveToConfig(const Config: TCastleConfig); |
| 310 |
end; |
| 311 |
|
| 312 |
{ Manage (load and unload) game level. |
| 313 |
|
| 314 |
For basic usage, assign @link(Viewport) and call @link(Load). |
| 315 |
It is similar to creating regular TCastleScene and adding it to |
| 316 |
@code(Viewport.Items), but has some extra features. Most notably, |
| 317 |
it will instantiate also creatures and items looking at special |
| 318 |
"placeholders" in the model file. } |
| 319 |
TLevel = class(TAbstractLevel) |
| 320 |
strict private |
| 321 |
type |
| 322 |
TLevelInternalLogic = class(TCastleTransform) |
| 323 |
Level: TLevel; |
| 324 |
procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override; |
| 325 |
end; |
| 326 |
var |
| 327 |
FViewport: TCastleViewport; |
| 328 |
FInternalLogic: TLevelInternalLogic; |
| 329 |
FCreaturesRoot, FItemsRoot: TCastleTransform; |
| 330 |
FLogic: TLevelLogic; |
| 331 |
FInfo: TLevelInfo; |
| 332 |
LevelResourcesPrepared: boolean; |
| 333 |
FWater: TBox3D; |
| 334 |
FSectors: TSectorList; |
| 335 |
Waypoints: TWaypointList; |
| 336 |
FPlayer: TPlayer; |
| 337 |
FPlayerSwimming: TPlayerSwimming; |
| 338 |
SickProjectionTime: TFloatTime; |
| 339 |
FFreeAtUnload: TComponent; |
| 340 |
{ Like TLevel.Load, but doesn't care about AInfo.LoadingImage. } |
| 341 |
procedure LoadCore(const AInfo: TLevelInfo); |
| 342 |
{ Unload Items from previous level, keeps only Player on Items. |
| 343 |
Returns previous resources. You have to call Release and free them. } |
| 344 |
function UnloadCore: T3DResourceList; |
| 345 |
function Placeholder(Shape: TShape; PlaceholderName: string): boolean; |
| 346 |
procedure SetPlayer(const Value: TPlayer); |
| 347 |
{ Assigns Camera and Navigation on level loading and setting/change player } |
| 348 |
procedure InitializeCamera; |
| 349 |
function Items: TCastleRootTransform; |
| 350 |
procedure Update(const SecondsPassed: Single); |
| 351 |
protected |
| 352 |
procedure Notification(AComponent: TComponent; Operation: TOperation); override; |
| 353 |
public |
| 354 |
constructor Create(AOwner: TComponent); override; |
| 355 |
destructor Destroy; override; |
| 356 |
|
| 357 |
function GetPlayer: TCastleTransform; override; |
| 358 |
function GetSectors: TSectorList; override; |
| 359 |
function RootTransform: TCastleRootTransform; override; |
| 360 |
function CreaturesRoot: TCastleTransform; override; |
| 361 |
function ItemsRoot: TCastleTransform; override; |
| 362 |
function PrepareParams: TPrepareParams; override; |
| 363 |
function FreeAtUnload: TComponent; override; |
| 364 |
|
| 365 |
{ Viewport whose contents will be adjusted to show given level. |
| 366 |
Must be assigned before @link(Load). } |
| 367 |
property Viewport: TCastleViewport read FViewport write FViewport; |
| 368 |
|
| 369 |
{ Load game level. |
| 370 |
|
| 371 |
@unorderedList( |
| 372 |
@item(@bold(Set Viewport.Items): |
| 373 |
|
| 374 |
Clear @link(TCastleViewport.Items), |
| 375 |
clear @link(TCastleViewport.Navigation Navigation), |
| 376 |
clear @link(TCastleRootTransform.MainScene) as well. |
| 377 |
Then load a new main scene and set navigation, adding to |
| 378 |
@link(TCastleViewport.Items) all resources (creatures and items) |
| 379 |
defined by placeholders named CasRes* in the main level file.) |
| 380 |
|
| 381 |
@item(@bold(Make sure resources are ready:) |
| 382 |
|
| 383 |
Resources are T3DResource instances on @link(Resources) list. |
| 384 |
They are heavy (in terms of memory use and preparation time), |
| 385 |
so you don't want to just load everything for every level. |
| 386 |
This method makes sure that all resources required by this level |
| 387 |
are prepared. All resources requested in level.xml file |
| 388 |
(in <resources> element in level.xml), |
| 389 |
as well as resources requested in player.xml file, |
| 390 |
as well as resources with AlwaysPrepared (usually: all possible items |
| 391 |
that can be dropped from player inventory on any level) |
| 392 |
will be prepared.) |
| 393 |
|
| 394 |
@item(@bold(Initialize move limits and water volume from placeholders). |
| 395 |
Special object names CasMoveLimit and CasWater (in the future: |
| 396 |
CasWater* with any suffix) in the main scene 3D model |
| 397 |
determine the places where player can go and where water is. |
| 398 |
|
| 399 |
When CasMoveLimit object is missing, |
| 400 |
we calculate it to include the level bounding box, with some |
| 401 |
additional space above (to allow flying).) |
| 402 |
|
| 403 |
@item(@bold(Initialize sectors and waypoints from placeholders). |
| 404 |
Special shape names CasSector* and CasWaypoint* can be used |
| 405 |
in level 3D model to help creature AI. |
| 406 |
You can add and name such shapes in 3D modeler, like Blender, |
| 407 |
and they will be automatically understood by the engine when loading level. |
| 408 |
|
| 409 |
Objects named CasSector<index>[_<ignored>] define sectors. |
| 410 |
The geometry of a sector with given <index> is set to be the sum |
| 411 |
of all CasSector<index>* boxes. |
| 412 |
Sectors are numbered from 0. |
| 413 |
|
| 414 |
Objects named CasWaypoint[<ignored>] define waypoints. |
| 415 |
Each waypoint is stored as a 3D point, this point is the middle of the |
| 416 |
bounding box of the object named CasWaypoint[<ignored>]. |
| 417 |
|
| 418 |
After extracting from level 3D model, |
| 419 |
sectors and waypoints are then connected together by |
| 420 |
TSectorList.LinkToWaypoints. The idea is that you can go from |
| 421 |
one sector to the other through the waypoint that is placed on |
| 422 |
the border of both of them.) |
| 423 |
|
| 424 |
@item(@bold(Prepare everything possible for rendering and collision |
| 425 |
detection) to avoid later preparing things on-demand (which would cause |
| 426 |
unpleasant delay during gameplay).) |
| 427 |
) |
| 428 |
|
| 429 |
The overloaded version with a LevelName string searches the @link(Levels) |
| 430 |
list for a level with given name (and raises exception if it cannot |
| 431 |
be found). It makes sense if you filled the @link(Levels) list before, |
| 432 |
usually by @link(TLevelInfoList.LoadFromFiles Levels.LoadFromFiles) |
| 433 |
call. So you can easily define a level in your data with @code(name="xxx") |
| 434 |
in the @code(level.xml) file, and then you can load it |
| 435 |
by @code(Load('xxx')) call. |
| 436 |
|
| 437 |
It's important to note that @bold(you do not have to use |
| 438 |
this method to make a 3D game). You may as well just load the 3D scene |
| 439 |
yourself, and add things to TCastleViewport.Items and |
| 440 |
TCastleRootTransform.MainScene directly. |
| 441 |
This method is just a comfortable way to set a world, |
| 442 |
with creatures and items, using placeholders. |
| 443 |
|
| 444 |
@groupBegin } |
| 445 |
procedure Load(const LevelName: string); overload; |
| 446 |
procedure Load(const AInfo: TLevelInfo); overload; |
| 447 |
{ @groupEnd } |
| 448 |
|
| 449 |
{ Level logic and state. } |
| 450 |
property Logic: TLevelLogic read FLogic; |
| 451 |
|
| 452 |
{ Level information, independent from current level state. } |
| 453 |
property Info: TLevelInfo read FInfo; |
| 454 |
|
| 455 |
{ Release everything loaded by @link(Load), clearing the 3D world. |
| 456 |
|
| 457 |
You do not have to call this in normal circumstances, |
| 458 |
as each @link(Load) automatically clears previous 3D world. If fact, |
| 459 |
you should not call this in normal circumstances: |
| 460 |
calling this prevents the next Load to reuse resources |
| 461 |
that were needed by both old and new level. |
| 462 |
|
| 463 |
Call this only if you really want to conserve memory @italic(right now). |
| 464 |
Or when you want to force reload of resources at next Load |
| 465 |
call (for example, if you changed BakedAnimationSmoothness, it is useful |
| 466 |
--- otherwise the old animations will remain loaded with old BakedAnimationSmoothness |
| 467 |
setting). } |
| 468 |
procedure Unload; |
| 469 |
|
| 470 |
{ Sectors and waypoints of this world, for AI in 3D. |
| 471 |
Initialized by @link(Load). |
| 472 |
@nil if you never call @link(Load). } |
| 473 |
property Sectors: TSectorList read FSectors; |
| 474 |
|
| 475 |
{ Water volume in the scene. It may be used by various 3D objects |
| 476 |
to indicate appropriate behavior --- some things swim, |
| 477 |
some things drown and such. For now, this is only used by TPlayer |
| 478 |
class to detect swimming (and make appropriate sounds, special rendering, |
| 479 |
drowning and such). |
| 480 |
|
| 481 |
For now, this is just a simple TBox3D. It will |
| 482 |
be extended to represent a set of flexible 3D volumes in the future. |
| 483 |
|
| 484 |
Empty initially. Initialize it however you want. } |
| 485 |
property Water: TBox3D read FWater write FWater; |
| 486 |
|
| 487 |
{ Player in this 3D world. This serves various purposes: |
| 488 |
|
| 489 |
@unorderedList( |
| 490 |
@item(This object never collides with the navigation. |
| 491 |
See @link(TCastleViewport.AvoidNavigationCollisions).) |
| 492 |
|
| 493 |
@item( |
| 494 |
Player transformation will be automatically synchronized |
| 495 |
with current @link(TCastleViewport.Camera) position. |
| 496 |
As such, TPlayer represents the volume of player in 1st person games.) |
| 497 |
|
| 498 |
@item(For AI in CastleCreatures, hostile creatures will attack |
| 499 |
this player. So this determines the target position that |
| 500 |
creatures try to reach, where they shoot missiles etc. |
| 501 |
More advanced AI, with friendlies/companions, or cooperating |
| 502 |
factions of creatures, may have other mechanisms to determine who |
| 503 |
wants to attack who.) |
| 504 |
|
| 505 |
@item(For items on level in CastleItems, this player will pick up the items |
| 506 |
lying on the ground, and will be able to equip weapons. |
| 507 |
This functionality may be generalized in the future, to allow |
| 508 |
anyone to pick up and carry and equip items.) |
| 509 |
) |
| 510 |
} |
| 511 |
property Player: TPlayer read FPlayer write SetPlayer; |
| 512 |
end; |
| 513 |
|
| 514 |
TLevelProperties = TAbstractLevel deprecated 'use TAbstractLevel'; |
| 515 |
|
| 516 |
{ Viewport that can comfortably load and manage a 3D game level. |
| 517 |
It really adds only one new method to TCastleSceneManager: |
| 518 |
@link(LoadLevel), see it's documentation to know what it gives you. |
| 519 |
It also exposes @link(Logic) and @link(Info) properties |
| 520 |
corresponding to the currently loaded level. |
| 521 |
|
| 522 |
@deprecated @exclude Use @link(TLevel) instead. } |
| 523 |
TGameSceneManager = class(TCastleSceneManager) |
| 524 |
strict private |
| 525 |
FLevel: TLevel; |
| 526 |
function GetSectors: TSectorList; |
| 527 |
function GetWater: TBox3D; |
| 528 |
procedure SetWater(const Value: TBox3D); |
| 529 |
function GetPlayer: TPlayer; |
| 530 |
procedure SetPlayer(const Value: TPlayer); |
| 531 |
public |
| 532 |
constructor Create(AOwner: TComponent); override; |
| 533 |
destructor Destroy; override; |
| 534 |
|
| 535 |
procedure LoadLevel(const LevelName: string); overload; |
| 536 |
procedure LoadLevel(const AInfo: TLevelInfo); overload; |
| 537 |
function Logic: TLevelLogic; |
| 538 |
function Info: TLevelInfo; |
| 539 |
procedure UnloadLevel; |
| 540 |
property Sectors: TSectorList read GetSectors; |
| 541 |
property Water: TBox3D read GetWater write SetWater; |
| 542 |
property Player: TPlayer read GetPlayer write SetPlayer; |
| 543 |
function LevelProperties: TAbstractLevel; |
| 544 |
end deprecated 'use TLevel together with a TCastleViewport'; |
| 545 |
|
| 546 |
{ Level logic. } |
| 547 |
TLevelLogic = class(TCastleBehavior) |
| 548 |
strict private |
| 549 |
FTime: TFloatTime; |
| 550 |
FLevel: TAbstractLevel; |
| 551 |
protected |
| 552 |
{ Level that we are part of. } |
| 553 |
property Level: TAbstractLevel read FLevel; |
| 554 |
|
| 555 |
{ Load scene from file, doing common tasks. |
| 556 |
@unorderedList( |
| 557 |
@item optionally create triangle octree |
| 558 |
@item(call PrepareResources, with prRenderSelf, prBoundingBox, prShadowVolume |
| 559 |
(if shadow volumes possible at all in this OpenGL context),) |
| 560 |
@item Free texture data, since they will not be needed anymore |
| 561 |
) |
| 562 |
@groupBegin } |
| 563 |
function LoadLevelScene(const Url: String; |
| 564 |
const PrepareForCollisions: boolean; |
| 565 |
const SceneClass: TCastleSceneClass): TCastleScene; overload; deprecated 'create and prepare TCastleScene instance directly'; |
| 566 |
function LoadLevelScene(const Url: String; |
| 567 |
const PrepareForCollisions: boolean): TCastleScene; overload; deprecated 'create and prepare TCastleScene instance directly'; |
| 568 |
{ @groupEnd } |
| 569 |
|
| 570 |
{ Handle a placeholder named in external modeler. |
| 571 |
Return @true if this is indeed a recognized placeholder name, |
| 572 |
and it was handled and relevant shape should be removed from level |
| 573 |
geometry (to not be rendered). } |
| 574 |
function Placeholder(const Shape: TShape; const PlaceholderName: string): boolean; virtual; |
| 575 |
|
| 576 |
{ Called after all placeholders have been processed, |
| 577 |
that is after @link(TLevel.Load) placed initial creatures, |
| 578 |
items and other stuff on the level. |
| 579 |
Override it to do anything you want. } |
| 580 |
procedure PlaceholdersEnd; virtual; |
| 581 |
public |
| 582 |
{ Create new level instance. Called before resources (creatures and items) |
| 583 |
are initialized (override PlaceholdersEnd if you need to do something |
| 584 |
after creatures and items are added). |
| 585 |
You can modify MainScene contents here. |
| 586 |
|
| 587 |
@param(Level |
| 588 |
|
| 589 |
Instance of TLevel, in particular with the root of level transformation |
| 590 |
in Level.RootTransform. |
| 591 |
|
| 592 |
The created TLevelLogic instance will be added to this Level.RootTransform, |
| 593 |
and it must stay there always. |
| 594 |
|
| 595 |
Passing it in constructor is necessary, as TLevelLogic descendants at |
| 596 |
construction may actually modify your world, and depend on it later.) |
| 597 |
|
| 598 |
@param(DOMElement |
| 599 |
|
| 600 |
An XML tree of level.xml file. You can read it |
| 601 |
however you want, to handle additional attributes in level.xml. |
| 602 |
You can use standard FPC DOM unit and classes, |
| 603 |
and add a handful of simple comfortable routines in CastleXmlUtils unit, |
| 604 |
for example you can use this to read a string attribute: |
| 605 |
|
| 606 |
@longCode(# |
| 607 |
MyAttribute := DOMElement.AttributeStringDef('my_attribute', 'default value'); |
| 608 |
MyRequiredAttribute := DOMElement.AttributeString('my_required_attribute'); |
| 609 |
#) |
| 610 |
) |
| 611 |
} |
| 612 |
constructor Create(const AOwner: TComponent; |
| 613 |
const ALevel: TAbstractLevel; |
| 614 |
const MainScene: TCastleScene; const DOMElement: TDOMElement); reintroduce; virtual; |
| 615 |
|
| 616 |
{ Called when new player starts new game on this level. |
| 617 |
This may be used to equip the player with some basic weapon / items. |
| 618 |
|
| 619 |
This is never called or used by the engine itself. |
| 620 |
This does nothing in the default TLevelLogic class implementation. |
| 621 |
|
| 622 |
Your particular game, where you can best decide when the player |
| 623 |
"starts a new game" and when the player merely "continues the previous |
| 624 |
game", may call it. And you may override this in your TLevelLogic descendants |
| 625 |
to equip the player. } |
| 626 |
procedure PrepareNewPlayer(NewPlayer: TPlayer); virtual; |
| 627 |
|
| 628 |
{ Time of the level, in seconds. Time 0 when level is created. |
| 629 |
This is updated in our @link(Update). } |
| 630 |
property Time: TFloatTime read FTime; |
| 631 |
|
| 632 |
procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override; |
| 633 |
end; |
| 634 |
|
| 635 |
TLevelLogicClasses = class({$ifdef FPC}specialize{$endif} TDictionary<string, TLevelLogicClass>) |
| 636 |
strict private |
| 637 |
function GetItems(const AKey: string): TLevelLogicClass; |
| 638 |
procedure SetItems(const AKey: string; const AValue: TLevelLogicClass); |
| 639 |
public |
| 640 |
{ Access dictionary items. |
| 641 |
Setting this is allowed regardless if the key previously existed or not, |
| 642 |
in other words: setting this does AddOrSetValue, contrary to the ancestor TDictionary |
| 643 |
that only allows setting when the key already exists. } |
| 644 |
property Items [const AKey: string]: TLevelLogicClass read GetItems write SetItems; default; |
| 645 |
end; |
| 646 |
|
| 647 |
function LevelLogicClasses: TLevelLogicClasses; |
| 648 |
|
| 649 |
{ All known levels. You can use this to show a list of available levels to user. |
| 650 |
You can also search it and use @link(TLevel.Load) to load |
| 651 |
a given TLevelInfo instance. } |
| 652 |
function Levels: TLevelInfoList; |
| 653 |
|
| 654 |
implementation |
| 655 |
|
| 656 |
uses SysUtils, Generics.Defaults, Math, |
| 657 |
CastleGLUtils, CastleFilesUtils, CastleStringUtils, |
| 658 |
CastleGLImages, CastleUIControls, XMLRead, CastleXmlUtils, CastleLog, |
| 659 |
X3DCameraUtils, CastleGLVersion, CastleUriUtils, CastleDownload, CastleThirdPersonNavigation; |
| 660 |
|
| 661 |
{ globals -------------------------------------------------------------------- } |
| 662 |
|
| 663 |
var |
| 664 |
FLevelLogicClasses: TLevelLogicClasses; |
| 665 |
|
| 666 |
function LevelLogicClasses: TLevelLogicClasses; |
| 667 |
begin |
| 668 |
if FLevelLogicClasses = nil then |
| 669 |
begin |
| 670 |
FLevelLogicClasses := TLevelLogicClasses.Create; |
| 671 |
FLevelLogicClasses['Level'] := TLevelLogic; |
| 672 |
end; |
| 673 |
Result := FLevelLogicClasses; |
| 674 |
end; |
| 675 |
|
| 676 |
var |
| 677 |
{ Created in initialization of this unit, destroyed in finalization |
| 678 |
(or when the last TLevel referring to TLevelInfo is destroyed). |
| 679 |
Owns it's Items. } |
| 680 |
FLevels: TLevelInfoList; |
| 681 |
|
| 682 |
function Levels: TLevelInfoList; |
| 683 |
begin |
| 684 |
Result := FLevels; |
| 685 |
end; |
| 686 |
|
| 687 |
{ TLevelInternalLogic -------------------------------------------------------- } |
| 688 |
|
| 689 |
procedure TLevel.TLevelInternalLogic.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); |
| 690 |
begin |
| 691 |
inherited; |
| 692 |
Level.Update(SecondsPassed); |
| 693 |
end; |
| 694 |
|
| 695 |
{ TLevel ---------------------------------------------------------- } |
| 696 |
|
| 697 |
constructor TLevel.Create(AOwner: TComponent); |
| 698 |
begin |
| 699 |
inherited; |
| 700 |
FWater := TBox3D.Empty; |
| 701 |
FInternalLogic := TLevelInternalLogic.Create(Self); |
| 702 |
FInternalLogic.Level := Self; |
| 703 |
end; |
| 704 |
|
| 705 |
destructor TLevel.Destroy; |
| 706 |
begin |
| 707 |
if Info <> nil then |
| 708 |
begin |
| 709 |
if (Info.LevelResources <> nil) and |
| 710 |
{ check LevelResourcesPrepared, to avoid calling |
| 711 |
Info.LevelResources.Release when Info.LevelResources.Prepare |
| 712 |
was not called (which may happen if there was an exception if LoadCore |
| 713 |
at MainScene.Load(SceneUrl). } |
| 714 |
LevelResourcesPrepared and |
| 715 |
{ check "Resources <> nil" is a hack to avoid calling Release |
| 716 |
on T3DResource when all T3DResource were already freed in CastleResources |
| 717 |
unit finalization. |
| 718 |
Testcase: darkest_before_dawn. |
| 719 |
|
| 720 |
TODO: This is not a general solution -- it would be better to implement in T3DResourceList |
| 721 |
a way to observe freeing of T3DResource, maybe even make T3DResource a TComponent |
| 722 |
and then make T3DResourceList as TComponentList. T3DResourceList should automatically |
| 723 |
remove items freed elsewhere. } |
| 724 |
(Resources <> nil) then |
| 725 |
Info.LevelResources.Release; |
| 726 |
|
| 727 |
Dec(FLevels.References); |
| 728 |
if FLevels.References = 0 then |
| 729 |
FreeAndNil(FLevels); |
| 730 |
end; |
| 731 |
|
| 732 |
{ unregister free notification from this } |
| 733 |
Player := nil; |
| 734 |
|
| 735 |
FreeAndNil(FSectors); |
| 736 |
FreeAndNil(Waypoints); |
| 737 |
FreeAndNil(FInternalLogic); |
| 738 |
FreeAndNil(FFreeAtUnload); // free stuff owned by FFreeAtUnload now |
| 739 |
|
| 740 |
inherited; |
| 741 |
end; |
| 742 |
|
| 743 |
function TLevel.FreeAtUnload: TComponent; |
| 744 |
begin |
| 745 |
if FFreeAtUnload = nil then |
| 746 |
FFreeAtUnload := TComponent.Create(nil); |
| 747 |
Result := FFreeAtUnload; |
| 748 |
end; |
| 749 |
|
| 750 |
function TLevel.GetPlayer: TCastleTransform; |
| 751 |
begin |
| 752 |
Result := FPlayer; |
| 753 |
end; |
| 754 |
|
| 755 |
function TLevel.GetSectors: TSectorList; |
| 756 |
begin |
| 757 |
Result := FSectors; |
| 758 |
end; |
| 759 |
|
| 760 |
function TLevel.RootTransform: TCastleRootTransform; |
| 761 |
begin |
| 762 |
Result := Viewport.Items; |
| 763 |
end; |
| 764 |
|
| 765 |
function TLevel.CreaturesRoot: TCastleTransform; |
| 766 |
begin |
| 767 |
Result := FCreaturesRoot; |
| 768 |
end; |
| 769 |
|
| 770 |
function TLevel.ItemsRoot: TCastleTransform; |
| 771 |
begin |
| 772 |
Result := FItemsRoot; |
| 773 |
end; |
| 774 |
|
| 775 |
function TLevel.PrepareParams: TPrepareParams; |
| 776 |
begin |
| 777 |
{$warnings off} // using deprecated in deprecated |
| 778 |
Result := Viewport.PrepareParams; |
| 779 |
{$warnings on} |
| 780 |
end; |
| 781 |
|
| 782 |
function TLevel.Placeholder(Shape: TShape; PlaceholderName: string): boolean; |
| 783 |
const |
| 784 |
{ Prefix of all placeholders that we seek on 3D models. } |
| 785 |
PlaceholderPrefix = 'Cas'; |
| 786 |
ResourcePrefix = PlaceholderPrefix + 'Res'; |
| 787 |
MoveLimitName = PlaceholderPrefix + 'MoveLimit'; |
| 788 |
WaterName = PlaceholderPrefix + 'Water'; |
| 789 |
SectorPrefix = PlaceholderPrefix + 'Sector'; |
| 790 |
WaypointPrefix = PlaceholderPrefix + 'Waypoint'; |
| 791 |
|
| 792 |
procedure PlaceholderResource(Shape: TShape; PlaceholderName: string); |
| 793 |
var |
| 794 |
ResourceName: string; |
| 795 |
ResourceNumberPresent: boolean; |
| 796 |
Resource: T3DResource; |
| 797 |
Box: TBox3D; |
| 798 |
Position, Direction: TVector3; |
| 799 |
IgnoredBegin, NumberBegin: Integer; |
| 800 |
ResourceNumber: Int64; |
| 801 |
begin |
| 802 |
{ PlaceholderName is now <resource_name>[<resource_number>][_<ignored>][.<ignored>] } |
| 803 |
|
| 804 |
{ cut off optional [_<ignored>] suffix } |
| 805 |
IgnoredBegin := Pos('_', PlaceholderName); |
| 806 |
if IgnoredBegin <> 0 then |
| 807 |
PlaceholderName := Copy(PlaceholderName, 1, IgnoredBegin - 1); |
| 808 |
IgnoredBegin := Pos('.', PlaceholderName); |
| 809 |
if IgnoredBegin <> 0 then |
| 810 |
PlaceholderName := Copy(PlaceholderName, 1, IgnoredBegin - 1); |
| 811 |
|
| 812 |
{ calculate ResourceName, ResourceNumber, ResourceNumberPresent } |
| 813 |
NumberBegin := CharsPos(['0'..'9'], PlaceholderName); |
| 814 |
ResourceNumberPresent := NumberBegin <> 0; |
| 815 |
if ResourceNumberPresent then |
| 816 |
begin |
| 817 |
ResourceName := Copy(PlaceholderName, 1, NumberBegin - 1); |
| 818 |
ResourceNumber := StrToInt(SEnding(PlaceholderName, NumberBegin)); |
| 819 |
end else |
| 820 |
begin |
| 821 |
ResourceName := PlaceholderName; |
| 822 |
ResourceNumber := 0; |
| 823 |
end; |
| 824 |
|
| 825 |
Resource := Resources.FindName(ResourceName); |
| 826 |
if not Resource.Prepared then |
| 827 |
WritelnWarning('Resource', 'Resource "%s" is initially present on the level, but was not prepared yet --- which probably means you did not add it to <resources> inside level level.xml file. This causes loading on-demand, which is less comfortable for player.', |
| 828 |
[Resource.Name]); |
| 829 |
|
| 830 |
Box := Shape.BoundingBox; |
| 831 |
Position := Box.Center; |
| 832 |
Position.Data[Items.GravityCoordinate] := Box.Data[0].Data[Items.GravityCoordinate]; |
| 833 |
|
| 834 |
Direction := Info.PlaceholderReferenceDirection; |
| 835 |
Direction := Shape.State.Transformation.Transform.MultDirection(Direction); |
| 836 |
|
| 837 |
Resource.InstantiatePlaceholder(Self, Position, Direction, |
| 838 |
ResourceNumberPresent, ResourceNumber); |
| 839 |
end; |
| 840 |
|
| 841 |
{ Shapes placed under the name CasWaypoint[_<ignored>] |
| 842 |
are removed from the Scene, and are added as new waypoint. |
| 843 |
Waypoint's Position is set to the middle point of shape's bounding box. } |
| 844 |
procedure PlaceholderWaypoint(Shape: TShape); |
| 845 |
var |
| 846 |
Waypoint: TWaypoint; |
| 847 |
begin |
| 848 |
Waypoint := TWaypoint.Create; |
| 849 |
Waypoint.Box := Shape.BoundingBox; |
| 850 |
Waypoint.Position := Waypoint.Box.Center; |
| 851 |
Waypoints.Add(Waypoint); |
| 852 |
|
| 853 |
{ Tests: |
| 854 |
Writeln('Waypoint ', Waypoints.Count - 1, ': at position ', |
| 855 |
Waypoint.Position.ToString);} |
| 856 |
end; |
| 857 |
|
| 858 |
{ Shapes placed under the name CasSector<index>[_<ignored>] |
| 859 |
are removed from the Scene, and are added to sector <index> BoundingBoxes. |
| 860 |
|
| 861 |
Count of the Sectors list is enlarged, if necessary, |
| 862 |
to include all sectors indicated in the Scene. } |
| 863 |
procedure PlaceholderSector(Shape: TShape; const SectorNodeName: string); |
| 864 |
var |
| 865 |
IgnoredBegin, SectorIndex: Integer; |
| 866 |
begin |
| 867 |
{ Calculate SectorIndex } |
| 868 |
IgnoredBegin := Pos('_', SectorNodeName); |
| 869 |
if IgnoredBegin = 0 then |
| 870 |
SectorIndex := StrToInt(SectorNodeName) else |
| 871 |
SectorIndex := StrToInt(Copy(SectorNodeName, 1, IgnoredBegin - 1)); |
| 872 |
|
| 873 |
Sectors.Count := Max(Sectors.Count, SectorIndex + 1); |
| 874 |
if Sectors[SectorIndex] = nil then |
| 875 |
Sectors[SectorIndex] := TSector.Create; |
| 876 |
|
| 877 |
Sectors[SectorIndex].Boxes.Add(Shape.BoundingBox); |
| 878 |
|
| 879 |
{ Tests: |
| 880 |
Writeln('Sector ', SectorIndex, ': added box ', |
| 881 |
SectorBoundingBox.ToNiceStr); } |
| 882 |
end; |
| 883 |
|
| 884 |
begin |
| 885 |
Result := true; |
| 886 |
if IsPrefix(ResourcePrefix, PlaceholderName) then |
| 887 |
PlaceholderResource(Shape, SEnding(PlaceholderName, Length(ResourcePrefix) + 1)) else |
| 888 |
if PlaceholderName = MoveLimitName then |
| 889 |
Items.MoveLimit := Shape.BoundingBox else |
| 890 |
if PlaceholderName = WaterName then |
| 891 |
Water := Shape.BoundingBox else |
| 892 |
if IsPrefix(SectorPrefix, PlaceholderName) then |
| 893 |
PlaceholderSector(Shape, SEnding(PlaceholderName, Length(SectorPrefix) + 1)) else |
| 894 |
if IsPrefix(WaypointPrefix, PlaceholderName) then |
| 895 |
PlaceholderWaypoint(Shape) else |
| 896 |
Result := Logic.Placeholder(Shape, PlaceholderName); |
| 897 |
end; |
| 898 |
|
| 899 |
function TLevel.UnloadCore: T3DResourceList; |
| 900 |
begin |
| 901 |
Items.ClearExceptCameras; |
| 902 |
|
| 903 |
{ free stuff like creatures, items, level logic. |
| 904 |
Note that things not owned by FreeAtUnload, like usual Player and FInternalLogic, |
| 905 |
remain untouched. } |
| 906 |
FreeAndNil(FFreeAtUnload); |
| 907 |
|
| 908 |
{ We freed FLogic etc. above, since they are always owned by FFreeAtUnload. |
| 909 |
To be safe, set them to nil. } |
| 910 |
FLogic := nil; |
| 911 |
FCreaturesRoot := nil; |
| 912 |
FItemsRoot := nil; |
| 913 |
|
| 914 |
{ save PreviousResources, before Info is overridden with new level. |
| 915 |
This allows us to keep PreviousResources while new resources are required, |
| 916 |
and this means that resources already loaded for previous level |
| 917 |
don't need to be reloaded for new. } |
| 918 |
Result := T3DResourceList.Create(false); |
| 919 |
if Info <> nil then |
| 920 |
begin |
| 921 |
Result.Clear; |
| 922 |
Result.AddRange(Info.LevelResources); |
| 923 |
Dec(Levels.References); |
| 924 |
FInfo := nil; |
| 925 |
end; |
| 926 |
end; |
| 927 |
|
| 928 |
procedure TLevel.Unload; |
| 929 |
var |
| 930 |
PreviousResources: T3DResourceList; |
| 931 |
begin |
| 932 |
PreviousResources := UnloadCore; |
| 933 |
PreviousResources.Release; |
| 934 |
FreeAndNil(PreviousResources); |
| 935 |
end; |
| 936 |
|
| 937 |
function TLevel.Items: TCastleRootTransform; |
| 938 |
begin |
| 939 |
Result := Viewport.Items; |
| 940 |
end; |
| 941 |
|
| 942 |
procedure TLevel.LoadCore(const AInfo: TLevelInfo); |
| 943 |
var |
| 944 |
{ Sometimes it's not comfortable |
| 945 |
to remove the items while traversing --- so we will instead |
| 946 |
put them on this list. |
| 947 |
|
| 948 |
Be careful: never add here two nodes such that one may be parent |
| 949 |
of another, otherwise freeing one could free the other one too |
| 950 |
early. } |
| 951 |
ItemsToRemove: TX3DNodeList; |
| 952 |
|
| 953 |
procedure TraverseForPlaceholders(Shape: TShape); |
| 954 |
var |
| 955 |
PlaceholderName: string; |
| 956 |
begin |
| 957 |
PlaceholderName := Info.PlaceholderName(Shape); |
| 958 |
if (PlaceholderName <> '') and Placeholder(Shape, PlaceholderName) then |
| 959 |
begin |
| 960 |
{ Don't remove OriginalGeometry node now --- will be removed later. |
| 961 |
This avoids problems with removing nodes while traversing. } |
| 962 |
if ItemsToRemove.IndexOf(Shape.OriginalGeometry) = -1 then |
| 963 |
ItemsToRemove.Add(Shape.OriginalGeometry); |
| 964 |
end; |
| 965 |
end; |
| 966 |
|
| 967 |
procedure RemoveItemsToRemove; |
| 968 |
var |
| 969 |
I: Integer; |
| 970 |
begin |
| 971 |
{$warnings off} // using deprecated in deprecated unit |
| 972 |
Items.MainScene.BeforeNodesFree; |
| 973 |
for I := 0 to ItemsToRemove.Count - 1 do |
| 974 |
ItemsToRemove.Items[I].FreeRemovingFromAllParents; |
| 975 |
Items.MainScene.ChangedAll; |
| 976 |
{$warnings on} |
| 977 |
end; |
| 978 |
|
| 979 |
{ After placeholders are processed, finish some stuff. } |
| 980 |
procedure PlaceholdersEnd; |
| 981 |
var |
| 982 |
NewMoveLimit: TBox3D; |
| 983 |
begin |
| 984 |
if Items.MoveLimit.IsEmpty then |
| 985 |
begin |
| 986 |
{ Set MoveLimit to Items.MainScene.BoundingBox, and make maximum up larger. } |
| 987 |
{$warnings off} // using deprecated in deprecated unit |
| 988 |
NewMoveLimit := Items.MainScene.BoundingBox; |
| 989 |
{$warnings on} |
| 990 |
NewMoveLimit.Data[1].Data[Items.GravityCoordinate] := |
| 991 |
NewMoveLimit.Data[1].Data[Items.GravityCoordinate] + |
| 992 |
4 * (NewMoveLimit.Data[1].Data[Items.GravityCoordinate] - |
| 993 |
NewMoveLimit.Data[0].Data[Items.GravityCoordinate]); |
| 994 |
Items.MoveLimit := NewMoveLimit; |
| 995 |
end; |
| 996 |
|
| 997 |
Sectors.LinkToWaypoints(Waypoints); |
| 998 |
|
| 999 |
Logic.PlaceholdersEnd; |
| 1000 |
end; |
| 1001 |
|
| 1002 |
var |
| 1003 |
Options: TPrepareResourcesOptions; |
| 1004 |
ShapeList: TShapeList; |
| 1005 |
Shape: TShape; |
| 1006 |
PreviousResources: T3DResourceList; |
| 1007 |
begin |
| 1008 |
PreviousResources := UnloadCore; |
| 1009 |
|
| 1010 |
FInfo := AInfo; |
| 1011 |
Inc(Levels.References); |
| 1012 |
Info.Played := true; |
| 1013 |
LevelResourcesPrepared := false; |
| 1014 |
|
| 1015 |
Progress.Init(1, 'Loading level "' + Info.Title + '"'); |
| 1016 |
try |
| 1017 |
{ Disconnect previous Viewport.Navigation. |
| 1018 |
Otherwise, it would be updated by Items.MainScene loading binding new |
| 1019 |
NavigationInfo (with it's speed) and Viewpoint. |
| 1020 |
We prefer to do it ourselves in InitializeCamera. } |
| 1021 |
{$warnings off} // using deprecated in deprecated unit |
| 1022 |
Viewport.Navigation := nil; |
| 1023 |
|
| 1024 |
Items.MainScene := TCastleScene.Create(Self); |
| 1025 |
Inc(Items.MainScene.InternalDirty); |
| 1026 |
Items.MainScene.Load(Info.SceneUrl); |
| 1027 |
|
| 1028 |
{ Scene must be the first one on Items, this way Items.MoveCollision will |
| 1029 |
use Scene for wall-sliding (see TCastleTransform.LocalMoveCollision implementation). } |
| 1030 |
Items.Insert(0, Items.MainScene); |
| 1031 |
{$warnings on} |
| 1032 |
|
| 1033 |
InitializeCamera; |
| 1034 |
|
| 1035 |
Progress.Step; |
| 1036 |
finally |
| 1037 |
Progress.Fini; |
| 1038 |
end; |
| 1039 |
|
| 1040 |
{ load new resources (and release old unused). This must be done after |
| 1041 |
InitializeCamera (because it uses GravityUp), which in turn must |
| 1042 |
be after loading Items.MainScene (because initial camera looks at Items.MainScene |
| 1043 |
contents). |
| 1044 |
It will show it's own progress bar. } |
| 1045 |
{$warnings off} // using deprecated in deprecated |
| 1046 |
Info.LevelResources.Prepare(Viewport.PrepareParams); |
| 1047 |
{$warnings on} |
| 1048 |
LevelResourcesPrepared := true; |
| 1049 |
PreviousResources.Release; |
| 1050 |
FreeAndNil(PreviousResources); |
| 1051 |
|
| 1052 |
Progress.Init(1, 'Loading level "' + Info.Title + '"'); |
| 1053 |
try |
| 1054 |
{ add Player to Items. |
| 1055 |
|
| 1056 |
It is necessary to keep Player as 1st item: |
| 1057 |
Testcase darkest-before-the-dawn: |
| 1058 |
- Doing Info.LogicClass.Create creates a number of TCastleLinearMoving |
| 1059 |
and adds them to Items. |
| 1060 |
|
| 1061 |
- If the TCastleLinearMoving are *before* Player on Items, |
| 1062 |
things are broken when player is moved |
| 1063 |
by TCastleLinearMoving (standing on elevator): |
| 1064 |
|
| 1065 |
TCastleLinearMoving.Update changes Player transformation, |
| 1066 |
causing TPlayer.ChangedTransform |
| 1067 |
causing TPlayer.SynchronizeToNavigation. |
| 1068 |
|
| 1069 |
But in effect any changes possibly done by user input in the same frame |
| 1070 |
(e.g. moving around) are lost. |
| 1071 |
When we reach TPlayer.Update, it calls SynchronizeFromNavigation |
| 1072 |
that does nothing, as Navigation and Player transformation |
| 1073 |
are for sure synchronized now. |
| 1074 |
|
| 1075 |
- OTOH, when Player is *before* everything else: |
| 1076 |
|
| 1077 |
TPlayer.Update calls SynchronizeFromNavigation which can apply |
| 1078 |
to Player transformation changes done to Viewport.Camera |
| 1079 |
(done by TCastleWalkNavigation receiving inputs). |
| 1080 |
|
| 1081 |
IOW, TPlayer now requires that you let SynchronizeFromNavigation to happen |
| 1082 |
in each frame, before any SynchronizeToNavigation. |
| 1083 |
|
| 1084 |
Do not add Player if was already added. |
| 1085 |
This happens if UseThirdPerson was used, |
| 1086 |
then ThirdPersonNavigation.AvatarHierarchy is already added to world, |
| 1087 |
and it is equal to Player. |
| 1088 |
} |
| 1089 |
if (Player <> nil) and (Player.World = nil) then |
| 1090 |
Items.Add(Player); |
| 1091 |
|
| 1092 |
{ add FInternalLogic to Items } |
| 1093 |
Items.Add(FInternalLogic); |
| 1094 |
|
| 1095 |
{ add CreaturesRoot, ItemsRoot to Items } |
| 1096 |
FCreaturesRoot := TCastleTransform.Create(FreeAtUnload); |
| 1097 |
Items.Add(FCreaturesRoot); |
| 1098 |
FItemsRoot := TCastleTransform.Create(FreeAtUnload); |
| 1099 |
Items.Add(FItemsRoot); |
| 1100 |
|
| 1101 |
{ add FLogic (new Info.LogicClass instance) } |
| 1102 |
{$warnings off} // using deprecated in deprecated unit |
| 1103 |
FLogic := Info.LogicClass.Create(FreeAtUnload, Self, Items.MainScene, Info.Element); |
| 1104 |
{$warnings on} |
| 1105 |
Items.AddBehavior(Logic); |
| 1106 |
|
| 1107 |
{ We will calculate new Sectors and Waypoints and other stuff |
| 1108 |
based on placeholders. Initialize them now to be empty. } |
| 1109 |
FreeAndNil(FSectors); |
| 1110 |
FreeAndNil(Waypoints); |
| 1111 |
FSectors := TSectorList.Create(true); |
| 1112 |
Waypoints := TWaypointList.Create(true); |
| 1113 |
Items.MoveLimit := TBox3D.Empty; |
| 1114 |
Water := TBox3D.Empty; |
| 1115 |
|
| 1116 |
ItemsToRemove := TX3DNodeList.Create(false); |
| 1117 |
try |
| 1118 |
{$warnings off} // using deprecated in deprecated unit |
| 1119 |
ShapeList := Items.MainScene.Shapes.TraverseList({ OnlyActive } true); |
| 1120 |
{$warnings on} |
| 1121 |
for Shape in ShapeList do |
| 1122 |
TraverseForPlaceholders(Shape); |
| 1123 |
RemoveItemsToRemove; |
| 1124 |
finally ItemsToRemove.Free end; |
| 1125 |
|
| 1126 |
PlaceholdersEnd; |
| 1127 |
|
| 1128 |
{ calculate Options for PrepareResources } |
| 1129 |
Options := [prRenderSelf, prBackground, prBoundingBox]; |
| 1130 |
if (GLFeatures <> nil) and GLFeatures.ShadowVolumesPossible then |
| 1131 |
Include(Options, prShadowVolume); |
| 1132 |
|
| 1133 |
{$warnings off} // using deprecated in deprecated unit |
| 1134 |
Viewport.PrepareResources(Items.MainScene, Options); |
| 1135 |
Items.MainScene.FreeResources([frTextureDataInNodes]); |
| 1136 |
{$warnings on} |
| 1137 |
|
| 1138 |
Progress.Step; |
| 1139 |
finally |
| 1140 |
Progress.Fini; |
| 1141 |
end; |
| 1142 |
|
| 1143 |
{$warnings off} // using deprecated in deprecated unit |
| 1144 |
Items.MainScene.PreciseCollisions := true; |
| 1145 |
Items.MainScene.PrepareResources([prSpatial], Viewport.PrepareParams); |
| 1146 |
{$warnings on} |
| 1147 |
|
| 1148 |
if (Player <> nil) then |
| 1149 |
Player.LevelChanged; |
| 1150 |
|
| 1151 |
SoundEngine.LoopingChannel[0].Sound := Info.MusicSound; |
| 1152 |
{$warnings off} // using deprecated in deprecated unit |
| 1153 |
SoundEngine.PrepareResources; |
| 1154 |
|
| 1155 |
Items.MainScene.ProcessEvents := true; |
| 1156 |
|
| 1157 |
Dec(Items.MainScene.InternalDirty); |
| 1158 |
{$warnings on} |
| 1159 |
end; |
| 1160 |
|
| 1161 |
procedure TLevel.Load(const AInfo: TLevelInfo); |
| 1162 |
var |
| 1163 |
SavedImage: TObject; |
| 1164 |
SavedBarYPosition: Single; |
| 1165 |
SavedOwnsImage: boolean; |
| 1166 |
begin |
| 1167 |
SavedOwnsImage := Progress.UserInterface.OwnsImage; |
| 1168 |
SavedImage := Progress.UserInterface.Image; |
| 1169 |
SavedBarYPosition := Progress.UserInterface.BarYPosition; |
| 1170 |
try |
| 1171 |
Progress.UserInterface.OwnsImage := false; // never free Image at next assignment |
| 1172 |
Progress.UserInterface.Image := AInfo.LoadingImage; |
| 1173 |
Progress.UserInterface.BarYPosition := AInfo.LoadingBarYPosition; |
| 1174 |
LoadCore(AInfo); |
| 1175 |
finally |
| 1176 |
Progress.UserInterface.Image := nil; // unassign AInfo.LoadingImage, while OwnsImage = false |
| 1177 |
Progress.UserInterface.OwnsImage := SavedOwnsImage; |
| 1178 |
Progress.UserInterface.Image := SavedImage; |
| 1179 |
Progress.UserInterface.BarYPosition := SavedBarYPosition; |
| 1180 |
end; |
| 1181 |
end; |
| 1182 |
|
| 1183 |
procedure TLevel.Load(const LevelName: string); |
| 1184 |
begin |
| 1185 |
Load(Levels.FindName(LevelName)); |
| 1186 |
end; |
| 1187 |
|
| 1188 |
procedure TLevel.Update(const SecondsPassed: Single); |
| 1189 |
|
| 1190 |
procedure UpdatePlayerSwimming; |
| 1191 |
begin |
| 1192 |
if Player = nil then |
| 1193 |
begin |
| 1194 |
FPlayerSwimming := psNo; |
| 1195 |
Exit; |
| 1196 |
end; |
| 1197 |
|
| 1198 |
if Water.Contains(Player.Translation) then |
| 1199 |
FPlayerSwimming := psUnderWater |
| 1200 |
else |
| 1201 |
{ TODO: swimming on water surface is not ready for 3rd-person navigation. } |
| 1202 |
if (not Player.UseThirdPerson) and |
| 1203 |
Water.Contains(Player.Translation - Viewport.Camera.GravityUp * Player.WalkNavigation.PreferredHeight) then |
| 1204 |
FPlayerSwimming := psAboveWater |
| 1205 |
else |
| 1206 |
FPlayerSwimming := psNo; |
| 1207 |
|
| 1208 |
Player.Swimming := FPlayerSwimming; |
| 1209 |
end; |
| 1210 |
|
| 1211 |
procedure UpdateSickProjection; |
| 1212 |
var |
| 1213 |
DistortFov, DistortAspect: Single; |
| 1214 |
S, C: Extended; |
| 1215 |
begin |
| 1216 |
DistortFov := 1; |
| 1217 |
DistortAspect := 1; |
| 1218 |
if FPlayerSwimming = psUnderWater then |
| 1219 |
begin |
| 1220 |
SickProjectionTime := SickProjectionTime + SecondsPassed * Items.TimeScale; |
| 1221 |
SinCos(SickProjectionTime * Player.SickProjectionSpeed, S, C); |
| 1222 |
DistortFov := DistortFov + (C * 0.03); |
| 1223 |
DistortAspect := DistortAspect + (S * 0.03); |
| 1224 |
end; |
| 1225 |
Viewport.InternalDistortFieldOfViewY := DistortFov; |
| 1226 |
Viewport.InternalDistortViewAspect := DistortAspect; |
| 1227 |
end; |
| 1228 |
|
| 1229 |
begin |
| 1230 |
UpdatePlayerSwimming; |
| 1231 |
UpdateSickProjection; |
| 1232 |
end; |
| 1233 |
|
| 1234 |
procedure TLevel.SetPlayer(const Value: TPlayer); |
| 1235 |
begin |
| 1236 |
if FPlayer <> Value then |
| 1237 |
begin |
| 1238 |
if FPlayer <> nil then |
| 1239 |
begin |
| 1240 |
FPlayer.RemoveFreeNotification(Self); |
| 1241 |
Items.Remove(FPlayer); |
| 1242 |
end; |
| 1243 |
FPlayer := Value; |
| 1244 |
if FPlayer <> nil then |
| 1245 |
begin |
| 1246 |
FPlayer.FreeNotification(Self); |
| 1247 |
FPlayer.InternalLevel := Self; |
| 1248 |
end; |
| 1249 |
Viewport.AvoidNavigationCollisions := Value; |
| 1250 |
|
| 1251 |
{ Reinitialize camera and navigation only when level was loaded. } |
| 1252 |
if FInfo <> nil then |
| 1253 |
begin |
| 1254 |
InitializeCamera; |
| 1255 |
if FPlayer <> nil then |
| 1256 |
begin |
| 1257 |
{ Add Player to Items, |
| 1258 |
as the second item (see LoadCore for explanation why), |
| 1259 |
making sure it's not already there (because InitializeCamera |
| 1260 |
may have already added it when UseThirdPerson). } |
| 1261 |
if FPlayer.World = nil then |
| 1262 |
begin |
| 1263 |
Items.Insert(1, FPlayer); |
| 1264 |
FPlayer.LevelChanged; |
| 1265 |
end; |
| 1266 |
end; |
| 1267 |
end; |
| 1268 |
end; |
| 1269 |
end; |
| 1270 |
|
| 1271 |
procedure TLevel.InitializeCamera; |
| 1272 |
var |
| 1273 |
InitialPosition: TVector3; |
| 1274 |
InitialDirection: TVector3; |
| 1275 |
InitialUp: TVector3; |
| 1276 |
GravityUp: TVector3; |
| 1277 |
Radius, PreferredHeight: Single; |
| 1278 |
ProjectionNear: Single; |
| 1279 |
NavigationNode: TNavigationInfoNode; |
| 1280 |
WalkNavigation: TCastleWalkNavigation; |
| 1281 |
ThirdPersonNavigation: TCastleThirdPersonNavigation; |
| 1282 |
begin |
| 1283 |
{$warnings off} // using deprecated in deprecated unit |
| 1284 |
if Items.MainScene.ViewpointStack.Top <> nil then |
| 1285 |
Items.MainScene.ViewpointStack.Top.GetView(InitialPosition, |
| 1286 |
InitialDirection, InitialUp, GravityUp) else |
| 1287 |
{$warnings on} |
| 1288 |
begin |
| 1289 |
InitialPosition := DefaultX3DCameraPosition[cvVrml2_X3d]; |
| 1290 |
InitialDirection := DefaultX3DCameraDirection; |
| 1291 |
InitialUp := DefaultX3DCameraUp; |
| 1292 |
GravityUp := DefaultX3DGravityUp; |
| 1293 |
end; |
| 1294 |
|
| 1295 |
{$warnings off} // using deprecated in deprecated unit |
| 1296 |
NavigationNode := Items.MainScene.NavigationInfoStack.Top; |
| 1297 |
{$warnings on} |
| 1298 |
|
| 1299 |
// calculate Radius |
| 1300 |
Radius := 0; |
| 1301 |
if (NavigationNode <> nil) and |
| 1302 |
(NavigationNode.FdAvatarSize.Count >= 1) then |
| 1303 |
Radius := NavigationNode.FdAvatarSize.Items[0]; |
| 1304 |
// If radius not specified, or invalid (<0), calculate it |
| 1305 |
{$warnings off} // using deprecated in deprecated unit |
| 1306 |
if Radius <= 0 then |
| 1307 |
Radius := DefaultCameraRadius; |
| 1308 |
{$warnings on} |
| 1309 |
Assert(Radius > 0, 'Navigation Radius must be > 0'); |
| 1310 |
|
| 1311 |
// calculate ProjectionNear |
| 1312 |
ProjectionNear := Radius * RadiusToProjectionNear; |
| 1313 |
Viewport.Camera.ProjectionNear := ProjectionNear; |
| 1314 |
|
| 1315 |
if (NavigationNode <> nil) and |
| 1316 |
(NavigationNode.FdAvatarSize.Count >= 2) then |
| 1317 |
PreferredHeight := NavigationNode.FdAvatarSize.Items[1] |
| 1318 |
else |
| 1319 |
PreferredHeight := Max(TCastleNavigation.DefaultPreferredHeight, Radius * RadiusToPreferredHeightMin); |
| 1320 |
CorrectPreferredHeight(PreferredHeight, Radius, |
| 1321 |
TCastleWalkNavigation.DefaultCrouchHeight, TCastleWalkNavigation.DefaultHeadBobbing); |
| 1322 |
|
| 1323 |
WalkNavigation := nil; |
| 1324 |
ThirdPersonNavigation := nil; |
| 1325 |
if Player <> nil then |
| 1326 |
begin |
| 1327 |
if Player.UseThirdPerson then |
| 1328 |
ThirdPersonNavigation := Player.ThirdPersonNavigation |
| 1329 |
else |
| 1330 |
WalkNavigation := Player.WalkNavigation; |
| 1331 |
end else |
| 1332 |
{ If you don't initialize Player (like for castle1 background level |
| 1333 |
or castle-view-level or lets_take_a_walk) then just create a camera. } |
| 1334 |
WalkNavigation := TCastleWalkNavigation.Create(Self); |
| 1335 |
|
| 1336 |
{ initialize some navigation settings of player } |
| 1337 |
if Player <> nil then |
| 1338 |
begin |
| 1339 |
Player.DefaultPreferredHeight := PreferredHeight; |
| 1340 |
if NavigationNode <> nil then |
| 1341 |
Player.DefaultMoveHorizontalSpeed := NavigationNode.FdSpeed.Value else |
| 1342 |
Player.DefaultMoveHorizontalSpeed := 1.0; |
| 1343 |
Player.DefaultMoveVerticalSpeed := 20; |
| 1344 |
end else |
| 1345 |
if WalkNavigation <> nil then |
| 1346 |
begin |
| 1347 |
{ if you use TCastlePlayer, then it will automatically update navigation |
| 1348 |
speed properties. But if not (when Player = nil), we have to set them |
| 1349 |
explicitly here. } |
| 1350 |
WalkNavigation.PreferredHeight := PreferredHeight; |
| 1351 |
if NavigationNode <> nil then |
| 1352 |
WalkNavigation.MoveHorizontalSpeed := NavigationNode.FdSpeed.Value else |
| 1353 |
WalkNavigation.MoveHorizontalSpeed := 1.0; |
| 1354 |
WalkNavigation.MoveVerticalSpeed := 20; |
| 1355 |
end; |
| 1356 |
|
| 1357 |
|
| 1358 |
// will be overridden by ThirdPersonNavigation.Init, possibly |
| 1359 |
{$warnings off} // using deprecated in deprecated unit |
| 1360 |
Viewport.Camera.Init(InitialPosition, InitialDirection, InitialUp, GravityUp); |
| 1361 |
{$warnings on} |
| 1362 |
|
| 1363 |
if WalkNavigation <> nil then |
| 1364 |
begin |
| 1365 |
WalkNavigation.PreferredHeight := PreferredHeight; |
| 1366 |
WalkNavigation.Radius := Radius; |
| 1367 |
WalkNavigation.CorrectPreferredHeight; |
| 1368 |
WalkNavigation.CancelFalling; |
| 1369 |
|
| 1370 |
{$warnings off} // using deprecated in deprecated unit |
| 1371 |
Viewport.Navigation := WalkNavigation; |
| 1372 |
{$warnings on} |
| 1373 |
end else |
| 1374 |
begin |
| 1375 |
{$warnings off} // using deprecated in deprecated unit |
| 1376 |
Viewport.Navigation := ThirdPersonNavigation; |
| 1377 |
{$warnings on} |
| 1378 |
|
| 1379 |
{ Use InitialXxx vectors to position avatar, camera will be derived from it. |
| 1380 |
Also add the avatar to Items (avatar needs to be part of hierarchy when |
| 1381 |
ThirdPersonNavigation.Init is called). } |
| 1382 |
if ThirdPersonNavigation.AvatarHierarchy <> nil then |
| 1383 |
begin |
| 1384 |
ThirdPersonNavigation.AvatarHierarchy.SetView(InitialPosition, InitialDirection, InitialUp); |
| 1385 |
|
| 1386 |
if (Player <> nil) and (ThirdPersonNavigation.AvatarHierarchy = Player) then |
| 1387 |
begin |
| 1388 |
Items.Insert(1, ThirdPersonNavigation.AvatarHierarchy); |
| 1389 |
Player.LevelChanged; |
| 1390 |
end else |
| 1391 |
Items.Add(ThirdPersonNavigation.AvatarHierarchy); |
| 1392 |
end else |
| 1393 |
if ThirdPersonNavigation.Avatar <> nil then |
| 1394 |
begin |
| 1395 |
ThirdPersonNavigation.Avatar.SetView(InitialPosition, InitialDirection, InitialUp); |
| 1396 |
Items.Add(ThirdPersonNavigation.Avatar); |
| 1397 |
end; |
| 1398 |
ThirdPersonNavigation.Init; |
| 1399 |
end; |
| 1400 |
end; |
| 1401 |
|
| 1402 |
procedure TLevel.Notification(AComponent: TComponent; Operation: TOperation); |
| 1403 |
begin |
| 1404 |
inherited; |
| 1405 |
if (Operation = opRemove) and (AComponent = FPlayer) then |
| 1406 |
Player := nil; |
| 1407 |
end; |
| 1408 |
|
| 1409 |
{ TGameSceneManager ---------------------------------------------------------- } |
| 1410 |
|
| 1411 |
{ TGameSceneManager is deprecated, just passes all the work |
| 1412 |
to internal TLevel instance. } |
| 1413 |
|
| 1414 |
constructor TGameSceneManager.Create(AOwner: TComponent); |
| 1415 |
begin |
| 1416 |
inherited; |
| 1417 |
FLevel := TLevel.Create(nil); |
| 1418 |
FLevel.Viewport := Self; |
| 1419 |
end; |
| 1420 |
|
| 1421 |
destructor TGameSceneManager.Destroy; |
| 1422 |
begin |
| 1423 |
FreeAndNil(FLevel); |
| 1424 |
inherited; |
| 1425 |
end; |
| 1426 |
|
| 1427 |
function TGameSceneManager.GetSectors: TSectorList; |
| 1428 |
begin |
| 1429 |
Result := FLevel.Sectors; |
| 1430 |
end; |
| 1431 |
|
| 1432 |
function TGameSceneManager.GetWater: TBox3D; |
| 1433 |
begin |
| 1434 |
Result := FLevel.Water; |
| 1435 |
end; |
| 1436 |
|
| 1437 |
procedure TGameSceneManager.SetWater(const Value: TBox3D); |
| 1438 |
begin |
| 1439 |
FLevel.Water := Value; |
| 1440 |
end; |
| 1441 |
|
| 1442 |
function TGameSceneManager.GetPlayer: TPlayer; |
| 1443 |
begin |
| 1444 |
Result := FLevel.Player; |
| 1445 |
end; |
| 1446 |
|
| 1447 |
procedure TGameSceneManager.SetPlayer(const Value: TPlayer); |
| 1448 |
begin |
| 1449 |
FLevel.Player := Value; |
| 1450 |
end; |
| 1451 |
|
| 1452 |
procedure TGameSceneManager.LoadLevel(const LevelName: string); |
| 1453 |
begin |
| 1454 |
FLevel.Load(LevelName); |
| 1455 |
end; |
| 1456 |
|
| 1457 |
procedure TGameSceneManager.LoadLevel(const AInfo: TLevelInfo); |
| 1458 |
begin |
| 1459 |
FLevel.Load(AInfo); |
| 1460 |
end; |
| 1461 |
|
| 1462 |
function TGameSceneManager.Logic: TLevelLogic; |
| 1463 |
begin |
| 1464 |
Result := FLevel.Logic; |
| 1465 |
end; |
| 1466 |
|
| 1467 |
function TGameSceneManager.Info: TLevelInfo; |
| 1468 |
begin |
| 1469 |
Result := FLevel.Info; |
| 1470 |
end; |
| 1471 |
|
| 1472 |
procedure TGameSceneManager.UnloadLevel; |
| 1473 |
begin |
| 1474 |
FLevel.Unload; |
| 1475 |
end; |
| 1476 |
|
| 1477 |
function TGameSceneManager.LevelProperties: TAbstractLevel; |
| 1478 |
begin |
| 1479 |
Result := FLevel; |
| 1480 |
end; |
| 1481 |
|
| 1482 |
{ TLevelLogic ---------------------------------------------------------------- } |
| 1483 |
|
| 1484 |
constructor TLevelLogic.Create(const AOwner: TComponent; |
| 1485 |
const ALevel: TAbstractLevel; |
| 1486 |
const MainScene: TCastleScene; const DOMElement: TDOMElement); |
| 1487 |
begin |
| 1488 |
inherited Create(AOwner); |
| 1489 |
FLevel := ALevel; |
| 1490 |
end; |
| 1491 |
|
| 1492 |
procedure TLevelLogic.PrepareNewPlayer(NewPlayer: TPlayer); |
| 1493 |
begin |
| 1494 |
{ Nothing to do in this class. } |
| 1495 |
end; |
| 1496 |
|
| 1497 |
function TLevelLogic.LoadLevelScene( |
| 1498 |
const Url: String; |
| 1499 |
const PrepareForCollisions: boolean; |
| 1500 |
const SceneClass: TCastleSceneClass): TCastleScene; |
| 1501 |
var |
| 1502 |
Options: TPrepareResourcesOptions; |
| 1503 |
begin |
| 1504 |
Result := SceneClass.Create(Self); |
| 1505 |
Result.Load(Url); |
| 1506 |
|
| 1507 |
{ calculate Options for PrepareResources } |
| 1508 |
Options := [prRenderSelf, prBoundingBox { always needed }]; |
| 1509 |
if (GLFeatures <> nil) and GLFeatures.ShadowVolumesPossible then |
| 1510 |
Include(Options, prShadowVolume); |
| 1511 |
|
| 1512 |
{$warnings off} // using deprecated in deprecated |
| 1513 |
Result.PrepareResources(Options, FLevel.PrepareParams); |
| 1514 |
{$warnings on} |
| 1515 |
|
| 1516 |
if PrepareForCollisions then |
| 1517 |
Result.PreciseCollisions := true; |
| 1518 |
|
| 1519 |
Result.FreeResources([frTextureDataInNodes]); |
| 1520 |
|
| 1521 |
Result.ProcessEvents := true; |
| 1522 |
end; |
| 1523 |
|
| 1524 |
function TLevelLogic.LoadLevelScene( |
| 1525 |
const Url: String; |
| 1526 |
const PrepareForCollisions: boolean): TCastleScene; |
| 1527 |
begin |
| 1528 |
{$warnings off} // using deprecated in deprecated |
| 1529 |
Result := LoadLevelScene(Url, PrepareForCollisions, TCastleScene); |
| 1530 |
{$warnings on} |
| 1531 |
end; |
| 1532 |
|
| 1533 |
procedure TLevelLogic.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); |
| 1534 |
begin |
| 1535 |
inherited; |
| 1536 |
FTime := FTime + SecondsPassed; |
| 1537 |
end; |
| 1538 |
|
| 1539 |
function TLevelLogic.Placeholder(const Shape: TShape; |
| 1540 |
const PlaceholderName: string): boolean; |
| 1541 |
begin |
| 1542 |
Result := false; |
| 1543 |
end; |
| 1544 |
|
| 1545 |
procedure TLevelLogic.PlaceholdersEnd; |
| 1546 |
begin |
| 1547 |
{ Nothing to do in this class. } |
| 1548 |
end; |
| 1549 |
|
| 1550 |
{ TLevelInfo ------------------------------------------------------------ } |
| 1551 |
|
| 1552 |
constructor TLevelInfo.Create; |
| 1553 |
begin |
| 1554 |
inherited; |
| 1555 |
LevelResources := T3DResourceList.Create(false); |
| 1556 |
end; |
| 1557 |
|
| 1558 |
destructor TLevelInfo.Destroy; |
| 1559 |
begin |
| 1560 |
FreeAndNil(Document); |
| 1561 |
FreeAndNil(LevelResources); |
| 1562 |
FreeAndNil(FLoadingImage); |
| 1563 |
inherited; |
| 1564 |
end; |
| 1565 |
|
| 1566 |
procedure TLevelInfo.LoadFromDocument; |
| 1567 |
|
| 1568 |
procedure MissingRequiredAttribute(const AttrName: string); |
| 1569 |
begin |
| 1570 |
raise Exception.CreateFmt( |
| 1571 |
'Missing required attribute "%s" of <level> element', [AttrName]); |
| 1572 |
end; |
| 1573 |
|
| 1574 |
{ Like DOMGetAttribute, but reads TLevelLogicClass value. } |
| 1575 |
function DOMGetLevelLogicClassAttribute(const Element: TDOMElement; |
| 1576 |
const AttrName: string; var Value: TLevelLogicClass): boolean; |
| 1577 |
var |
| 1578 |
ValueStr: string; |
| 1579 |
begin |
| 1580 |
Result := Element.AttributeString(AttrName, ValueStr); |
| 1581 |
if not LevelLogicClasses.TryGetValue(ValueStr, Value) then |
| 1582 |
raise Exception.CreateFmt('Unknown level type "%s"', [ValueStr]); |
| 1583 |
end; |
| 1584 |
|
| 1585 |
{ Add all resources with AlwaysPrepared = true to the LevelResources. } |
| 1586 |
procedure AddAlwaysPreparedResources; |
| 1587 |
var |
| 1588 |
I: Integer; |
| 1589 |
begin |
| 1590 |
for I := 0 to Resources.Count - 1 do |
| 1591 |
if Resources[I].AlwaysPrepared and |
| 1592 |
(LevelResources.IndexOf(Resources[I]) = -1) then |
| 1593 |
LevelResources.Add(Resources[I]); |
| 1594 |
end; |
| 1595 |
|
| 1596 |
const |
| 1597 |
DefaultPlaceholderReferenceDirection: TVector3 = (X: 1; Y: 0; Z: 0); |
| 1598 |
var |
| 1599 |
LoadingImageUrl: String; |
| 1600 |
SoundName: string; |
| 1601 |
PlaceholdersKey: string; |
| 1602 |
S: string; |
| 1603 |
begin |
| 1604 |
Element := Document.DocumentElement; |
| 1605 |
|
| 1606 |
if Element.TagName <> 'level' then |
| 1607 |
raise Exception.CreateFmt('Root node of level.xml file must be <level>, but is "%s", in "%s"', |
| 1608 |
[Element.TagName, DocumentBaseUrl]); |
| 1609 |
|
| 1610 |
{ Required attributes } |
| 1611 |
|
| 1612 |
if not Element.AttributeString('name', FName) then |
| 1613 |
MissingRequiredAttribute('name'); |
| 1614 |
|
| 1615 |
if not Element.AttributeString('scene', FSceneUrl) then |
| 1616 |
MissingRequiredAttribute('scene'); |
| 1617 |
SceneUrl := CombineURI(DocumentBaseUrl, SceneUrl); |
| 1618 |
|
| 1619 |
if not Element.AttributeString('title', FTitle) then |
| 1620 |
MissingRequiredAttribute('title'); |
| 1621 |
|
| 1622 |
{ Optional attributes } |
| 1623 |
|
| 1624 |
if not Element.AttributeInteger('number', FNumber) then |
| 1625 |
Number := 0; |
| 1626 |
|
| 1627 |
if not Element.AttributeBoolean('demo', FDemo) then |
| 1628 |
Demo := false; |
| 1629 |
|
| 1630 |
if not Element.AttributeString('title_hint', FTitleHint) then |
| 1631 |
TitleHint := ''; |
| 1632 |
|
| 1633 |
if not Element.AttributeBoolean('default_played', FDefaultPlayed) then |
| 1634 |
DefaultPlayed := false; |
| 1635 |
|
| 1636 |
if not DOMGetLevelLogicClassAttribute(Element, 'type', FLogicClass) then |
| 1637 |
LogicClass := TLevelLogic; |
| 1638 |
|
| 1639 |
PlaceholderName := PlaceholderNames['x3dshape']; |
| 1640 |
if Element.AttributeString('placeholders', PlaceholdersKey) then |
| 1641 |
PlaceholderName := PlaceholderNames[PlaceholdersKey]; |
| 1642 |
|
| 1643 |
FreeAndNil(FLoadingImage); { make sure LoadingImage is clear first } |
| 1644 |
if Element.AttributeString('loading_image', LoadingImageUrl) then |
| 1645 |
begin |
| 1646 |
LoadingImageUrl := CombineURI(DocumentBaseUrl, LoadingImageUrl); |
| 1647 |
LoadingImage := LoadImage(LoadingImageUrl, [TRGBImage]) as TRGBImage; |
| 1648 |
end; |
| 1649 |
|
| 1650 |
if (not Element.AttributeSingle('loading_bar_y_position', |
| 1651 |
FLoadingBarYPosition)) and |
| 1652 |
{ handle loading_image_bar_y_position for backward compatibility } |
| 1653 |
(not Element.AttributeSingle('loading_image_bar_y_position', |
| 1654 |
FLoadingBarYPosition)) then |
| 1655 |
LoadingBarYPosition := TProgressUserInterface.DefaultBarYPosition; |
| 1656 |
|
| 1657 |
if Element.AttributeString('placeholder_reference_direction', S) then |
| 1658 |
PlaceholderReferenceDirection := Vector3FromStr(S) else |
| 1659 |
PlaceholderReferenceDirection := DefaultPlaceholderReferenceDirection; |
| 1660 |
|
| 1661 |
LevelResources.LoadResources(Element); |
| 1662 |
AddAlwaysPreparedResources; |
| 1663 |
|
| 1664 |
{$warnings off} // using deprecated in deprecated unit |
| 1665 |
if Element.AttributeString('music_sound', SoundName) then |
| 1666 |
MusicSound := SoundEngine.SoundFromName(SoundName) |
| 1667 |
else |
| 1668 |
MusicSound := nil; |
| 1669 |
{$warnings on} |
| 1670 |
end; |
| 1671 |
|
| 1672 |
{ TLevelInfoList ------------------------------------------------------- } |
| 1673 |
|
| 1674 |
function TLevelInfoList.FindName(const AName: string): TLevelInfo; |
| 1675 |
var |
| 1676 |
I: Integer; |
| 1677 |
S: string; |
| 1678 |
begin |
| 1679 |
for I := 0 to Count - 1 do |
| 1680 |
if Items[I].Name = AName then |
| 1681 |
Exit(Items[I]); |
| 1682 |
|
| 1683 |
S := Format('Level name "%s" is not found on the Levels list', [AName]); |
| 1684 |
if Count = 0 then |
| 1685 |
S := S + '.' + NL + NL + 'Warning: there are no levels available on the list at all. This means that the game data was not correctly installed (as we did not find any level.xml files defining any levels). Or the developer forgot to call Levels.LoadFromFiles.'; |
| 1686 |
raise Exception.Create(S); |
| 1687 |
end; |
| 1688 |
|
| 1689 |
function IsSmallerByNumber({$ifdef GENERICS_CONSTREF}constref{$else}const{$endif} A, B: TLevelInfo): Integer; |
| 1690 |
begin |
| 1691 |
Result := A.Number - B.Number; |
| 1692 |
end; |
| 1693 |
|
| 1694 |
procedure TLevelInfoList.LoadFromConfig(const Config: TCastleConfig); |
| 1695 |
var |
| 1696 |
I: Integer; |
| 1697 |
begin |
| 1698 |
for I := 0 to Count - 1 do |
| 1699 |
Items[I].Played := Config.GetValue( |
| 1700 |
'levels_available/' + Items[I].Name + '/played', |
| 1701 |
Items[I].DefaultPlayed); |
| 1702 |
end; |
| 1703 |
|
| 1704 |
procedure TLevelInfoList.SaveToConfig(const Config: TCastleConfig); |
| 1705 |
var |
| 1706 |
I: Integer; |
| 1707 |
begin |
| 1708 |
for I := 0 to Count - 1 do |
| 1709 |
Config.SetDeleteValue( |
| 1710 |
'levels_available/' + Items[I].Name + '/played', |
| 1711 |
Items[I].Played, |
| 1712 |
Items[I].DefaultPlayed); |
| 1713 |
end; |
| 1714 |
|
| 1715 |
procedure TLevelInfoList.AddFromInfo(const Info: TFileInfo; var StopSearch: boolean); |
| 1716 |
begin |
| 1717 |
AddFromFile(Info.Url); |
| 1718 |
end; |
| 1719 |
|
| 1720 |
procedure TLevelInfoList.AddFromFile(const Url: String); |
| 1721 |
var |
| 1722 |
NewLevelInfo: TLevelInfo; |
| 1723 |
begin |
| 1724 |
NewLevelInfo := TLevelInfo.Create; |
| 1725 |
Add(NewLevelInfo); |
| 1726 |
NewLevelInfo.Played := false; |
| 1727 |
|
| 1728 |
UrlReadXML(NewLevelInfo.Document, Url); |
| 1729 |
NewLevelInfo.DocumentBaseUrl := Url; |
| 1730 |
NewLevelInfo.LoadFromDocument; |
| 1731 |
end; |
| 1732 |
|
| 1733 |
procedure TLevelInfoList.LoadFromFiles(const LevelsPath: string); |
| 1734 |
begin |
| 1735 |
FindFiles(LevelsPath, 'level.xml', false, |
| 1736 |
{$ifdef FPC}@{$endif}AddFromInfo, [ffRecursive]); |
| 1737 |
end; |
| 1738 |
|
| 1739 |
procedure TLevelInfoList.LoadFromFiles; |
| 1740 |
begin |
| 1741 |
LoadFromFiles('castle-data:/'); |
| 1742 |
SortByNumber; |
| 1743 |
end; |
| 1744 |
|
| 1745 |
procedure TLevelInfoList.SortByNumber; |
| 1746 |
type |
| 1747 |
TLevelInfoComparer = {$ifdef FPC}specialize{$endif} TComparer<TLevelInfo>; |
| 1748 |
begin |
| 1749 |
Sort(TLevelInfoComparer.Construct({$ifdef FPC}@{$endif}IsSmallerByNumber)); |
| 1750 |
end; |
| 1751 |
|
| 1752 |
{ TLevelLogicClasses --------------------------------------------------------- } |
| 1753 |
|
| 1754 |
function TLevelLogicClasses.GetItems(const AKey: string): TLevelLogicClass; |
| 1755 |
begin |
| 1756 |
Result := inherited Items[AKey]; |
| 1757 |
end; |
| 1758 |
|
| 1759 |
procedure TLevelLogicClasses.SetItems(const AKey: string; const AValue: TLevelLogicClass); |
| 1760 |
begin |
| 1761 |
AddOrSetValue(AKey, AValue); |
| 1762 |
end; |
| 1763 |
|
| 1764 |
{ initialization / finalization ---------------------------------------------- } |
| 1765 |
|
| 1766 |
initialization |
| 1767 |
FLevels := TLevelInfoList.Create(true); |
| 1768 |
Inc(FLevels.References); |
| 1769 |
finalization |
| 1770 |
FreeAndNil(FLevelLogicClasses); |
| 1771 |
{ there may still exist TLevel instances that refer to our |
| 1772 |
TLevelInfo instances. So we don't always free Levels below. } |
| 1773 |
if FLevels <> nil then |
| 1774 |
begin |
| 1775 |
Dec(FLevels.References); |
| 1776 |
if FLevels.References = 0 then |
| 1777 |
FreeAndNil(FLevels); |
| 1778 |
end; |
| 1779 |
end. |