| 1 |
{ |
| 2 |
Copyright 2009-2024 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 |
{ Terrain (height map) components. |
| 17 |
|
| 18 |
TODO: Terrain API is not finalized yet, |
| 19 |
there may be significant incompatible changes to this unit in the future. |
| 20 |
Big TODOs: |
| 21 |
|
| 22 |
@unorderedList( |
| 23 |
@item( |
| 24 |
Edit terrain heights in the CGE editor. |
| 25 |
|
| 26 |
Possible approach: turn any data (including TCastleTerrainNoise) into |
| 27 |
TCastleTerrainImage, then add editing tools to just change this image. |
| 28 |
|
| 29 |
Alternatively user could edit a TCastleTerrainImage that is combined |
| 30 |
with TCastleTerrainNoise -- this seems a powerful but uncertain feature, |
| 31 |
i.e. in the end it means you cannot directly edit the output of TCastleTerrainNoise, |
| 32 |
so it may be less comfortable (although it would allow to later regenerate |
| 33 |
TCastleTerrainNoise and keep the edits -- effectively they would work |
| 34 |
like Blender modifier.) |
| 35 |
) |
| 36 |
|
| 37 |
@item( |
| 38 |
Edit textures influence using splatmap. Just a texture where RGBA |
| 39 |
are weights for each texture. |
| 40 |
|
| 41 |
Implement this, and also add a brush to edit splatmap in CGE editor. |
| 42 |
|
| 43 |
The existing way to determine layers influence can then be used |
| 44 |
as just a nice (optional) way to auto-generate initial splatmap.) |
| 45 |
|
| 46 |
@item(Adding vegetation to the terrain. |
| 47 |
|
| 48 |
Adding grass and other small things (that must be placed in large batches |
| 49 |
and density should be dynamic). |
| 50 |
|
| 51 |
Adding trees, boulders and other large things (their density should |
| 52 |
also be dynamic for fast rendering, but at close distance they are just |
| 53 |
3D models).) |
| 54 |
|
| 55 |
@item( |
| 56 |
Add non-trivial rendering algorithm. |
| 57 |
Right now it is really the simplest possible approach to generate a mesh |
| 58 |
from heights with a simplest shader mixing a few texture layers.) |
| 59 |
) |
| 60 |
|
| 61 |
Smaller TODOs: |
| 62 |
|
| 63 |
@unorderedList( |
| 64 |
@item(TCastleTerrain.Subdivisions should be TVector2Cardinal. |
| 65 |
Needs introducing TCastleVector2CardinalPersistent.) |
| 66 |
@item(Enable normalmaps for each layer.) |
| 67 |
@item(? TCastleTerrain configurable textures number. |
| 68 |
Unsure -- hardcoding current 4 layers sucks, but also it makes sense for coming RGBA splatmap.) |
| 69 |
@item(? TCastleTerrain Use GridCount, GridStep instead of Subdivisions, Size? |
| 70 |
See wyrd-forest arguments.) |
| 71 |
@item(? TCastleTerrain add property to define material type, like in primitives - unlit, physical, phong. |
| 72 |
Wait with this for our final CGE components to define materials and effects, |
| 73 |
TCastlePhysicalMaterial, TCastleShaderEffect -- they will determine how to nicely |
| 74 |
expose it here.) |
| 75 |
) |
| 76 |
} |
| 77 |
unit CastleTerrain; |
| 78 |
|
| 79 |
{$I castleconf.inc} |
| 80 |
|
| 81 |
interface |
| 82 |
|
| 83 |
uses SysUtils, Classes, |
| 84 |
CastleClassUtils, CastleScript, CastleImages, X3DNodes, CastleVectors, |
| 85 |
CastleRectangles, CastleTransform, CastleScene, X3DFields, CastleRenderOptions, |
| 86 |
CastleColors, CastleTriangles; |
| 87 |
|
| 88 |
type |
| 89 |
{ Terrain (height map) data that can be used for @link(TCastleTerrain.Data). } |
| 90 |
TCastleTerrainData = class(TCastleComponent) |
| 91 |
strict private |
| 92 |
FChangeNotifications: TNotifyEventList; |
| 93 |
procedure UpdateNodeCore(const Node: TAbstractChildNode; |
| 94 |
const Subdivisions: TVector2; const InputRange, OutputRange: TFloatRectangle; |
| 95 |
const Appearance: TAppearanceNode; |
| 96 |
const TriangulationIgnoreHeights: Boolean); |
| 97 |
private |
| 98 |
{ Create X3D node with the given terrain shape. |
| 99 |
|
| 100 |
InputRange determines the range of values (minimum and maximum X and Y) |
| 101 |
queried from the underlying terrain, that is: queried using the @link(Height) |
| 102 |
method. |
| 103 |
|
| 104 |
OutputRange determines the span of the resulting shape in X and Z |
| 105 |
coordinates. Note that, when converting a heightmap to 3D, |
| 106 |
the 2nd dimension is Z. In 3D, we use Y for height, as this is the default |
| 107 |
in X3D and Castle Game Engine. |
| 108 |
|
| 109 |
Often you will set InputRange and OutputRange to the same values, |
| 110 |
but you don't have to. Often they will at least have the same aspect ratio |
| 111 |
(actually, often they will be square), but you don't have to. |
| 112 |
|
| 113 |
Subdivisions determines how dense is the mesh. |
| 114 |
They determine the number of rows in columns in the mesh. |
| 115 |
E.g. subdivision (4,4) means 16 (4 * 4) quads and 25 (5 * 5) vertexes. |
| 116 |
This matches the Blender's "subdivisions" parameter for grids. |
| 117 |
|
| 118 |
We return the node that you should insert to your scene. |
| 119 |
|
| 120 |
It will use the given TAppearanceNode. |
| 121 |
The appearance is not configured in any way by this method, |
| 122 |
and it can even be @nil. } |
| 123 |
function CreateNode(const Subdivisions: TVector2; |
| 124 |
const InputRange, OutputRange: TFloatRectangle; |
| 125 |
const Appearance: TAppearanceNode; |
| 126 |
const TriangulationIgnoreHeights: Boolean): TAbstractChildNode; overload; |
| 127 |
|
| 128 |
{ Update a node created by @link(CreateNode) |
| 129 |
to the new terrain and it's settings. |
| 130 |
The appearance of the previously created node (in CreateNode) is preserved. } |
| 131 |
procedure UpdateNode(const Node: TAbstractChildNode; |
| 132 |
const Subdivisions: TVector2; const InputRange, OutputRange: TFloatRectangle; |
| 133 |
const TriangulationIgnoreHeights: Boolean); |
| 134 |
protected |
| 135 |
{ Use this in descendants implementation to notify that data |
| 136 |
(affecting @link(Height) results) changed. |
| 137 |
In the base class, it takes care to run notifications registered |
| 138 |
by @link(AddChangeNotification). } |
| 139 |
procedure DoChange; |
| 140 |
public |
| 141 |
constructor Create(AOwner: TComponent); override; |
| 142 |
destructor Destroy; override; |
| 143 |
|
| 144 |
{ Return height for given terrain point. |
| 145 |
|
| 146 |
@param(Coord The queried terrain height. |
| 147 |
Coord.X is the X position in local terrain coordinate space. |
| 148 |
Coord.Y is the Z position in local terrain coordinate space. |
| 149 |
They are in the range determined by TCastleTerrain.Size. |
| 150 |
) |
| 151 |
@param(TexCoord The texture coordinate at this point, |
| 152 |
assuming that TCastleTerrain.Size and texture UV scale would cancel each other, |
| 153 |
making both TexCoord.X and TexCoord.Y always in [0..1] range. |
| 154 |
|
| 155 |
Note that TexCoord.Y grows in different direction than Coord.Y, |
| 156 |
this means that textures have natural look when viewer from above the terrain |
| 157 |
(otherwise they would seem flipped in one direction in CGE right-handed |
| 158 |
coordinate system). |
| 159 |
) } |
| 160 |
function Height(const Coord, TexCoord: TVector2): Single; virtual; abstract; |
| 161 |
|
| 162 |
{ Add notification when data (affecting @link(Height) results) changes. } |
| 163 |
procedure AddChangeNotification(const Notify: TNotifyEvent); |
| 164 |
{ Remove notification when data (affecting @link(Height) results) changes. } |
| 165 |
procedure RemoveChangeNotification(const Notify: TNotifyEvent); |
| 166 |
end; |
| 167 |
|
| 168 |
{ Terrain (height map) data taken from intensities in an image. |
| 169 |
|
| 170 |
The image spans always the entire terrain in X and Z. |
| 171 |
|
| 172 |
The image minimum intensity (black) maps to height MinLevel, |
| 173 |
maximum intensity (white) maps to height MaxLevel. |
| 174 |
Any relation of MinLevel and MaxLevel is OK, |
| 175 |
that is: both MinLevel<MaxLevel and MinLevel>MaxLevel are valid. |
| 176 |
|
| 177 |
When image is not loaded, it behaves like all the image intensities are 0.5. } |
| 178 |
TCastleTerrainImage = class(TCastleTerrainData) |
| 179 |
strict private |
| 180 |
{ FImage = nil and FUrl = '' when not loaded. } |
| 181 |
FImage: TGrayscaleFloatImage; |
| 182 |
FUrl: String; |
| 183 |
FMinLevel, FMaxLevel: Single; |
| 184 |
procedure SetUrl(const Value: String); |
| 185 |
procedure SetMinLevel(const Value: Single); |
| 186 |
procedure SetMaxLevel(const Value: Single); |
| 187 |
public |
| 188 |
constructor Create(AOwner: TComponent); override; |
| 189 |
destructor Destroy; override; |
| 190 |
function Height(const Coord, TexCoord: TVector2): Single; override; |
| 191 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 192 |
published |
| 193 |
{ Image URL. Empty string means that no image is loaded. } |
| 194 |
property Url: String read FUrl write SetUrl; |
| 195 |
{ Height when the image has minimum intensity (black). } |
| 196 |
property MinLevel: Single read FMinLevel write SetMinLevel {$ifdef FPC}default -0.5{$endif}; |
| 197 |
{ Height when the image has maximum intensity (white). } |
| 198 |
property MaxLevel: Single read FMaxLevel write SetMaxLevel {$ifdef FPC}default 0.5{$endif}; |
| 199 |
end; |
| 200 |
|
| 201 |
{ Terrain (height for each X, Y) data calculated from CastleScript |
| 202 |
expression. At construction, pass FunctionExpression, |
| 203 |
that is CastleScript language expression calculating height |
| 204 |
based on X, Y. |
| 205 |
|
| 206 |
See https://castle-engine.io/castle_script.php for CastleScript syntax. |
| 207 |
Try e.g. function like |
| 208 |
|
| 209 |
- @code(sin(x) + sin(y)) |
| 210 |
|
| 211 |
- Sum sinusoides of various frequencies and amplitudes: |
| 212 |
|
| 213 |
@preformatted( |
| 214 |
(sin(x) + sin(x*2) / 2 + sin(x*4) / 4) * |
| 215 |
(sin(y) + sin(y*2) / 2 + sin(y*4) / 4) |
| 216 |
) } |
| 217 |
TTerrainCasScript = class(TCastleTerrainData) |
| 218 |
strict private |
| 219 |
FXVariable, FYVariable: TCasScriptFloat; |
| 220 |
FFunction: TCasScriptExpression; |
| 221 |
public |
| 222 |
constructor Create(const FunctionExpression: String); reintroduce; |
| 223 |
destructor Destroy; override; |
| 224 |
function Height(const Coord, TexCoord: TVector2): Single; override; |
| 225 |
end deprecated 'using CastleScript to define terrain is deprecated due to low usage'; |
| 226 |
|
| 227 |
TNoiseInterpolation = (niNone, niLinear, niCosine, niSpline); |
| 228 |
|
| 229 |
{ Terrain heights are generated from a smooth noise, |
| 230 |
combined with some terrain-specific improvements (Heterogeneous). |
| 231 |
|
| 232 |
We take the noise (integer noise, i.e. hash), smooth it |
| 233 |
(how well, and how fast --- see @link(Interpolation) and @link(Blur)), |
| 234 |
and add several |
| 235 |
functions ("octaves") of such noise (with varying frequency and amplitude) |
| 236 |
together. This is the kind of noise used to synthesize textures, |
| 237 |
terrains and all other procedural stuff. |
| 238 |
|
| 239 |
For more info about math inside: |
| 240 |
|
| 241 |
@unorderedList( |
| 242 |
@item([http://en.wikipedia.org/wiki/Fractional_Brownian_motion]. |
| 243 |
This is the idea of summing up octaves of noise. |
| 244 |
Ken Musgrave's dissertation has a lot of info and interesting references: |
| 245 |
[http://www.kenmusgrave.com/dissertation.html]) |
| 246 |
|
| 247 |
@item(Blender's source code is informative, interesting file |
| 248 |
is blender/source/blender/blenlib/intern/noise.c) |
| 249 |
|
| 250 |
@item(The simplest practical introduction to the idea is on |
| 251 |
[http://freespace.virgin.net/hugo.elias/models/m_perlin.htm]. |
| 252 |
It describes how to get nice noise very easily, and my approach follows |
| 253 |
theirs.) |
| 254 |
) } |
| 255 |
TCastleTerrainNoise = class(TCastleTerrainData) |
| 256 |
strict private |
| 257 |
type |
| 258 |
TNoise2DMethod = function (const X, Y: Single; const Seed: Cardinal): Single; |
| 259 |
var |
| 260 |
FOctaves: Single; |
| 261 |
FSmoothness: Single; |
| 262 |
FAmplitude: Single; |
| 263 |
FFrequency: Single; |
| 264 |
FInterpolation: TNoiseInterpolation; |
| 265 |
NoiseMethod: TNoise2DMethod; |
| 266 |
FBlur: Boolean; |
| 267 |
FSeed: Cardinal; |
| 268 |
FHeterogeneous: Single; |
| 269 |
procedure SetOctaves(const Value: Single); |
| 270 |
procedure SetSmoothness(const Value: Single); |
| 271 |
procedure SetAmplitude(const Value: Single); |
| 272 |
procedure SetFrequency(const Value: Single); |
| 273 |
procedure SetInterpolation(const Value: TNoiseInterpolation); |
| 274 |
procedure SetBlur(const Value: Boolean); |
| 275 |
procedure SetSeed(const Value: Cardinal); |
| 276 |
procedure SetHeterogeneous(const Value: Single); |
| 277 |
procedure UpdateNoiseMethod; |
| 278 |
public |
| 279 |
const |
| 280 |
DefaultOctaves = 4.0; |
| 281 |
DefaultSmoothnes = 2.0; |
| 282 |
DefaultAmplitude = 8.0; |
| 283 |
DefaultFrequency = 0.05; |
| 284 |
DefaultInterpolation = niCosine; |
| 285 |
DefaultBlur = false; |
| 286 |
DefaultHeterogeneous = 0.5; |
| 287 |
|
| 288 |
constructor Create(AOwner: TComponent); override; |
| 289 |
function Height(const Coord, TexCoord: TVector2): Single; override; |
| 290 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 291 |
published |
| 292 |
{ Number of noise functions to sum. |
| 293 |
This linearly affects the time for Height call, so don't make |
| 294 |
it too much. Usually ~a few are Ok. |
| 295 |
|
| 296 |
(The fact that it's a float is just a simple trick to allow smooth |
| 297 |
transitions from x to x+1. In fact, it's executed like |
| 298 |
Trunc(Octaves) * some noises + Frac(Octaves) * some last noise.) |
| 299 |
|
| 300 |
Reasonable values are roughly between 0..20. } |
| 301 |
property Octaves: Single read FOctaves write SetOctaves {$ifdef FPC}default DefaultOctaves{$endif}; |
| 302 |
|
| 303 |
{ How noise amplitude changes, when frequency doubles. |
| 304 |
When we double frequency, amplitude is divided by this. |
| 305 |
Smaller values <=> larger frequency noise |
| 306 |
is more visible, so terrain is less smooth (more noisy). |
| 307 |
|
| 308 |
This is elsewhere called fractal increment, fractal dimension parameter, |
| 309 |
"H", spectral exponent (see e.g. Blender sources, Musgrave's dissertation). |
| 310 |
Do not confuse this with "lacunarity" (how frequency changes in each octave), |
| 311 |
that is simply hardcoded to 2.0 in our code currently. |
| 312 |
In [http://freespace.virgin.net/hugo.elias/models/m_perlin.htm], |
| 313 |
the inverse of this 1/Smoothness is called "Persistence". |
| 314 |
|
| 315 |
I decided to call it "Smoothness", since this is the practical |
| 316 |
intuitive meaning. |
| 317 |
|
| 318 |
Value equal 1.0 means that amplitude doesn't change at all, |
| 319 |
each noise frequency is visible the same, so in effect you will |
| 320 |
just see a lot of noise. And values < 1.0 are really nonsense, |
| 321 |
they make more frequency noise even more visible, which means that |
| 322 |
the terrain is dominated by noise. |
| 323 |
|
| 324 |
Reasonable values are roughly between 1..10. } |
| 325 |
property Smoothness: Single read FSmoothness write SetSmoothness {$ifdef FPC}default DefaultSmoothnes{$endif}; |
| 326 |
|
| 327 |
{ Amplitude and frequency of the first noise octave. |
| 328 |
Amplitude scales the height of the result, and Frequency scales |
| 329 |
the size of the bumps. |
| 330 |
@groupBegin } |
| 331 |
property Amplitude: Single read FAmplitude write SetAmplitude {$ifdef FPC}default DefaultAmplitude{$endif}; |
| 332 |
property Frequency: Single read FFrequency write SetFrequency {$ifdef FPC}default DefaultFrequency{$endif}; |
| 333 |
{ @groupEnd } |
| 334 |
|
| 335 |
{ How integer noise is interpolated to get smooth float noise. |
| 336 |
|
| 337 |
Setting this to niNone turns off interpolation, which means that |
| 338 |
your terrain is a sum of a couple of blocky noises --- ugly. |
| 339 |
|
| 340 |
Using niLinear (means "bilinear", since this is 2D case) |
| 341 |
is also usually bad. Unless you use octaves of really high frequencies, |
| 342 |
usually sharp edges / flat in-betweens will be visible. |
| 343 |
|
| 344 |
Using niCosine in right now the best. |
| 345 |
|
| 346 |
Using niSpline is even better looking |
| 347 |
(usese Catmull-Rom splines, |
| 348 |
which are special case of cubic Hermite spline, see |
| 349 |
http://en.wikipedia.org/wiki/Cubic_Hermite_spline, |
| 350 |
http://en.wikipedia.org/wiki/Bicubic_interpolation). |
| 351 |
But it's more time consuming under current implementation. } |
| 352 |
property Interpolation: TNoiseInterpolation |
| 353 |
read FInterpolation write SetInterpolation default DefaultInterpolation; |
| 354 |
|
| 355 |
{ Resulting noise octaves may be blurred. This helps to remove |
| 356 |
the inherent vertical/horizontal directionality in our 2D noise |
| 357 |
(it also makes it more smooth, since that's what blurring is about; |
| 358 |
you may want to increase Frequency * 2 to balance this). |
| 359 |
|
| 360 |
This is independent from @link(Interpolation). Although the need |
| 361 |
for Blur is most obvious in poor/none interpolation methods |
| 362 |
(none, linear), it also helps for the nicer interpolation methods |
| 363 |
(cosine, cubic). |
| 364 |
|
| 365 |
Note about [http://freespace.virgin.net/hugo.elias/models/m_perlin.htm]: |
| 366 |
this "blurring" is called "smoothing" there. |
| 367 |
I call it blurring, as it seems more precise to me. } |
| 368 |
property Blur: Boolean read FBlur write SetBlur default DefaultBlur; |
| 369 |
|
| 370 |
{ Determines the random seeds used when generating the terrain. } |
| 371 |
property Seed: Cardinal read FSeed write SetSeed default 0; |
| 372 |
|
| 373 |
{ If non-zero, then we generate terrain using heterogeneous fBm. |
| 374 |
Intuitively, the idea is that the terrain details (from higher octaves) |
| 375 |
are more noisy when ground is higher. This is realistic |
| 376 |
(debris gathers in lower terrain, smoothing it more). |
| 377 |
|
| 378 |
More precisely, this means that we accumulate multiplied previous noise, |
| 379 |
at each step dividing this accumulated result by Heterogeneous, |
| 380 |
and clamping at 1.0. So when Heterogeneous is very small, |
| 381 |
this always ends up 1.0, and we get normal (homogeneous) generation. |
| 382 |
When Heterogeneous is larger, the details (at lower ground) |
| 383 |
are scaled down (terrain is smoother). |
| 384 |
|
| 385 |
This is called "threshold" in Musgrave's dissertation (see algorithm |
| 386 |
in section 2.3.2.5 "A Large Scale Terrain Model"). |
| 387 |
|
| 388 |
Reasonable values for this are between 0..2. } |
| 389 |
property Heterogeneous: Single |
| 390 |
read FHeterogeneous write SetHeterogeneous {$ifdef FPC}default DefaultHeterogeneous{$endif}; |
| 391 |
end; |
| 392 |
|
| 393 |
TTerrain = TCastleTerrainData deprecated 'use TCastleTerrainData'; |
| 394 |
TTerrainImage = TCastleTerrainImage deprecated 'use TCastleTerrainImage'; |
| 395 |
TTerrainNoise = TCastleTerrainNoise deprecated 'use TCastleTerrainNoise'; |
| 396 |
|
| 397 |
{ Operation used by TCastleTerrainCombine to combine heights from 2 terrain data sources. |
| 398 |
See @link(TCastleTerrainCombine.Operation). } |
| 399 |
TCastleTerrainCombineOperation = (opMax, opMin, opAdd, opMultiply); |
| 400 |
|
| 401 |
{ Combine (add, multiply, do maximum or minimum) two other terrain data sources. |
| 402 |
This allows to e.g. combine TCastleTerrainNoise with TCastleTerrainImage |
| 403 |
in a flexible way. For example you can use TCastleTerrainImage to force some |
| 404 |
mountains / valleys even where TCastleTerrainNoise doesn't have them. } |
| 405 |
TCastleTerrainCombine = class(TCastleTerrainData) |
| 406 |
private |
| 407 |
type |
| 408 |
TOperationFunc = function (const A, B: Single): Single; |
| 409 |
var |
| 410 |
FData1, FData2: TCastleTerrainData; |
| 411 |
FData1Observer, FData2Observer: TFreeNotificationObserver; |
| 412 |
FOperation: TCastleTerrainCombineOperation; |
| 413 |
FOperationFunc: TOperationFunc; |
| 414 |
procedure Data1FreeNotification(const Sender: TFreeNotificationObserver); |
| 415 |
procedure Data2FreeNotification(const Sender: TFreeNotificationObserver); |
| 416 |
procedure Data1Changed(Sender: TObject); |
| 417 |
procedure Data2Changed(Sender: TObject); |
| 418 |
procedure SetData1(const Value: TCastleTerrainData); |
| 419 |
procedure SetData2(const Value: TCastleTerrainData); |
| 420 |
procedure SetOperation(const Value: TCastleTerrainCombineOperation); |
| 421 |
procedure UpdateOperationFunc; |
| 422 |
public |
| 423 |
const |
| 424 |
DefaultOperation = opMax; |
| 425 |
constructor Create(AOwner: TComponent); override; |
| 426 |
function Height(const Coord, TexCoord: TVector2): Single; override; |
| 427 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 428 |
published |
| 429 |
{ First data for terrain heights. } |
| 430 |
property Data1: TCastleTerrainData read FData1 write SetData1; |
| 431 |
{ Second data for terrain heights. } |
| 432 |
property Data2: TCastleTerrainData read FData2 write SetData2; |
| 433 |
{ How to combine results of Data1 and Data2. } |
| 434 |
property Operation: TCastleTerrainCombineOperation read FOperation write SetOperation default opMax; |
| 435 |
end; |
| 436 |
|
| 437 |
TCastleTerrain = class; |
| 438 |
|
| 439 |
{ Layer of a terrain properties. See @link(TCastleTerrain) for docs how terrain |
| 440 |
uses layers for display. } |
| 441 |
TCastleTerrainLayer = class(TCastleComponent) |
| 442 |
strict private |
| 443 |
Terrain: TCastleTerrain; |
| 444 |
Layer: Integer; |
| 445 |
ColorField: TSFColor; |
| 446 |
TextureNode: TImageTextureNode; |
| 447 |
function GetUvScale: Single; |
| 448 |
procedure SetUvScale(const Value: Single); |
| 449 |
function GetMetallic: Single; |
| 450 |
procedure SetMetallic(const Value: Single); |
| 451 |
function GetRoughness: Single; |
| 452 |
procedure SetRoughness(const Value: Single); |
| 453 |
function GetColor: TCastleColorRGB; |
| 454 |
procedure SetColor(const Value: TCastleColorRGB); |
| 455 |
function GetTexture: String; |
| 456 |
procedure SetTexture(const Value: String); |
| 457 |
function GetUsingPackedVector(const Vec: TSFVec4f): Single; |
| 458 |
procedure SetUsingPackedVector(const Vec: TSFVec4f; const Value: Single); |
| 459 |
{$warnings off} |
| 460 |
private |
| 461 |
constructor CreateForTerrain(const ATerrain: TCastleTerrain; |
| 462 |
const ALayer: Integer; const Effect: TEffectNode); |
| 463 |
public |
| 464 |
{$warnings on} |
| 465 |
const |
| 466 |
DefaultUvScale = 1.0; |
| 467 |
DefaultMetallic = 1.0; |
| 468 |
DefaultRoughness = 1.0; |
| 469 |
|
| 470 |
{ Public constructor for this class raises exception. |
| 471 |
Never create instances of this class directly. |
| 472 |
The instances of this class should only be created by implementation of TCastleTerrain, |
| 473 |
access them as TCastleTerrain subcomponents like @link(TCastleTerrain.Layer1). } |
| 474 |
constructor Create(AOwner: TComponent); override; |
| 475 |
destructor Destroy; override; |
| 476 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 477 |
|
| 478 |
{ Color, multiplied by @link(Texture). |
| 479 |
Default is white. } |
| 480 |
property Color: TCastleColorRGB read GetColor write SetColor; |
| 481 |
|
| 482 |
published |
| 483 |
{ Scale the @link(Texture). |
| 484 |
Setting UV scale to be equal to 1/@link(TCastleTerrain.Size) |
| 485 |
reliably makes the texture image size match the whole terrain. } |
| 486 |
property UvScale: Single read GetUvScale write SetUvScale {$ifdef FPC}default DefaultUvScale{$endif}; |
| 487 |
|
| 488 |
{ Texture URL. Texture is multiplied by @link(Color). |
| 489 |
Default (none) behaves as if it was a white texture for calculation. } |
| 490 |
property Texture: String read GetTexture write SetTexture; |
| 491 |
|
| 492 |
{ The metalness of the material; values range from 0.0 (non-metal) to 1.0 (metal). } |
| 493 |
property Metallic: Single read GetMetallic write SetMetallic {$ifdef FPC}default DefaultMetallic{$endif}; |
| 494 |
|
| 495 |
{ The roughness of the material; values range from 0.0 (smooth) to 1.0 (rough). } |
| 496 |
property Roughness: Single read GetRoughness write SetRoughness {$ifdef FPC}default DefaultRoughness{$endif}; |
| 497 |
|
| 498 |
{$define read_interface_class} |
| 499 |
{$I auto_generated_persistent_vectors/tcastleterrainlayer_persistent_vectors.inc} |
| 500 |
{$undef read_interface_class} |
| 501 |
end; |
| 502 |
|
| 503 |
{ Terrain. |
| 504 |
|
| 505 |
Assign @link(Data) to provide some non-trivial height map, you can use there: |
| 506 |
|
| 507 |
@unorderedList( |
| 508 |
@item(@link(TCastleTerrainNoise) to generate a height map using a dedicated |
| 509 |
algorithm for terrain generation, using smooth noise and special tricks |
| 510 |
to have smooth and heteregeneous terrain.) |
| 511 |
|
| 512 |
@item(@link(TCastleTerrainImage) to generate a height map from intensities |
| 513 |
of a simple 2D image.) |
| 514 |
|
| 515 |
@item(@link(TCastleTerrainCombine) to combine the above options in any expression |
| 516 |
(take minimum, maximum, sum, multiply).) |
| 517 |
) |
| 518 |
|
| 519 |
The terrain starts as a standard mesh with a @link(TPhysicalMaterialNode) material. |
| 520 |
We apply on it a special affect to mix 4 layers, where each layer has a separate |
| 521 |
color and texture. |
| 522 |
|
| 523 |
@unorderedList( |
| 524 |
@item( |
| 525 |
Each layer has a color (white by default), texture (none by default, |
| 526 |
that behaves like white) and UV scale. |
| 527 |
See @link(TCastleTerrainLayer). |
| 528 |
Each layer is a property like @link(Layer1), @link(Layer2), |
| 529 |
@link(Layer3), @link(Layer4).) |
| 530 |
|
| 531 |
@item(Only the RBG channels of textures matter, alpha is ignored.) |
| 532 |
|
| 533 |
@item(Layer 1 is used for flat terrain on lower heights.) |
| 534 |
|
| 535 |
@item(Layer 2 is used for steep terrain on lower heights.) |
| 536 |
|
| 537 |
@item(Layer 3 is used for flat terrain on higher heights.) |
| 538 |
|
| 539 |
@item(Layer 4 is used for steep terrain on higher heights.) |
| 540 |
|
| 541 |
@item(The meaning of "lower" and "higher" heights is determined by @link(Height1) |
| 542 |
and @link(Height2). Below @link(Height1) we show only layers 1+2, |
| 543 |
above @link(Height2) we show only layers 3+4, |
| 544 |
between we show a smooth interpolation between them.) |
| 545 |
|
| 546 |
@item(The meaning of "flat" and "steep" is determined by looking at terrain |
| 547 |
normals emphasized by @link(SteepEmphasize).) |
| 548 |
|
| 549 |
@item(The influence of this effect can be controlled by LayersInfluence.) |
| 550 |
) |
| 551 |
} |
| 552 |
TCastleTerrain = class(TCastleTransform) |
| 553 |
public |
| 554 |
const |
| 555 |
{ Texture layers to render this terrain. } |
| 556 |
LayersCount = 4; |
| 557 |
HeightsCount = 2; |
| 558 |
strict private |
| 559 |
TerrainNode: TAbstractChildNode; |
| 560 |
Appearance: TAppearanceNode; |
| 561 |
Effect: TEffectNode; |
| 562 |
HeightsFields: array [1..HeightsCount] of TSFFloat; |
| 563 |
Layers: array [1..LayersCount] of TCastleTerrainLayer; |
| 564 |
FData: TCastleTerrainData; |
| 565 |
FDataObserver: TFreeNotificationObserver; |
| 566 |
FTriangulationIgnoreHeights: Boolean; |
| 567 |
FSize, FQueryOffset: TVector2; |
| 568 |
FLayersInfluence: Single; |
| 569 |
FSteepEmphasize: Single; |
| 570 |
FSubdivisions: TVector2; |
| 571 |
FPreciseCollisions: Boolean; |
| 572 |
FUpdateGeometryWhenLoaded: Boolean; |
| 573 |
function GetRenderOptions: TCastleRenderOptions; |
| 574 |
function GetLayer(const Index: Integer): TCastleTerrainLayer; |
| 575 |
procedure DataFreeNotification(const Sender: TFreeNotificationObserver); |
| 576 |
procedure DataChanged(Sender: TObject); |
| 577 |
|
| 578 |
{ Regenerate geometry (vertexes, normals etc.) to show the current Data |
| 579 |
with current parameters. } |
| 580 |
procedure UpdateGeometry; |
| 581 |
|
| 582 |
procedure SetData(const Value: TCastleTerrainData); |
| 583 |
procedure SetTriangulationIgnoreHeights(const Value: Boolean); |
| 584 |
procedure SetSubdivisions(const Value: TVector2); |
| 585 |
procedure SetSize(const Value: TVector2); |
| 586 |
procedure SetQueryOffset(const Value: TVector2); |
| 587 |
function GetHeight(const Index: Integer): Single; |
| 588 |
procedure SetHeight(const Index: Integer; const Value: Single); |
| 589 |
procedure SetLayersInfluence(const Value: Single); |
| 590 |
procedure SetSteepEmphasize(const Value: Single); |
| 591 |
procedure SetPreciseCollisions(const Value: Boolean); |
| 592 |
private |
| 593 |
Scene: TCastleScene; |
| 594 |
UvScaleField, MetallicField, RoughnessField: TSFVec4f; |
| 595 |
protected |
| 596 |
procedure Loaded; override; |
| 597 |
public |
| 598 |
const |
| 599 |
DefaultSubdivisions = 64; |
| 600 |
DefaultSize = 100; |
| 601 |
DefaultHeight1 = 4.0; |
| 602 |
DefaultHeight2 = 8.0; |
| 603 |
{ Default values for @link(Height1), @link(Height2) etc. |
| 604 |
|
| 605 |
Note: This array duplicates information in constants |
| 606 |
@link(DefaultHeight1), @link(DefaultHeight2) etc. |
| 607 |
Unfortunately we need the simple constants too, to specify properties default values |
| 608 |
like "default DefaultHeight0". Using "default DefaultHeight[0]" doesn't work in FPC |
| 609 |
(nor in Delphi, but that's because Delphi cannot handle Single defaults at all). } |
| 610 |
DefaultHeight: array [1..HeightsCount] of Single = ( |
| 611 |
DefaultHeight1, |
| 612 |
DefaultHeight2 |
| 613 |
); |
| 614 |
DefaultLayersInfluence = 1.0; |
| 615 |
DefaultSteepEmphasize = 2.0; |
| 616 |
DefaultTriangulationIgnoreHeights = false; |
| 617 |
|
| 618 |
constructor Create(AOwner: TComponent); override; |
| 619 |
destructor Destroy; override; |
| 620 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 621 |
function HasColliderMesh: Boolean; override; |
| 622 |
procedure ColliderMesh(const TriangleEvent: TTriangleEvent); override; |
| 623 |
|
| 624 |
{ How dense is the mesh. |
| 625 |
By default this is (DefaultSubdivisions,DefaultSubdivisions). |
| 626 |
|
| 627 |
Changing this requires rebuild of terrain geometry, so it's costly. |
| 628 |
Avoid doing it at runtime. } |
| 629 |
property Subdivisions: TVector2 read FSubdivisions write SetSubdivisions; |
| 630 |
|
| 631 |
{ Size of the generated shape and also the underlying range to query |
| 632 |
the TCastleTerrainNoise data for heights. |
| 633 |
|
| 634 |
Note that changing this does not just scale the same geometry, |
| 635 |
if TCastleTerrainNoise is used for @link(Data). |
| 636 |
The TCastleTerrainNoise uses the size you set here to determine |
| 637 |
what heights to query from a smooth noise. |
| 638 |
This has a nice effect that increasing the size adds additional |
| 639 |
pieces of terrain adjacent to the previous terrain, |
| 640 |
and the previous terrain shape is still visible at the same place. |
| 641 |
|
| 642 |
Be sure to increase also @link(Subdivisions) when increasing |
| 643 |
this field, to keep seeing the same detail. |
| 644 |
|
| 645 |
By default this is (DefaultSize,DefaultSize). |
| 646 |
|
| 647 |
Changing this requires rebuild of terrain geometry, so it's costly. |
| 648 |
Avoid doing it at runtime. } |
| 649 |
property Size: TVector2 read FSize write SetSize; |
| 650 |
|
| 651 |
{ Offset the range of input values used to query the @link(Data). |
| 652 |
|
| 653 |
By default (when this is zero) we query the @link(TCastleTerrainData.Height) |
| 654 |
using @code(Coord) values ranging in X from -Size/2 to Size/2, |
| 655 |
similarly in Z. |
| 656 |
|
| 657 |
This vector offsets the range of queried values. |
| 658 |
|
| 659 |
It can be used to display a terrain noise matching neighboring terrain |
| 660 |
noise. } |
| 661 |
property QueryOffset: TVector2 read FQueryOffset write SetQueryOffset; |
| 662 |
|
| 663 |
property Triangulate: Boolean read FTriangulationIgnoreHeights write SetTriangulationIgnoreHeights; |
| 664 |
{$ifdef FPC}deprecated 'use TriangulationIgnoreHeights';{$endif} |
| 665 |
published |
| 666 |
{ Options used to render the terrain. Can be used e.g. to toggle wireframe rendering. } |
| 667 |
property RenderOptions: TCastleRenderOptions read GetRenderOptions; |
| 668 |
|
| 669 |
{ 1st layer is displayed on lower heights and more flat terrain. |
| 670 |
See TCastleTerrain for a full description how do we mix layers. } |
| 671 |
property Layer1: TCastleTerrainLayer index 1 read GetLayer; |
| 672 |
|
| 673 |
{ 2nd layer is displayed on lower heights and more steep terrain. |
| 674 |
See TCastleTerrain for a full description how do we mix layers. } |
| 675 |
property Layer2: TCastleTerrainLayer index 2 read GetLayer; |
| 676 |
|
| 677 |
{ 3rd layer is displayed on higher heights and more flat terrain. |
| 678 |
See TCastleTerrain for a full description how do we mix layers. } |
| 679 |
property Layer3: TCastleTerrainLayer index 3 read GetLayer; |
| 680 |
|
| 681 |
{ 4th layer is displayed on higher heights and more steep terrain. |
| 682 |
See TCastleTerrain for a full description how do we mix layers. } |
| 683 |
property Layer4: TCastleTerrainLayer index 4 read GetLayer; |
| 684 |
|
| 685 |
{ Data for terrain heights. |
| 686 |
Changing this requires rebuild of terrain geometry, so it's costly. |
| 687 |
Avoid doing it at runtime. } |
| 688 |
property Data: TCastleTerrainData read FData write SetData; |
| 689 |
|
| 690 |
{ Triangulate each terrain quad the same way. |
| 691 |
|
| 692 |
When @false (default) we make a triangulation that has a little better |
| 693 |
quality. Each quad is split into 2 triangles in a way along the shortest |
| 694 |
diagonal. |
| 695 |
|
| 696 |
When @true, all the quads are triangulated consistently, disregarding |
| 697 |
the heights. This looks a bit worse, but is more friendly to dynamic changes, |
| 698 |
since changing the heights doesn't change the topology. |
| 699 |
|
| 700 |
Changing this requires rebuild of terrain geometry, so it's costly. |
| 701 |
Avoid doing it at runtime. } |
| 702 |
property TriangulationIgnoreHeights: Boolean |
| 703 |
read FTriangulationIgnoreHeights write SetTriangulationIgnoreHeights |
| 704 |
default DefaultTriangulationIgnoreHeights; |
| 705 |
|
| 706 |
{ How much should we emphasize the "steep" layers (2nd and 4th layers) |
| 707 |
at the expense of "flat" layers (1st and 3rd). |
| 708 |
|
| 709 |
SteepEmphasize = 0.0 means that only "flat" layers (1 and 3) are visible. |
| 710 |
SteepEmphasize = 1.0 means that flat vs steep is a linear interpolation |
| 711 |
based on normal Y coordinate (but, since most terrains are more flat than |
| 712 |
steep, in practice the "flat" layers are still more visible). |
| 713 |
As SteepEmphasize goes toward infinity, the "steep" layers (2 and 4) dominate. } |
| 714 |
property SteepEmphasize: Single read FSteepEmphasize write SetSteepEmphasize |
| 715 |
{$ifdef FPC}default DefaultSteepEmphasize{$endif}; |
| 716 |
|
| 717 |
{ Below Height1 we only display layers 1+2. |
| 718 |
See TCastleTerrain for a description when do we show show layers and how this property affects it. } |
| 719 |
property Height1: Single index 1 read GetHeight write SetHeight {$ifdef FPC}default DefaultHeight1{$endif}; |
| 720 |
{ Above Height2 we only display layers 3+4. |
| 721 |
See TCastleTerrain for a description when do we show show layers and how this property affects it. } |
| 722 |
property Height2: Single index 2 read GetHeight write SetHeight {$ifdef FPC}default DefaultHeight2{$endif}; |
| 723 |
|
| 724 |
{ How much do the layers affect the final color. |
| 725 |
0.0 means that layes are ignored, and the terrain look is a regular |
| 726 |
mesh look with @link(TPhysicalMaterialNode). |
| 727 |
1.0 means maximum influence, the layers determine the base color |
| 728 |
(TODO: and normals in the future). } |
| 729 |
property LayersInfluence: Single read FLayersInfluence write SetLayersInfluence |
| 730 |
{$ifdef FPC}default DefaultLayersInfluence{$endif}; |
| 731 |
|
| 732 |
{ Resolve collisions precisely with the terrain geometry. |
| 733 |
When this is @false we will only consider the terrain bounding box for collisions, |
| 734 |
which prevents moving on terrain nicely, picking terrain points with mouse etc. |
| 735 |
This sets @link(TCastleSceneCore.Spatial). } |
| 736 |
property PreciseCollisions: Boolean read FPreciseCollisions write SetPreciseCollisions default true; |
| 737 |
|
| 738 |
{$define read_interface_class} |
| 739 |
{$I auto_generated_persistent_vectors/tcastleterrain_persistent_vectors.inc} |
| 740 |
{$undef read_interface_class} |
| 741 |
end; |
| 742 |
|
| 743 |
implementation |
| 744 |
|
| 745 |
uses Math, |
| 746 |
CastleUtils, CastleScriptParser, CastleInternalNoise, CastleDownload, CastleLog, |
| 747 |
CastleUriUtils, CastleComponentSerialize; |
| 748 |
|
| 749 |
{ TCastleTerrainData ------------------------------------------------------------------- } |
| 750 |
|
| 751 |
constructor TCastleTerrainData.Create(AOwner: TComponent); |
| 752 |
begin |
| 753 |
inherited; |
| 754 |
FChangeNotifications := TNotifyEventList.Create; |
| 755 |
end; |
| 756 |
|
| 757 |
destructor TCastleTerrainData.Destroy; |
| 758 |
begin |
| 759 |
FreeAndNil(FChangeNotifications); |
| 760 |
inherited; |
| 761 |
end; |
| 762 |
|
| 763 |
procedure TCastleTerrainData.DoChange; |
| 764 |
begin |
| 765 |
{ TODO: To fully avoid useless UpdateGeometry calls, |
| 766 |
avoid calling FChangeNotifications when IsLoading. |
| 767 |
Only schedule it and call when Loaded. } |
| 768 |
|
| 769 |
FChangeNotifications.ExecuteAll(Self); |
| 770 |
end; |
| 771 |
|
| 772 |
procedure TCastleTerrainData.AddChangeNotification(const Notify: TNotifyEvent); |
| 773 |
begin |
| 774 |
FChangeNotifications.Add(Notify); |
| 775 |
end; |
| 776 |
|
| 777 |
procedure TCastleTerrainData.RemoveChangeNotification(const Notify: TNotifyEvent); |
| 778 |
begin |
| 779 |
if FChangeNotifications = nil then |
| 780 |
begin |
| 781 |
{ This can happen when we free the TCastleTerrainData (like TCastleTerrainNoise) |
| 782 |
that is referenced in some TCastleTerrain.Data. |
| 783 |
Then TCastleTerrainData.Destroy does "FreeAndNil(FChangeNotifications)" |
| 784 |
first, then calls inherited destructor, that sends DataFreeNotification |
| 785 |
to TCastleTerrain which in turn in SetData does RemoveChangeNotification. |
| 786 |
So this all can happen in valid situation and can be just ignored. |
| 787 |
When FChangeNotifications = nil it means we're freeing ourselves |
| 788 |
and we no longer care about tracking FChangeNotifications. } |
| 789 |
Assert(csDestroying in ComponentState); |
| 790 |
Exit; |
| 791 |
end; |
| 792 |
FChangeNotifications.Remove(Notify); |
| 793 |
end; |
| 794 |
|
| 795 |
function TCastleTerrainData.CreateNode(const Subdivisions: TVector2; |
| 796 |
const InputRange, OutputRange: TFloatRectangle; |
| 797 |
const Appearance: TAppearanceNode; |
| 798 |
const TriangulationIgnoreHeights: Boolean): TAbstractChildNode; |
| 799 |
begin |
| 800 |
Result := TTransformNode.Create; |
| 801 |
UpdateNodeCore(Result, Subdivisions, InputRange, OutputRange, Appearance, |
| 802 |
TriangulationIgnoreHeights); |
| 803 |
end; |
| 804 |
|
| 805 |
procedure TCastleTerrainData.UpdateNode(const Node: TAbstractChildNode; |
| 806 |
const Subdivisions: TVector2; const InputRange, OutputRange: TFloatRectangle; |
| 807 |
const TriangulationIgnoreHeights: Boolean); |
| 808 |
var |
| 809 |
Transform: TTransformNode; |
| 810 |
Shape: TShapeNode; |
| 811 |
Appearance: TAppearanceNode; |
| 812 |
begin |
| 813 |
{ extract Appearance from Node, assuming Node was created by CreateNode } |
| 814 |
Transform := Node as TTransformNode; |
| 815 |
Shape := Transform.FdChildren[0] as TShapeNode; |
| 816 |
Appearance := Shape.Appearance; |
| 817 |
|
| 818 |
Appearance.KeepExistingBegin; |
| 819 |
UpdateNodeCore(Node, Subdivisions, InputRange, OutputRange, Appearance, |
| 820 |
TriangulationIgnoreHeights); |
| 821 |
Appearance.KeepExistingEnd; |
| 822 |
end; |
| 823 |
|
| 824 |
procedure TCastleTerrainData.UpdateNodeCore(const Node: TAbstractChildNode; |
| 825 |
const Subdivisions: TVector2; const InputRange, OutputRange: TFloatRectangle; |
| 826 |
const Appearance: TAppearanceNode; const TriangulationIgnoreHeights: Boolean); |
| 827 |
var |
| 828 |
XDimension, ZDimension: Cardinal; |
| 829 |
|
| 830 |
{ Calculate height for given terrain point. |
| 831 |
Returns also coordinate and texture coordinate of this point. |
| 832 |
|
| 833 |
Note: coordinate in InputCoord does *not* equal, in XZ, the local coordinates |
| 834 |
that will be calculated by TElevationGridNode.InternalCreateTriangles. |
| 835 |
This coordinate is in input range, InputRange. |
| 836 |
|
| 837 |
In contrast, the local coordinates calculated by TElevationGridNode.InternalCreateTriangles |
| 838 |
are partially in output range: they take into account OutputRange.Width/Height. |
| 839 |
They do not take into account OutputRange.Left, OutputRange.Bottom |
| 840 |
which is applied by the transfomaion node. } |
| 841 |
function GetHeight(const X, Z: Single; out InputCoord, TexCoord: TVector2): Single; |
| 842 |
begin |
| 843 |
TexCoord := Vector2( |
| 844 |
MapRangeTo01(X, 0, XDimension - 1), |
| 845 |
MapRangeTo01(Z, 0, ZDimension - 1) |
| 846 |
); |
| 847 |
InputCoord := Vector2( |
| 848 |
Lerp(TexCoord.X, InputRange.Left , InputRange.Right), |
| 849 |
Lerp(TexCoord.Y, InputRange.Bottom, InputRange.Top) |
| 850 |
); |
| 851 |
// TexCoord.Y grows in different direction, see Height docs for reason |
| 852 |
TexCoord.Y := 1 - TexCoord.Y; |
| 853 |
Result := Height(InputCoord, TexCoord); |
| 854 |
end; |
| 855 |
|
| 856 |
{ Calculate 3D coordinate for given terrain point. |
| 857 |
The XZ of this corresponds to the InputRange, |
| 858 |
these are *not* 3D coordinates that will be |
| 859 |
calculated by TElevationGridNode.InternalCreateTriangles. } |
| 860 |
function GetInputCoord3D(const X, Z: Single): TVector3; |
| 861 |
var |
| 862 |
InputCoord, IgnoredTexCoord: TVector2; |
| 863 |
begin |
| 864 |
Result.Y := GetHeight(X, Z, InputCoord, IgnoredTexCoord); |
| 865 |
Result.X := InputCoord.X; |
| 866 |
Result.Z := InputCoord.Y; |
| 867 |
end; |
| 868 |
|
| 869 |
{ Calculate normal at given terrain point. |
| 870 |
|
| 871 |
Generating normals on our side, instead of letting TIndexedTriangleSetNode |
| 872 |
algorithm to calculate them. Reasons: |
| 873 |
|
| 874 |
- This is faster. TIndexedTriangleSetNode has to consider general case, |
| 875 |
multiple triangles sharing a vertex in a general mesh. |
| 876 |
We can optimize for our case, a grid of vertexes. |
| 877 |
|
| 878 |
- On the edges, we can calculate normals in a more predictable way. |
| 879 |
This makes placing one terrain next to another result in smooth lighting |
| 880 |
where the terrains meet. } |
| 881 |
function GetNormal(const X, Z: Integer): TVector3; |
| 882 |
var |
| 883 |
P, PX, PZ: TVector3; |
| 884 |
begin |
| 885 |
// P := GetInputCoord3D(X, Z); |
| 886 |
// PX := GetInputCoord3D(X + 1, Z); |
| 887 |
// PZ := GetInputCoord3D(X, Z + 1); |
| 888 |
// sample around the point, this way we don't make normal reflecting only one side |
| 889 |
P := GetInputCoord3D(X - 0.5, Z - 0.5); |
| 890 |
PX := GetInputCoord3D(X + 0.5, Z - 0.5); |
| 891 |
PZ := GetInputCoord3D(X - 0.5, Z + 0.5); |
| 892 |
Result := TVector3.CrossProduct( |
| 893 |
(PZ - P), |
| 894 |
(PX - P)).Normalize; |
| 895 |
end; |
| 896 |
|
| 897 |
var |
| 898 |
Transform: TTransformNode; |
| 899 |
Normal: TNormalNode; |
| 900 |
Shape: TShapeNode; |
| 901 |
TriangleSet: TIndexedTriangleSetNode; |
| 902 |
X, Z: Cardinal; |
| 903 |
IgnoredInputCoord, IgnoredTexCoord: TVector2; |
| 904 |
Heights: TSingleList; |
| 905 |
begin |
| 906 |
XDimension := Round(Subdivisions.X) + 1; |
| 907 |
ZDimension := Round(Subdivisions.Y) + 1; |
| 908 |
|
| 909 |
Transform := Node as TTransformNode; // created by CreateNode |
| 910 |
Transform.ClearChildren; |
| 911 |
Transform.Translation := Vector3(OutputRange.Left, 0, OutputRange.Bottom); |
| 912 |
|
| 913 |
Shape := TShapeNode.Create; |
| 914 |
|
| 915 |
Heights := TSingleList.Create; |
| 916 |
try |
| 917 |
// calculate Heights |
| 918 |
Heights.Count := XDimension * ZDimension; |
| 919 |
for X := 0 to XDimension - 1 do |
| 920 |
for Z := 0 to ZDimension - 1 do |
| 921 |
begin |
| 922 |
Heights.L[X + Z * XDimension] := GetHeight(X, Z, IgnoredInputCoord, IgnoredTexCoord); |
| 923 |
end; |
| 924 |
|
| 925 |
TriangleSet := TElevationGridNode.InternalCreateTriangles( |
| 926 |
XDimension, |
| 927 |
ZDimension, |
| 928 |
OutputRange.Width / (XDimension - 1), |
| 929 |
OutputRange.Height / (ZDimension - 1), |
| 930 |
Heights, |
| 931 |
nil, |
| 932 |
TriangulationIgnoreHeights |
| 933 |
); |
| 934 |
finally FreeAndNil(Heights) end; |
| 935 |
|
| 936 |
// calculate Normal (for TriangleSet.Normal) |
| 937 |
Normal := TNormalNode.Create; |
| 938 |
Normal.FdVector.Items.Count := XDimension * ZDimension; |
| 939 |
for X := 0 to XDimension - 1 do |
| 940 |
for Z := 0 to ZDimension - 1 do |
| 941 |
Normal.FdVector.Items.L[X + Z * XDimension] := GetNormal(X, Z); |
| 942 |
TriangleSet.Normal := Normal; |
| 943 |
|
| 944 |
Shape.Geometry := TriangleSet; |
| 945 |
Shape.Appearance := Appearance; |
| 946 |
|
| 947 |
// at the end, as this may cause Scene.ChangedAll |
| 948 |
Transform.AddChildren(Shape); |
| 949 |
end; |
| 950 |
|
| 951 |
{ TCastleTerrainImage ------------------------------------------------------------ } |
| 952 |
|
| 953 |
constructor TCastleTerrainImage.Create(AOwner: TComponent); |
| 954 |
begin |
| 955 |
inherited; |
| 956 |
FMinLevel := -0.5; |
| 957 |
FMaxLevel := 0.5; |
| 958 |
end; |
| 959 |
|
| 960 |
destructor TCastleTerrainImage.Destroy; |
| 961 |
begin |
| 962 |
FreeAndNil(FImage); |
| 963 |
inherited; |
| 964 |
end; |
| 965 |
|
| 966 |
procedure TCastleTerrainImage.SetUrl(const Value: String); |
| 967 |
|
| 968 |
procedure LoadImage(const NewUrl: String); |
| 969 |
var |
| 970 |
NewImage: TGrayscaleFloatImage; |
| 971 |
begin |
| 972 |
if NewUrl = '' then |
| 973 |
NewImage := nil |
| 974 |
else |
| 975 |
begin |
| 976 |
{ Read as TGrayscaleFloatImage. |
| 977 |
Allows to read high-precision data from image formats that support it, |
| 978 |
like 16-bit PNG, 16/32-bit TIFF, OpenEXR in the future. |
| 979 |
The 8-bit formats will be converted to TGrayscaleFloatImage by |
| 980 |
TGrayscaleFloatImage.Assign. } |
| 981 |
NewImage := CastleImages.LoadImage(NewUrl, [TGrayscaleFloatImage]) |
| 982 |
as TGrayscaleFloatImage; |
| 983 |
end; |
| 984 |
|
| 985 |
FreeAndNil(FImage); |
| 986 |
FImage := NewImage; |
| 987 |
FUrl := NewUrl; |
| 988 |
DoChange; |
| 989 |
end; |
| 990 |
|
| 991 |
begin |
| 992 |
if FUrl <> Value then |
| 993 |
begin |
| 994 |
try |
| 995 |
LoadImage(Value); // in case of exception when loading, LoadImage leaves state unchanged |
| 996 |
except |
| 997 |
{ If loading file failed, and we're inside CGE editor, merely report a warning. |
| 998 |
This allows deserializing in CGE editor designs with broken URLs. } |
| 999 |
on E: Exception do |
| 1000 |
begin |
| 1001 |
if CastleDesignMode then |
| 1002 |
begin |
| 1003 |
WritelnWarning('TCastleTerrainImage', 'Failed to load image "%s": %s', [ |
| 1004 |
UriDisplay(Value), |
| 1005 |
ExceptMessage(E) |
| 1006 |
]); |
| 1007 |
end else |
| 1008 |
raise; |
| 1009 |
end; |
| 1010 |
end; |
| 1011 |
end; |
| 1012 |
end; |
| 1013 |
|
| 1014 |
function TCastleTerrainImage.Height(const Coord, TexCoord: TVector2): Single; |
| 1015 |
var |
| 1016 |
PX, PY: Integer; |
| 1017 |
Intensity: Single; |
| 1018 |
begin |
| 1019 |
if FImage <> nil then |
| 1020 |
begin |
| 1021 |
PX := Floor(TexCoord.X * FImage.Width ); |
| 1022 |
PY := Floor(TexCoord.Y * FImage.Height); |
| 1023 |
ClampVar(PX, 0, FImage.Width - 1); |
| 1024 |
ClampVar(PY, 0, FImage.Height - 1); |
| 1025 |
Intensity := FImage.PixelPtr(PX, PY)^; |
| 1026 |
end else |
| 1027 |
Intensity := 0.5; |
| 1028 |
Result := Lerp(Intensity, MinLevel, MaxLevel); |
| 1029 |
end; |
| 1030 |
|
| 1031 |
procedure TCastleTerrainImage.SetMinLevel(const Value: Single); |
| 1032 |
begin |
| 1033 |
if FMinLevel <> Value then |
| 1034 |
begin |
| 1035 |
FMinLevel := Value; |
| 1036 |
DoChange; |
| 1037 |
end; |
| 1038 |
end; |
| 1039 |
|
| 1040 |
procedure TCastleTerrainImage.SetMaxLevel(const Value: Single); |
| 1041 |
begin |
| 1042 |
if FMaxLevel <> Value then |
| 1043 |
begin |
| 1044 |
FMaxLevel := Value; |
| 1045 |
DoChange; |
| 1046 |
end; |
| 1047 |
end; |
| 1048 |
|
| 1049 |
function TCastleTerrainImage.PropertySections(const PropertyName: String): TPropertySections; |
| 1050 |
begin |
| 1051 |
if ArrayContainsString(PropertyName, [ |
| 1052 |
'Url', 'MinLevel', 'MaxLevel' |
| 1053 |
]) then |
| 1054 |
Result := [psBasic] |
| 1055 |
else |
| 1056 |
Result := inherited PropertySections(PropertyName); |
| 1057 |
end; |
| 1058 |
|
| 1059 |
{ TTerrainCasScript -------------------------------------------------------- } |
| 1060 |
|
| 1061 |
constructor TTerrainCasScript.Create(const FunctionExpression: String); |
| 1062 |
begin |
| 1063 |
inherited Create(nil); |
| 1064 |
|
| 1065 |
FXVariable := TCasScriptFloat.Create(false); |
| 1066 |
FXVariable.Name := 'x'; |
| 1067 |
FXVariable.OwnedByParentExpression := false; |
| 1068 |
|
| 1069 |
FYVariable := TCasScriptFloat.Create(false); |
| 1070 |
FYVariable.Name := 'y'; |
| 1071 |
FYVariable.OwnedByParentExpression := false; |
| 1072 |
|
| 1073 |
FFunction := ParseFloatExpression(FunctionExpression, [FXVariable, FYVariable]); |
| 1074 |
end; |
| 1075 |
|
| 1076 |
destructor TTerrainCasScript.Destroy; |
| 1077 |
begin |
| 1078 |
FFunction.FreeByParentExpression; |
| 1079 |
FFunction := nil; |
| 1080 |
|
| 1081 |
FreeAndNil(FXVariable); |
| 1082 |
FreeAndNil(FYVariable); |
| 1083 |
|
| 1084 |
inherited; |
| 1085 |
end; |
| 1086 |
|
| 1087 |
function TTerrainCasScript.Height(const Coord, TexCoord: TVector2): Single; |
| 1088 |
begin |
| 1089 |
FXVariable.Value := Coord.X; |
| 1090 |
FYVariable.Value := Coord.Y; |
| 1091 |
Result := (FFunction.Execute as TCasScriptFloat).Value; |
| 1092 |
end; |
| 1093 |
|
| 1094 |
{ TCastleTerrainNoise ------------------------------------------------------------ } |
| 1095 |
|
| 1096 |
constructor TCastleTerrainNoise.Create(AOwner: TComponent); |
| 1097 |
begin |
| 1098 |
inherited; |
| 1099 |
|
| 1100 |
FOctaves := DefaultOctaves; |
| 1101 |
FSmoothness := DefaultSmoothnes; |
| 1102 |
FAmplitude := DefaultAmplitude; |
| 1103 |
FFrequency := DefaultFrequency; |
| 1104 |
FInterpolation := DefaultInterpolation; |
| 1105 |
FBlur := DefaultBlur; |
| 1106 |
FHeterogeneous := DefaultHeterogeneous; |
| 1107 |
|
| 1108 |
UpdateNoiseMethod; |
| 1109 |
end; |
| 1110 |
|
| 1111 |
procedure TCastleTerrainNoise.UpdateNoiseMethod; |
| 1112 |
begin |
| 1113 |
if Blur then |
| 1114 |
case Interpolation of |
| 1115 |
niNone: NoiseMethod := @BlurredInterpolatedNoise2D_None; |
| 1116 |
niLinear: NoiseMethod := @BlurredInterpolatedNoise2D_Linear; |
| 1117 |
niCosine: NoiseMethod := @BlurredInterpolatedNoise2D_Cosine; |
| 1118 |
niSpline: NoiseMethod := @BlurredInterpolatedNoise2D_Spline; |
| 1119 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 1120 |
else raise EInternalError.Create('TCastleTerrainNoise.UpdateNoiseMethod(Interpolation?)'); |
| 1121 |
{$endif} |
| 1122 |
end else |
| 1123 |
case Interpolation of |
| 1124 |
niNone: NoiseMethod := @InterpolatedNoise2D_None; |
| 1125 |
niLinear: NoiseMethod := @InterpolatedNoise2D_Linear; |
| 1126 |
niCosine: NoiseMethod := @InterpolatedNoise2D_Cosine; |
| 1127 |
niSpline: NoiseMethod := @InterpolatedNoise2D_Spline; |
| 1128 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 1129 |
else raise EInternalError.Create('TCastleTerrainNoise.UpdateNoiseMethod(Interpolation?)'); |
| 1130 |
{$endif} |
| 1131 |
end; |
| 1132 |
end; |
| 1133 |
|
| 1134 |
procedure TCastleTerrainNoise.SetOctaves(const Value: Single); |
| 1135 |
begin |
| 1136 |
if FOctaves <> Value then |
| 1137 |
begin |
| 1138 |
FOctaves := Value; |
| 1139 |
DoChange; |
| 1140 |
end; |
| 1141 |
end; |
| 1142 |
|
| 1143 |
procedure TCastleTerrainNoise.SetSmoothness(const Value: Single); |
| 1144 |
begin |
| 1145 |
if FSmoothness <> Value then |
| 1146 |
begin |
| 1147 |
FSmoothness := Value; |
| 1148 |
DoChange; |
| 1149 |
end; |
| 1150 |
end; |
| 1151 |
|
| 1152 |
procedure TCastleTerrainNoise.SetAmplitude(const Value: Single); |
| 1153 |
begin |
| 1154 |
if FAmplitude <> Value then |
| 1155 |
begin |
| 1156 |
FAmplitude := Value; |
| 1157 |
DoChange; |
| 1158 |
end; |
| 1159 |
end; |
| 1160 |
|
| 1161 |
procedure TCastleTerrainNoise.SetFrequency(const Value: Single); |
| 1162 |
begin |
| 1163 |
if FFrequency <> Value then |
| 1164 |
begin |
| 1165 |
FFrequency := Value; |
| 1166 |
DoChange; |
| 1167 |
end; |
| 1168 |
end; |
| 1169 |
|
| 1170 |
procedure TCastleTerrainNoise.SetInterpolation(const Value: TNoiseInterpolation); |
| 1171 |
begin |
| 1172 |
if FInterpolation <> Value then |
| 1173 |
begin |
| 1174 |
FInterpolation := Value; |
| 1175 |
UpdateNoiseMethod; |
| 1176 |
DoChange; |
| 1177 |
end; |
| 1178 |
end; |
| 1179 |
|
| 1180 |
procedure TCastleTerrainNoise.SetBlur(const Value: Boolean); |
| 1181 |
begin |
| 1182 |
if FBlur <> Value then |
| 1183 |
begin |
| 1184 |
FBlur := Value; |
| 1185 |
UpdateNoiseMethod; |
| 1186 |
DoChange; |
| 1187 |
end; |
| 1188 |
end; |
| 1189 |
|
| 1190 |
procedure TCastleTerrainNoise.SetSeed(const Value: Cardinal); |
| 1191 |
begin |
| 1192 |
if FSeed <> Value then |
| 1193 |
begin |
| 1194 |
FSeed := Value; |
| 1195 |
DoChange; |
| 1196 |
end; |
| 1197 |
end; |
| 1198 |
|
| 1199 |
procedure TCastleTerrainNoise.SetHeterogeneous(const Value: Single); |
| 1200 |
begin |
| 1201 |
if FHeterogeneous <> Value then |
| 1202 |
begin |
| 1203 |
FHeterogeneous := Value; |
| 1204 |
DoChange; |
| 1205 |
end; |
| 1206 |
end; |
| 1207 |
|
| 1208 |
function TCastleTerrainNoise.Height(const Coord, TexCoord: TVector2): Single; |
| 1209 |
// const |
| 1210 |
// { Idea, maybe useful --- apply heterogeneous only on higher octaves. |
| 1211 |
// Note that 1st octave is anyway always without heterogeneous, |
| 1212 |
// so this is really useful only if setting to >= 2. } |
| 1213 |
// HomogeneousOctaves = 2; |
| 1214 |
var |
| 1215 |
A, F, NoiseAccumulator: Single; |
| 1216 |
|
| 1217 |
function NextOctave(const OctaveNumber: Cardinal): Single; |
| 1218 |
begin |
| 1219 |
{ An explicit check for "Heterogeneous = 0" case is needed. |
| 1220 |
|
| 1221 |
Otherwise, when Heterogeneous = 0, "NoiseAccumulator /= Heterogeneous" |
| 1222 |
calculates "0 / 0", which will not get us what we want. |
| 1223 |
(What we want is to have NoiseAccumulator=+infinity, |
| 1224 |
so that it gets clamped to 1, but it seems FPC 2.2.4 doesn't do this. |
| 1225 |
FPC 2.4.0 seems to land on +infinity more often, |
| 1226 |
but not when using Spline interpolation... Looks like "0 / 0" |
| 1227 |
is simply undefined, and unsafe to use.) |
| 1228 |
|
| 1229 |
Note there's no need to check for IsZero(Heterogeneous). |
| 1230 |
When Heterogeneous is close to zero, but not exactly zero, |
| 1231 |
the +infinity trick will make the later code behave Ok. } |
| 1232 |
if Heterogeneous = 0 then |
| 1233 |
Exit(NoiseMethod( |
| 1234 |
Coord.X * F, |
| 1235 |
Coord.Y * F, OctaveNumber + Seed) * A); |
| 1236 |
|
| 1237 |
NoiseAccumulator := NoiseAccumulator / Heterogeneous; |
| 1238 |
{ Following Musgrave's dissertation, we should now force |
| 1239 |
NoiseAccumulator to <0, 1> range. |
| 1240 |
We know our NoiseMethod is always positive, and we require |
| 1241 |
Amplitude, Heterogeneous and such to also be always positive. |
| 1242 |
So we already know NoiseAccumulator is always >= 0. } |
| 1243 |
MinVar(NoiseAccumulator, 1); |
| 1244 |
|
| 1245 |
NoiseAccumulator := NoiseAccumulator * NoiseMethod( |
| 1246 |
Coord.X * F, |
| 1247 |
Coord.Y * F, OctaveNumber + Seed); |
| 1248 |
|
| 1249 |
Result := NoiseAccumulator * A; |
| 1250 |
end; |
| 1251 |
|
| 1252 |
var |
| 1253 |
I: Cardinal; |
| 1254 |
begin |
| 1255 |
Result := 0; |
| 1256 |
|
| 1257 |
A := Amplitude; |
| 1258 |
F := Frequency; |
| 1259 |
{ This will accumulate multiplication of noise octaves. |
| 1260 |
Initial value is chosen so that at first step (I = 1) |
| 1261 |
NoiseAccumulator will become 1.0, and then NoiseMethod() * A. } |
| 1262 |
NoiseAccumulator := Heterogeneous; |
| 1263 |
for I := 1 to Trunc(Octaves) do |
| 1264 |
begin |
| 1265 |
Result := Result + NextOctave(I); |
| 1266 |
F := F * 2; |
| 1267 |
A := A / Smoothness; |
| 1268 |
end; |
| 1269 |
|
| 1270 |
{ Add last octave's remainder. |
| 1271 |
Just like a normal octave, but multiply by Frac(Octaves). } |
| 1272 |
Result := Result + Frac(Octaves) * NextOctave(Trunc(Octaves) + 1); |
| 1273 |
end; |
| 1274 |
|
| 1275 |
function TCastleTerrainNoise.PropertySections(const PropertyName: String): TPropertySections; |
| 1276 |
begin |
| 1277 |
if ArrayContainsString(PropertyName, [ |
| 1278 |
'Octaves', 'Smoothness', 'Amplitude', 'Frequency', 'Interpolation', 'Blur', 'Seed', 'Heterogeneous' |
| 1279 |
]) then |
| 1280 |
Result := [psBasic] |
| 1281 |
else |
| 1282 |
Result := inherited PropertySections(PropertyName); |
| 1283 |
end; |
| 1284 |
|
| 1285 |
{ TCastleTerrainCombine ------------------------------------------------------ } |
| 1286 |
|
| 1287 |
function CombineOperationMax(const A, B: Single): Single; |
| 1288 |
begin |
| 1289 |
Result := Max(A, B); |
| 1290 |
end; |
| 1291 |
|
| 1292 |
function CombineOperationMin(const A, B: Single): Single; |
| 1293 |
begin |
| 1294 |
Result := Min(A, B); |
| 1295 |
end; |
| 1296 |
|
| 1297 |
function CombineOperationAdd(const A, B: Single): Single; |
| 1298 |
begin |
| 1299 |
Result := A + B; |
| 1300 |
end; |
| 1301 |
|
| 1302 |
function CombineOperationMultiply(const A, B: Single): Single; |
| 1303 |
begin |
| 1304 |
Result := A * B; |
| 1305 |
end; |
| 1306 |
|
| 1307 |
constructor TCastleTerrainCombine.Create(AOwner: TComponent); |
| 1308 |
begin |
| 1309 |
inherited; |
| 1310 |
FData1Observer := TFreeNotificationObserver.Create(Self); |
| 1311 |
FData1Observer.OnFreeNotification := {$ifdef FPC}@{$endif} Data1FreeNotification; |
| 1312 |
FData2Observer := TFreeNotificationObserver.Create(Self); |
| 1313 |
FData2Observer.OnFreeNotification := {$ifdef FPC}@{$endif} Data2FreeNotification; |
| 1314 |
FOperation := DefaultOperation; |
| 1315 |
UpdateOperationFunc; |
| 1316 |
end; |
| 1317 |
|
| 1318 |
procedure TCastleTerrainCombine.UpdateOperationFunc; |
| 1319 |
begin |
| 1320 |
case FOperation of |
| 1321 |
opMax: FOperationFunc := {$ifdef FPC}@{$endif} CombineOperationMax; |
| 1322 |
opMin: FOperationFunc := {$ifdef FPC}@{$endif} CombineOperationMin; |
| 1323 |
opAdd: FOperationFunc := {$ifdef FPC}@{$endif} CombineOperationAdd; |
| 1324 |
opMultiply: FOperationFunc := {$ifdef FPC}@{$endif} CombineOperationMultiply; |
| 1325 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 1326 |
else raise EInternalError.Create('TCastleTerrainCombine.UpdateOperationFunc?'); |
| 1327 |
{$endif} |
| 1328 |
end; |
| 1329 |
end; |
| 1330 |
|
| 1331 |
procedure TCastleTerrainCombine.SetOperation(const Value: TCastleTerrainCombineOperation); |
| 1332 |
begin |
| 1333 |
if FOperation <> Value then |
| 1334 |
begin |
| 1335 |
FOperation := Value; |
| 1336 |
UpdateOperationFunc; |
| 1337 |
DoChange; |
| 1338 |
end; |
| 1339 |
end; |
| 1340 |
|
| 1341 |
function TCastleTerrainCombine.Height(const Coord, TexCoord: TVector2): Single; |
| 1342 |
begin |
| 1343 |
if (Data1 <> nil) and (Data2 <> nil) then |
| 1344 |
begin |
| 1345 |
Result := FOperationFunc( |
| 1346 |
Data1.Height(Coord, TexCoord), |
| 1347 |
Data2.Height(Coord, TexCoord) |
| 1348 |
); |
| 1349 |
end else |
| 1350 |
if Data1 <> nil then |
| 1351 |
Result := Data1.Height(Coord, TexCoord) |
| 1352 |
else |
| 1353 |
if Data2 <> nil then |
| 1354 |
Result := Data2.Height(Coord, TexCoord) |
| 1355 |
else |
| 1356 |
Result := 0; |
| 1357 |
end; |
| 1358 |
|
| 1359 |
function TCastleTerrainCombine.PropertySections(const PropertyName: String): TPropertySections; |
| 1360 |
begin |
| 1361 |
if ArrayContainsString(PropertyName, [ |
| 1362 |
'Data1', 'Data2', 'Operation' |
| 1363 |
]) then |
| 1364 |
Result := [psBasic] |
| 1365 |
else |
| 1366 |
Result := inherited PropertySections(PropertyName); |
| 1367 |
end; |
| 1368 |
|
| 1369 |
procedure TCastleTerrainCombine.Data1FreeNotification(const Sender: TFreeNotificationObserver); |
| 1370 |
begin |
| 1371 |
Data1 := nil; |
| 1372 |
end; |
| 1373 |
|
| 1374 |
procedure TCastleTerrainCombine.Data2FreeNotification(const Sender: TFreeNotificationObserver); |
| 1375 |
begin |
| 1376 |
Data2 := nil; |
| 1377 |
end; |
| 1378 |
|
| 1379 |
procedure TCastleTerrainCombine.Data1Changed(Sender: TObject); |
| 1380 |
begin |
| 1381 |
DoChange; |
| 1382 |
end; |
| 1383 |
|
| 1384 |
procedure TCastleTerrainCombine.Data2Changed(Sender: TObject); |
| 1385 |
begin |
| 1386 |
DoChange; |
| 1387 |
end; |
| 1388 |
|
| 1389 |
function ContainsData(const Tree, ValueToFind: TCastleTerrainData): Boolean; |
| 1390 |
begin |
| 1391 |
Result := |
| 1392 |
(Tree = ValueToFind) or |
| 1393 |
( |
| 1394 |
(Tree is TCastleTerrainCombine) and ( |
| 1395 |
ContainsData(TCastleTerrainCombine(Tree).Data1, ValueToFind) or |
| 1396 |
ContainsData(TCastleTerrainCombine(Tree).Data2, ValueToFind) |
| 1397 |
) |
| 1398 |
); |
| 1399 |
end; |
| 1400 |
|
| 1401 |
procedure TCastleTerrainCombine.SetData1(const Value: TCastleTerrainData); |
| 1402 |
begin |
| 1403 |
if FData1 <> Value then |
| 1404 |
begin |
| 1405 |
{ Ignore nonsense assignment done by FpRttiJson when this node references |
| 1406 |
in JSON non-yet-known name. See TCastleTerrain.SetData comments. } |
| 1407 |
if (Value <> nil) and |
| 1408 |
(Value.ClassType = TCastleTerrainData) then |
| 1409 |
Exit; |
| 1410 |
|
| 1411 |
// Protect from recursive usage hanging the process (editor or runtime) |
| 1412 |
if (Value <> nil) and |
| 1413 |
ContainsData(Value, Self) then |
| 1414 |
begin |
| 1415 |
raise Exception.CreateFmt('Setting %s as data for %s would make a recursive dependency (infinite calculation) in TCastleTerrainCombine', [ |
| 1416 |
Value.Name, |
| 1417 |
Name |
| 1418 |
]); |
| 1419 |
Exit; |
| 1420 |
end; |
| 1421 |
|
| 1422 |
if FData1 <> nil then |
| 1423 |
FData1.RemoveChangeNotification({$ifdef FPC}@{$endif} Data1Changed); |
| 1424 |
FData1 := Value; |
| 1425 |
FData1Observer.Observed := Value; |
| 1426 |
if FData1 <> nil then |
| 1427 |
FData1.AddChangeNotification({$ifdef FPC}@{$endif} Data1Changed); |
| 1428 |
DoChange; |
| 1429 |
end; |
| 1430 |
end; |
| 1431 |
|
| 1432 |
procedure TCastleTerrainCombine.SetData2(const Value: TCastleTerrainData); |
| 1433 |
begin |
| 1434 |
if FData2 <> Value then |
| 1435 |
begin |
| 1436 |
{ Ignore nonsense assignment done by FpRttiJson when this node references |
| 1437 |
in JSON non-yet-known name. See TCastleTerrain.SetData comments. } |
| 1438 |
if (Value <> nil) and |
| 1439 |
(Value.ClassType = TCastleTerrainData) then |
| 1440 |
Exit; |
| 1441 |
|
| 1442 |
// Protect from recursive usage hanging the process (editor or runtime) |
| 1443 |
if (Value <> nil) and |
| 1444 |
ContainsData(Value, Self) then |
| 1445 |
begin |
| 1446 |
raise Exception.CreateFmt('Setting %s and data for %s would make a recursive dependency (infinite calculation) in TCastleTerrainCombine', [ |
| 1447 |
Value.Name, |
| 1448 |
Name |
| 1449 |
]); |
| 1450 |
Exit; |
| 1451 |
end; |
| 1452 |
|
| 1453 |
if FData2 <> nil then |
| 1454 |
FData2.RemoveChangeNotification({$ifdef FPC}@{$endif} Data2Changed); |
| 1455 |
FData2 := Value; |
| 1456 |
FData2Observer.Observed := Value; |
| 1457 |
if FData2 <> nil then |
| 1458 |
FData2.AddChangeNotification({$ifdef FPC}@{$endif} Data2Changed); |
| 1459 |
DoChange; |
| 1460 |
end; |
| 1461 |
end; |
| 1462 |
|
| 1463 |
{ TCastleTerrainLayer -------------------------------------------------------- } |
| 1464 |
|
| 1465 |
const |
| 1466 |
{ URL of a white pixel texture, embedded PPM. |
| 1467 |
See http://netpbm.sourceforge.net/doc/ppm.html . } |
| 1468 |
WhitePixel = 'data:image/x-portable-pixmap,P3'#10 + |
| 1469 |
'1 1'#10 + |
| 1470 |
'255'#10 + |
| 1471 |
'255 255 255'; |
| 1472 |
|
| 1473 |
constructor TCastleTerrainLayer.Create(AOwner: TComponent); |
| 1474 |
begin |
| 1475 |
inherited; |
| 1476 |
raise Exception.Create('TCastleTerrainLayer can only be instantiated by TCastleTerrain as a subcomponent'); |
| 1477 |
end; |
| 1478 |
|
| 1479 |
constructor TCastleTerrainLayer.CreateForTerrain(const ATerrain: TCastleTerrain; |
| 1480 |
const ALayer: Integer; const Effect: TEffectNode); |
| 1481 |
var |
| 1482 |
TextureField: TSFNode; |
| 1483 |
begin |
| 1484 |
inherited Create(ATerrain); |
| 1485 |
Terrain := ATerrain; |
| 1486 |
Layer := ALayer; |
| 1487 |
|
| 1488 |
TextureNode := TImageTextureNode.Create; |
| 1489 |
TextureNode.SetUrl([WhitePixel]); |
| 1490 |
TextureField := TSFNode.Create(Effect, false, 'tex_' + IntToStr(Layer), [], TextureNode); |
| 1491 |
Effect.AddCustomField(TextureField); |
| 1492 |
|
| 1493 |
|
| 1494 |
ColorField := TSFColor.Create(Effect, true, 'color_' + IntToStr(Layer), WhiteRGB); |
| 1495 |
Effect.AddCustomField(ColorField); |
| 1496 |
|
| 1497 |
{$define read_implementation_constructor} |
| 1498 |
{$I auto_generated_persistent_vectors/tcastleterrainlayer_persistent_vectors.inc} |
| 1499 |
{$undef read_implementation_constructor} |
| 1500 |
end; |
| 1501 |
|
| 1502 |
destructor TCastleTerrainLayer.Destroy; |
| 1503 |
begin |
| 1504 |
{$define read_implementation_destructor} |
| 1505 |
{$I auto_generated_persistent_vectors/tcastleterrainlayer_persistent_vectors.inc} |
| 1506 |
{$undef read_implementation_destructor} |
| 1507 |
inherited; |
| 1508 |
end; |
| 1509 |
|
| 1510 |
function TCastleTerrainLayer.GetUsingPackedVector(const Vec: TSFVec4f): Single; |
| 1511 |
begin |
| 1512 |
Result := Vec.Value[Layer - 1]; |
| 1513 |
end; |
| 1514 |
|
| 1515 |
procedure TCastleTerrainLayer.SetUsingPackedVector(const Vec: TSFVec4f; const Value: Single); |
| 1516 |
var |
| 1517 |
V: TVector4; |
| 1518 |
begin |
| 1519 |
V := Vec.Value; |
| 1520 |
V.Data[Layer - 1] := Value; |
| 1521 |
Vec.Send(V); |
| 1522 |
end; |
| 1523 |
|
| 1524 |
function TCastleTerrainLayer.GetUvScale: Single; |
| 1525 |
begin |
| 1526 |
Result := GetUsingPackedVector(Terrain.UvScaleField); |
| 1527 |
end; |
| 1528 |
|
| 1529 |
procedure TCastleTerrainLayer.SetUvScale(const Value: Single); |
| 1530 |
begin |
| 1531 |
SetUsingPackedVector(Terrain.UvScaleField, Value); |
| 1532 |
end; |
| 1533 |
|
| 1534 |
function TCastleTerrainLayer.GetMetallic: Single; |
| 1535 |
begin |
| 1536 |
Result := GetUsingPackedVector(Terrain.MetallicField); |
| 1537 |
end; |
| 1538 |
|
| 1539 |
procedure TCastleTerrainLayer.SetMetallic(const Value: Single); |
| 1540 |
begin |
| 1541 |
SetUsingPackedVector(Terrain.MetallicField, Value); |
| 1542 |
end; |
| 1543 |
|
| 1544 |
function TCastleTerrainLayer.GetRoughness: Single; |
| 1545 |
begin |
| 1546 |
Result := GetUsingPackedVector(Terrain.RoughnessField); |
| 1547 |
end; |
| 1548 |
|
| 1549 |
procedure TCastleTerrainLayer.SetRoughness(const Value: Single); |
| 1550 |
begin |
| 1551 |
SetUsingPackedVector(Terrain.RoughnessField, Value); |
| 1552 |
end; |
| 1553 |
|
| 1554 |
function TCastleTerrainLayer.GetColor: TCastleColorRGB; |
| 1555 |
begin |
| 1556 |
Result := ColorField.Value; |
| 1557 |
end; |
| 1558 |
|
| 1559 |
procedure TCastleTerrainLayer.SetColor(const Value: TCastleColorRGB); |
| 1560 |
begin |
| 1561 |
ColorField.Send(Value); |
| 1562 |
end; |
| 1563 |
|
| 1564 |
function TCastleTerrainLayer.GetTexture: String; |
| 1565 |
begin |
| 1566 |
if TextureNode.FdUrl.Count = 2 then // [image url, WhitePixel] |
| 1567 |
Result := TextureNode.FdUrl.Items[0] |
| 1568 |
else |
| 1569 |
Result := ''; |
| 1570 |
end; |
| 1571 |
|
| 1572 |
procedure TCastleTerrainLayer.SetTexture(const Value: String); |
| 1573 |
begin |
| 1574 |
if GetTexture() <> Value then |
| 1575 |
begin |
| 1576 |
if Value <> '' then |
| 1577 |
TextureNode.SetUrl([Value, WhitePixel]) |
| 1578 |
else |
| 1579 |
TextureNode.SetUrl([WhitePixel]); |
| 1580 |
// TODO: Only this will properly update the shader uniform to use new texture |
| 1581 |
Terrain.Scene.ChangedAll; |
| 1582 |
end; |
| 1583 |
end; |
| 1584 |
|
| 1585 |
function TCastleTerrainLayer.PropertySections(const PropertyName: String): TPropertySections; |
| 1586 |
begin |
| 1587 |
if ArrayContainsString(PropertyName, [ |
| 1588 |
'UvScale', 'ColorPersistent', 'Texture', 'Metallic', 'Roughness' |
| 1589 |
]) then |
| 1590 |
Result := [psBasic] |
| 1591 |
else |
| 1592 |
Result := inherited PropertySections(PropertyName); |
| 1593 |
end; |
| 1594 |
|
| 1595 |
{$define read_implementation_methods} |
| 1596 |
{$I auto_generated_persistent_vectors/tcastleterrainlayer_persistent_vectors.inc} |
| 1597 |
{$undef read_implementation_methods} |
| 1598 |
|
| 1599 |
{ TCastleTerrain ------------------------------------------------------------- } |
| 1600 |
|
| 1601 |
constructor TCastleTerrain.Create(AOwner: TComponent); |
| 1602 |
|
| 1603 |
procedure AdjustAppearance; |
| 1604 |
var |
| 1605 |
VertexPart, FragmentPart: TEffectPartNode; |
| 1606 |
I: Integer; |
| 1607 |
begin |
| 1608 |
{ initialize Effect node, for a shader effect } |
| 1609 |
Effect := TEffectNode.Create; |
| 1610 |
Effect.Language := slGLSL; |
| 1611 |
{ If no light sources are present, it is normal that almost all uniforms |
| 1612 |
in this effect do not exist -- because they affect only |
| 1613 |
the TPhysicalMaterialNode.BaseTexture, which is meaningless when no light shines. } |
| 1614 |
Effect.UniformMissing := umIgnore; |
| 1615 |
Appearance.SetEffects([Effect]); |
| 1616 |
|
| 1617 |
UvScaleField := TSFVec4f.Create(Effect, true, 'uv_scale', Vector4( |
| 1618 |
TCastleTerrainLayer.DefaultUvScale, |
| 1619 |
TCastleTerrainLayer.DefaultUvScale, |
| 1620 |
TCastleTerrainLayer.DefaultUvScale, |
| 1621 |
TCastleTerrainLayer.DefaultUvScale)); |
| 1622 |
Effect.AddCustomField(UvScaleField); |
| 1623 |
|
| 1624 |
MetallicField := TSFVec4f.Create(Effect, true, 'metallic', Vector4( |
| 1625 |
TCastleTerrainLayer.DefaultMetallic, |
| 1626 |
TCastleTerrainLayer.DefaultMetallic, |
| 1627 |
TCastleTerrainLayer.DefaultMetallic, |
| 1628 |
TCastleTerrainLayer.DefaultMetallic)); |
| 1629 |
Effect.AddCustomField(MetallicField); |
| 1630 |
|
| 1631 |
RoughnessField := TSFVec4f.Create(Effect, true, 'roughness', Vector4( |
| 1632 |
TCastleTerrainLayer.DefaultRoughness, |
| 1633 |
TCastleTerrainLayer.DefaultRoughness, |
| 1634 |
TCastleTerrainLayer.DefaultRoughness, |
| 1635 |
TCastleTerrainLayer.DefaultRoughness)); |
| 1636 |
Effect.AddCustomField(RoughnessField); |
| 1637 |
|
| 1638 |
for I := 1 to HeightsCount do |
| 1639 |
begin |
| 1640 |
HeightsFields[I] := TSFFloat.Create(Effect, true, 'height_' + IntToStr(I), DefaultHeight[I]); |
| 1641 |
Effect.AddCustomField(HeightsFields[I]); |
| 1642 |
end; |
| 1643 |
|
| 1644 |
Effect.AddCustomField(TSFFloat.Create(Effect, true, 'layers_influence', FLayersInfluence)); |
| 1645 |
Effect.AddCustomField(TSFFloat.Create(Effect, true, 'steep_emphasize', FSteepEmphasize)); |
| 1646 |
|
| 1647 |
{ initialize 2 EffectPart nodes (one for vertex shader, one for fragment shader) } |
| 1648 |
FragmentPart := TEffectPartNode.Create; |
| 1649 |
FragmentPart.ShaderType := stFragment; |
| 1650 |
FragmentPart.Contents := {$I terrain.fs.inc}; |
| 1651 |
|
| 1652 |
VertexPart := TEffectPartNode.Create; |
| 1653 |
VertexPart.ShaderType := stVertex; |
| 1654 |
VertexPart.Contents := {$I terrain.vs.inc}; |
| 1655 |
|
| 1656 |
Effect.SetParts([FragmentPart, VertexPart]); |
| 1657 |
|
| 1658 |
{ make the material lit } |
| 1659 |
Appearance.Material := TPhysicalMaterialNode.Create; |
| 1660 |
end; |
| 1661 |
|
| 1662 |
var |
| 1663 |
Layer: Cardinal; |
| 1664 |
begin |
| 1665 |
inherited; |
| 1666 |
|
| 1667 |
FTriangulationIgnoreHeights := DefaultTriangulationIgnoreHeights; |
| 1668 |
FSubdivisions := Vector2(DefaultSubdivisions, DefaultSubdivisions); |
| 1669 |
FSize := Vector2(DefaultSize, DefaultSize); |
| 1670 |
FLayersInfluence := DefaultLayersInfluence; |
| 1671 |
FSteepEmphasize := DefaultSteepEmphasize; |
| 1672 |
FPreciseCollisions := true; |
| 1673 |
|
| 1674 |
Scene := TCastleScene.Create(Self); |
| 1675 |
//Scene.ProcessEvents := true; // not necessary right now for anything |
| 1676 |
Scene.SetTransient; |
| 1677 |
Scene.PreciseCollisions := true; |
| 1678 |
Add(Scene); |
| 1679 |
|
| 1680 |
Appearance := TAppearanceNode.Create; |
| 1681 |
Appearance.KeepExistingBegin; // it's easiest to manage release of Appearance |
| 1682 |
AdjustAppearance; |
| 1683 |
|
| 1684 |
for Layer := 1 to LayersCount do |
| 1685 |
begin |
| 1686 |
Layers[Layer] := TCastleTerrainLayer.CreateForTerrain(Self, Layer, Effect); |
| 1687 |
Layers[Layer].SetSubComponent(true); |
| 1688 |
Layers[Layer].Name := 'Layer' + IntToStr(Layer); |
| 1689 |
end; |
| 1690 |
|
| 1691 |
FDataObserver := TFreeNotificationObserver.Create(Self); |
| 1692 |
FDataObserver.OnFreeNotification := {$ifdef FPC}@{$endif} DataFreeNotification; |
| 1693 |
|
| 1694 |
UpdateGeometry; |
| 1695 |
|
| 1696 |
{$define read_implementation_constructor} |
| 1697 |
{$I auto_generated_persistent_vectors/tcastleterrain_persistent_vectors.inc} |
| 1698 |
{$undef read_implementation_constructor} |
| 1699 |
end; |
| 1700 |
|
| 1701 |
destructor TCastleTerrain.Destroy; |
| 1702 |
begin |
| 1703 |
{$define read_implementation_destructor} |
| 1704 |
{$I auto_generated_persistent_vectors/tcastleterrain_persistent_vectors.inc} |
| 1705 |
{$undef read_implementation_destructor} |
| 1706 |
inherited; |
| 1707 |
|
| 1708 |
{ Avoid Appearance having invalid reference in Appearance.Scene. |
| 1709 |
Note that Scene was freed in "inherited" above, |
| 1710 |
but Appearance.Scene may not have been cleared, |
| 1711 |
because of optimization in TCastleSceneCore.FreeRootNode doing: |
| 1712 |
|
| 1713 |
if (FRootNode <> nil) and (not FOwnsRootNode) then |
| 1714 |
FRootNode.UnregisterScene; |
| 1715 |
|
| 1716 |
See comments in TCastleSceneCore.FreeRootNode about it. |
| 1717 |
|
| 1718 |
To avoid crashes at examples/terrain exit, we have to clear |
| 1719 |
Appearance.Scene manually, otherwise TAppearanceNode will try to access |
| 1720 |
it in MoveShapeAssociations. } |
| 1721 |
if Appearance <> nil then |
| 1722 |
Appearance.UnregisterScene; |
| 1723 |
|
| 1724 |
// remove after RootNode containing this is removed too |
| 1725 |
FreeAndNil(Appearance); |
| 1726 |
end; |
| 1727 |
|
| 1728 |
procedure TCastleTerrain.Loaded; |
| 1729 |
begin |
| 1730 |
inherited; |
| 1731 |
if FUpdateGeometryWhenLoaded then |
| 1732 |
begin |
| 1733 |
FUpdateGeometryWhenLoaded := false; |
| 1734 |
Assert(not IsLoading); |
| 1735 |
UpdateGeometry; |
| 1736 |
end; |
| 1737 |
end; |
| 1738 |
|
| 1739 |
procedure TCastleTerrain.UpdateGeometry; |
| 1740 |
|
| 1741 |
function CreateQuadShape(const Range: TFloatRectangle): TAbstractChildNode; |
| 1742 |
var |
| 1743 |
QuadSet: TQuadSetNode; |
| 1744 |
Coord: TCoordinateNode; |
| 1745 |
Shape: TShapeNode; |
| 1746 |
Transform: TTransformNode; |
| 1747 |
begin |
| 1748 |
Coord := TCoordinateNode.Create; |
| 1749 |
Coord.SetPoint([ |
| 1750 |
{ Order of these points matter, must be CCW when observed from top, |
| 1751 |
just like "real" terrain data generated by TCastleTerrainNoise. |
| 1752 |
This way backface culling works in the same way. } |
| 1753 |
Vector3( 0, 0, Range.Height), |
| 1754 |
Vector3(Range.Width, 0, Range.Height), |
| 1755 |
Vector3(Range.Width, 0, 0), |
| 1756 |
Vector3( 0, 0, 0) |
| 1757 |
]); |
| 1758 |
|
| 1759 |
QuadSet := TQuadSetNode.CreateWithTransform(Shape, Transform); |
| 1760 |
QuadSet.Coord := Coord; |
| 1761 |
|
| 1762 |
Shape.Appearance := Appearance; |
| 1763 |
|
| 1764 |
{ We translate the quad by TTransformNode, to keep the vertex coordinates |
| 1765 |
in object space consistent with what is generated by CreateNode, |
| 1766 |
and make the texture UV coordinates start the same. } |
| 1767 |
Transform.Translation := Vector3(Range.Left, 0, Range.Bottom); |
| 1768 |
|
| 1769 |
Result := Transform; |
| 1770 |
end; |
| 1771 |
|
| 1772 |
{ Update associated collider, e.g. to update TCastleMeshCollider to reflect new terrain. } |
| 1773 |
procedure UpdateCollider; |
| 1774 |
var |
| 1775 |
C: TCastleCollider; |
| 1776 |
begin |
| 1777 |
C := FindBehavior(TCastleCollider) as TCastleCollider; |
| 1778 |
if C <> nil then |
| 1779 |
C.InternalTransformChanged(Self); |
| 1780 |
end; |
| 1781 |
|
| 1782 |
var |
| 1783 |
Root: TX3DRootNode; |
| 1784 |
InputRange, OutputRange: TFloatRectangle; |
| 1785 |
begin |
| 1786 |
{ During deserialization, defer the real work to the Loaded moment, |
| 1787 |
to avoid regenerating heights multiple times. } |
| 1788 |
if IsLoading then |
| 1789 |
begin |
| 1790 |
FUpdateGeometryWhenLoaded := true; |
| 1791 |
Exit; |
| 1792 |
end; |
| 1793 |
|
| 1794 |
OutputRange := FloatRectangle(-Size.X/2, -Size.Y/2, Size.X, Size.Y); |
| 1795 |
|
| 1796 |
InputRange := OutputRange; |
| 1797 |
InputRange.LeftBottom := InputRange.LeftBottom + QueryOffset; |
| 1798 |
|
| 1799 |
if Data <> nil then |
| 1800 |
begin |
| 1801 |
if TerrainNode = nil then |
| 1802 |
begin |
| 1803 |
TerrainNode := Data.CreateNode(Subdivisions, InputRange, OutputRange, Appearance, TriangulationIgnoreHeights); |
| 1804 |
Root := TX3DRootNode.Create; |
| 1805 |
Root.AddChildren(TerrainNode); |
| 1806 |
Scene.Load(Root, true); |
| 1807 |
end else |
| 1808 |
begin |
| 1809 |
Data.UpdateNode(TerrainNode, Subdivisions, InputRange, OutputRange, TriangulationIgnoreHeights); |
| 1810 |
end; |
| 1811 |
end else |
| 1812 |
begin |
| 1813 |
{ When Data is empty, show a simple quad to visualize Size of the terrain. } |
| 1814 |
Root := TX3DRootNode.Create; |
| 1815 |
Root.AddChildren(CreateQuadShape(OutputRange)); |
| 1816 |
Scene.Load(Root, true); |
| 1817 |
{ Do not let subsequent calls to use TerrainNode as it was destroyed |
| 1818 |
by Scene.Load above. |
| 1819 |
Testcase: create TCastleTerrain and TCastleTerrainImage, |
| 1820 |
assign TCastleTerrain.Data to TCastleTerrainImage, to nil, again to TCastleTerrainImage. } |
| 1821 |
TerrainNode := nil; |
| 1822 |
end; |
| 1823 |
|
| 1824 |
UpdateCollider; |
| 1825 |
end; |
| 1826 |
|
| 1827 |
function TCastleTerrain.GetLayer(const Index: Integer): TCastleTerrainLayer; |
| 1828 |
begin |
| 1829 |
Result := Layers[Index]; |
| 1830 |
end; |
| 1831 |
|
| 1832 |
function TCastleTerrain.GetRenderOptions: TCastleRenderOptions; |
| 1833 |
begin |
| 1834 |
Result := Scene.RenderOptions; |
| 1835 |
end; |
| 1836 |
|
| 1837 |
procedure TCastleTerrain.SetData(const Value: TCastleTerrainData); |
| 1838 |
begin |
| 1839 |
if FData <> Value then |
| 1840 |
begin |
| 1841 |
{ Ignore nonsense assignment done by FpRttiJson when this node references |
| 1842 |
in JSON non-yet-known name. FpRttiJson then creates an instance of |
| 1843 |
TCastleTerrainData and assigns it here -- a useless instance, |
| 1844 |
that would actually cause trouble as it has abstract methods. } |
| 1845 |
if (Value <> nil) and |
| 1846 |
(Value.ClassType = TCastleTerrainData) then |
| 1847 |
Exit; |
| 1848 |
|
| 1849 |
if FData <> nil then |
| 1850 |
FData.RemoveChangeNotification({$ifdef FPC}@{$endif} DataChanged); |
| 1851 |
FData := Value; |
| 1852 |
FDataObserver.Observed := Value; |
| 1853 |
if FData <> nil then |
| 1854 |
FData.AddChangeNotification({$ifdef FPC}@{$endif} DataChanged); |
| 1855 |
UpdateGeometry; |
| 1856 |
end; |
| 1857 |
end; |
| 1858 |
|
| 1859 |
procedure TCastleTerrain.DataChanged(Sender: TObject); |
| 1860 |
begin |
| 1861 |
UpdateGeometry; |
| 1862 |
end; |
| 1863 |
|
| 1864 |
procedure TCastleTerrain.DataFreeNotification(const Sender: TFreeNotificationObserver); |
| 1865 |
begin |
| 1866 |
Data := nil; |
| 1867 |
end; |
| 1868 |
|
| 1869 |
procedure TCastleTerrain.SetTriangulationIgnoreHeights(const Value: Boolean); |
| 1870 |
begin |
| 1871 |
if FTriangulationIgnoreHeights <> Value then |
| 1872 |
begin |
| 1873 |
// free the TerrainNode and RootNode, even if already created, to create new one |
| 1874 |
if TerrainNode <> nil then |
| 1875 |
begin |
| 1876 |
Scene.RootNode := nil; // will free TerrainNode and RootNode |
| 1877 |
TerrainNode := nil; |
| 1878 |
end; |
| 1879 |
FTriangulationIgnoreHeights := Value; |
| 1880 |
UpdateGeometry; |
| 1881 |
end; |
| 1882 |
end; |
| 1883 |
|
| 1884 |
procedure TCastleTerrain.SetSubdivisions(const Value: TVector2); |
| 1885 |
begin |
| 1886 |
if not TVector2.PerfectlyEquals(FSubdivisions, Value) then |
| 1887 |
begin |
| 1888 |
FSubdivisions := Value; |
| 1889 |
UpdateGeometry; |
| 1890 |
end; |
| 1891 |
end; |
| 1892 |
|
| 1893 |
procedure TCastleTerrain.SetSize(const Value: TVector2); |
| 1894 |
begin |
| 1895 |
if not TVector2.PerfectlyEquals(FSize, Value) then |
| 1896 |
begin |
| 1897 |
FSize := Value; |
| 1898 |
UpdateGeometry; |
| 1899 |
end; |
| 1900 |
end; |
| 1901 |
|
| 1902 |
procedure TCastleTerrain.SetQueryOffset(const Value: TVector2); |
| 1903 |
begin |
| 1904 |
if not TVector2.PerfectlyEquals(FQueryOffset, Value) then |
| 1905 |
begin |
| 1906 |
FQueryOffset := Value; |
| 1907 |
UpdateGeometry; |
| 1908 |
end; |
| 1909 |
end; |
| 1910 |
|
| 1911 |
function TCastleTerrain.GetHeight(const Index: Integer): Single; |
| 1912 |
begin |
| 1913 |
Result := HeightsFields[Index].Value; |
| 1914 |
end; |
| 1915 |
|
| 1916 |
procedure TCastleTerrain.SetHeight(const Index: Integer; const Value: Single); |
| 1917 |
begin |
| 1918 |
HeightsFields[Index].Send(Value); |
| 1919 |
end; |
| 1920 |
|
| 1921 |
procedure TCastleTerrain.SetLayersInfluence(const Value: Single); |
| 1922 |
begin |
| 1923 |
if FLayersInfluence <> Value then |
| 1924 |
begin |
| 1925 |
FLayersInfluence := Value; |
| 1926 |
(Effect.Field('layers_influence') as TSFFloat).Send(Value); |
| 1927 |
end; |
| 1928 |
end; |
| 1929 |
|
| 1930 |
procedure TCastleTerrain.SetSteepEmphasize(const Value: Single); |
| 1931 |
begin |
| 1932 |
if FSteepEmphasize <> Value then |
| 1933 |
begin |
| 1934 |
FSteepEmphasize := Value; |
| 1935 |
(Effect.Field('steep_emphasize') as TSFFloat).Send(Value); |
| 1936 |
end; |
| 1937 |
end; |
| 1938 |
|
| 1939 |
procedure TCastleTerrain.SetPreciseCollisions(const Value: Boolean); |
| 1940 |
begin |
| 1941 |
if FPreciseCollisions <> Value then |
| 1942 |
begin |
| 1943 |
FPreciseCollisions := Value; |
| 1944 |
Scene.PreciseCollisions := Value; |
| 1945 |
end; |
| 1946 |
end; |
| 1947 |
|
| 1948 |
function TCastleTerrain.PropertySections(const PropertyName: String): TPropertySections; |
| 1949 |
begin |
| 1950 |
if ArrayContainsString(PropertyName, [ |
| 1951 |
'RenderOptions', 'Data', 'TriangulationIgnoreHeights', 'SubdivisionsPersistent', |
| 1952 |
'SizePersistent', 'PreciseCollisions', |
| 1953 |
'Height1', 'Height2', |
| 1954 |
'Layer1', 'Layer2', 'Layer3', 'Layer4', |
| 1955 |
'LayersInfluence', 'SteepEmphasize', 'QueryOffsetPersistent' |
| 1956 |
]) then |
| 1957 |
Result := [psBasic] |
| 1958 |
else |
| 1959 |
Result := inherited PropertySections(PropertyName); |
| 1960 |
end; |
| 1961 |
|
| 1962 |
function TCastleTerrain.HasColliderMesh: Boolean; |
| 1963 |
begin |
| 1964 |
Result := true; |
| 1965 |
end; |
| 1966 |
|
| 1967 |
procedure TCastleTerrain.ColliderMesh(const TriangleEvent: TTriangleEvent); |
| 1968 |
begin |
| 1969 |
Scene.ColliderMesh(TriangleEvent); |
| 1970 |
end; |
| 1971 |
|
| 1972 |
{$define read_implementation_methods} |
| 1973 |
{$I auto_generated_persistent_vectors/tcastleterrain_persistent_vectors.inc} |
| 1974 |
{$undef read_implementation_methods} |
| 1975 |
|
| 1976 |
initialization |
| 1977 |
RegisterSerializableComponent(TCastleTerrainImage, ['Terrain Data (Experimental)', 'Image Data']); |
| 1978 |
RegisterSerializableComponent(TCastleTerrainNoise, ['Terrain Data (Experimental)', 'Noise Data']); |
| 1979 |
RegisterSerializableComponent(TCastleTerrainCombine, ['Terrain Data (Experimental)', 'Combine Data']); |
| 1980 |
RegisterSerializableComponent(TCastleTerrain, ['Terrain (Experimental)']); |
| 1981 |
end. |