/usr/src/castle-game-engine-5.2.0/x3d/opengl/castlebackground.pas is in castle-game-engine-src 5.2.0-3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | {
Copyright 2002-2014 Michalis Kamburelis.
This file is part of "Castle Game Engine".
"Castle Game Engine" is free software; see the file COPYING.txt,
included in this distribution, for details about the copyright.
"Castle Game Engine" is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
----------------------------------------------------------------------------
}
{ Background for 3D world (TBackground). }
unit CastleBackground;
interface
uses CastleVectors, SysUtils, CastleUtils, CastleImages, X3DNodes,
CastleFrustum, CastleColors, CastleGLUtils;
type
{ Background for 3D world.
Background defined here has the same features as VRML/X3D Background:
@unorderedList(
@itemSpacing Compact
@item(skybox - a cube with each face potentially textured
(textures may have alpha channel))
@item a ground sphere around this, with color rings for ground colors
@item a sky sphere around this, with color rings for sky colors
)
Engine users should not use this class directly. Instead TCastleSceneManager
automatically uses this to render the background defined by
TCastleSceneManager.MainScene. }
TBackground = class
private
{ TCastleScene to render the background in most cases.
Cannot be declared as TCastleScene as it would create a circular dependency
with CastleScene unit. }
SceneObj: TObject;
ParamsObj: TObject;
ClearColor: TCastleColor;
MatrixTransform: TMatrixTransformNode;
public
{ Calculate (or just confirm that Proposed value is still OK)
the sky sphere radius that fits nicely in your projection near/far.
Background spheres (for sky and ground) are rendered at given radius.
And inside these spheres, we have a cube (to apply background textures).
Both spheres and cube must fit nicely within your projection near/far
to avoid any artifacts.
We first check is Proposed a good result value (it satisfies
the conditions, with some safety margin). If yes, then we return
exactly the Proposed value. Otherwise, we calculate new value
as an average in our range.
This way, if you already had sky sphere radius calculated
(and prepared some OpenGL resources for it),
and projection near/far changes very slightly
(e.g. because bounding box slightly changed), then you don't have
to recreate background --- if the old sky sphere radius is still OK,
then the old background resources are still OK.
Just pass Proposed = 0 (or anything else that is always outside
the range) if you don't need this feature. }
class function NearFarToSkySphereRadius(const zNear, zFar: Single;
const Proposed: Single = 0): Single;
constructor Create;
destructor Destroy; override;
procedure Update(const Node: TAbstractBackgroundNode;
const SkySphereRadius: Single);
procedure Render(const Wireframe: boolean; const Frustum: TFrustum);
procedure UpdateTransform(const Transform: TMatrix4Single);
procedure FreeResources;
end;
implementation
uses CastleWarnings, CastleScene, X3DFields, Math, CastleSceneCore;
const
{ Relation of a cube size and a radius of it's bounding sphere.
Sphere surrounds the cube, such that 6 cube corners touch the sphere.
So cube diameter = 2 * sphere radius.
Cube diameter = sqrt(sqr(cube size) + sqr(cube face diameter)),
and cube face diameter = sqrt(2) * cube size.
This gives constants below. }
SphereRadiusToCubeSize = 2 / Sqrt(3);
CubeSizeToSphereRadius = Sqrt(3) / 2;
{ TBackground ------------------------------------------------------------ }
class function TBackground.NearFarToSkySphereRadius(const zNear, zFar: Single;
const Proposed: Single): Single;
{ Conditions are ZNear < CubeSize/2, ZFar > SphereRadius.
So conditions for radius are
ZNear * 2 * CubeSizeToSphereRadius < SphereRadius < ZFar
Note that 2 * CubeSizeToSphereRadius is Sqrt(3) =~ 1.7,
so it's possible to choose
ZNear <= ZFar that still yield no possible radius.
It would be possible to avoid whole need for this method
by setting projection matrix in our own render. But then,
you'd have to pass fovy and such parameters to the background renderer.
}
var
Min, Max, SafeMin, SafeMax: Single;
begin
Min := zNear * 2 * CubeSizeToSphereRadius;
Max := zFar;
{ The new sphere radius should be in [Min...Max].
For maximum safety (from floating point troubles), we require
that it's within slightly smaller "safe" range. }
SafeMin := Lerp(0.1, Min, Max);
SafeMax := Lerp(0.9, Min, Max);
if (Proposed >= SafeMin) and
(Proposed <= SafeMax) then
Result := Proposed else
Result := (Min + Max) / 2;
end;
{$define Scene := TCastleScene(SceneObj)}
{$define Params := TBasicRenderParams(ParamsObj)}
constructor TBackground.Create;
begin
inherited;
Scene := TCastleScene.Create(nil);
{ We don't need depth test (we put our shapes in proper order),
we even don't want it (because we don't clear depth buffer
before drawing, so it may contain the depths on 3D world rendered
in previous frame). }
Scene.Attributes.DepthTest := false;
Params := TBasicRenderParams.Create;
end;
destructor TBackground.Destroy;
begin
FreeAndNil(Scene);
FreeAndNil(Params);
inherited;
end;
procedure TBackground.Update(const Node: TAbstractBackgroundNode;
const SkySphereRadius: Single);
var
RootNode: TX3DRootNode;
procedure RenderCubeSides;
var
CubeSize, CubeSize2: Single;
procedure RenderTextureSide(const Side: TBackgroundSide);
const
Coords: array [TBackgroundSide, 0..3] of TVector3Single =
( (( 1, -1, 1), (-1, -1, 1), (-1, 1, 1), ( 1, 1, 1)), {back}
((-1, -1, 1), ( 1, -1, 1), ( 1, -1, -1), (-1, -1, -1)), {bottom}
((-1, -1, -1), ( 1, -1, -1), ( 1, 1, -1), (-1, 1, -1)), {front}
((-1, -1, 1), (-1, -1, -1), (-1, 1, -1), (-1, 1, 1)), {left}
(( 1, -1, -1), ( 1, -1, 1), ( 1, 1, 1), ( 1, 1, -1)), {right}
((-1, 1, -1), ( 1, 1, -1), ( 1, 1, 1), (-1, 1, 1)) {top}
);
TexCoords: array [0..3] of TVector2Single = ((0, 0), (1, 0), (1, 1), (0, 1));
var
Shape: TShapeNode;
Appearance: TAppearanceNode;
QuadSet: TQuadSetNode;
Coord: TCoordinateNode;
TexCoord: TTextureCoordinateNode;
Texture: TAbstractTextureNode;
V: TVector3Single;
begin
Texture := Node.Texture(Side);
if Texture = nil then Exit;
Coord := TCoordinateNode.Create('', Node.BaseUrl);
for V in Coords[Side] do
Coord.FdPoint.Items.Add(V * CubeSize2);
TexCoord := TTextureCoordinateNode.Create('', Node.BaseUrl);
TexCoord.FdPoint.Send(TexCoords);
QuadSet := TQuadSetNode.Create('', Node.BaseUrl);
QuadSet.FdCoord.Value := Coord;
QuadSet.FdTexCoord.Value := TexCoord;
Appearance := TAppearanceNode.Create('', Node.BaseUrl);
Appearance.FdShaders.AssignValue(Node.FdShaders);
Appearance.FdEffects.AssignValue(Node.FdEffects);
Appearance.Texture := Texture;
if Texture is TAbstractTexture2DNode then
begin
{ We have to change repeat mode of this texture, even if it came from
TTextureBackgroundNode. The only reasonable way to render background
is to use clamp mode. More correct alternative would be creating
a copy of node in case of TTextureBackgroundNode,
but this would often be wasteful --- the background texture is
probably not DEF/USEd in other places (that need repeat mode),
and it's probably repeat=true by accident (since this is the default value). }
TAbstractTexture2DNode(Texture).RepeatS := false;
TAbstractTexture2DNode(Texture).RepeatT := false;
end;
Shape := TShapeNode.Create('', Node.BaseUrl);
Shape.FdGeometry.Value := QuadSet;
Shape.Appearance := Appearance;
MatrixTransform.FdChildren.Add(Shape);
end;
var
BS: TBackgroundSide;
begin
CubeSize := SkySphereRadius * SphereRadiusToCubeSize;
CubeSize2 := CubeSize / 2;
for BS := Low(BS) to High(BS) do RenderTextureSide(BS);
end;
var
SphereCreated: boolean;
SphereCoord: TMFVec3f;
SphereCoordIndex: TMFInt32;
SphereColor: TMFColor;
procedure NeedsSphere;
var
Coord: TCoordinateNode;
Color: TColorNode;
Geometry: TIndexedFaceSetNode;
Shape: TShapeNode;
begin
{ add a mesh for sphere, if not present already }
if not SphereCreated then
begin
SphereCreated := true;
Coord := TCoordinateNode.Create('', Node.BaseUrl);
SphereCoord := Coord.FdPoint;
Color := TColorNode.Create('', Node.BaseUrl);
SphereColor := Color.FdColor;
Geometry := TIndexedFaceSetNode.Create('', Node.BaseUrl);
Geometry.FdCoord.Value := Coord;
Geometry.FdColor.Value := Color;
Geometry.FdSolid.Value := false;
SphereCoordIndex := Geometry.FdCoordIndex;
Shape := TShapeNode.Create('', Node.BaseUrl);
Shape.FdGeometry.Value := Geometry;
MatrixTransform.FdChildren.Add(Shape);
end;
end;
const
{ slices of rings rendered in Render*Stack }
Slices = 24;
{ For given Angle (meaning: 0 = zenith, Pi = nadir), calculate the height
and radius of given circle of sky sphere. }
procedure StackCircleCalc(const Angle: Single; out Y, Radius: Single);
var
S, C: Extended;
begin
SinCos(Angle, S, C);
Radius := S * SkySphereRadius;
Y := C * SkySphereRadius;
end;
function StackTipCalc(const Angle: Single): TVector3Single;
begin
// Result := Vector3Single(0, Cos(Angle) * SkySphereRadius, 0);
{ simpler and more accurate version, since StackTipCalc is only called with
Angle = 0 or Pi }
if Angle = 0 then
Result := Vector3Single(0, SkySphereRadius, 0) else
begin
Assert(Angle = Single(Pi));
Result := Vector3Single(0, -SkySphereRadius, 0);
end;
end;
function CirclePoint(const Y, Radius: Single; const SliceIndex: Integer): TVector3Single;
var
S, C: Extended;
begin
SinCos(SliceIndex * 2 * Pi / Slices, S, C);
Result := Vector3Single(S * Radius, Y, C * Radius);
end;
{ Render*Stack: render one stack of sky/ground sphere.
Angles are given in the sky connvention : 0 is zenith, Pi is nadir. }
procedure RenderFirstStack(
const TipColor : TVector3Single; const TipAngle : Single;
const CircleColor: TVector3Single; const CircleAngle: Single);
var
CircleY, CircleRadius: Single;
I, Start, Next, StartIndex, NextIndex: Integer;
begin
Start := SphereCoord.Count;
Next := Start;
Assert(Start = SphereColor.Count);
SphereCoord.Count := Start + Slices + 1;
SphereColor.Count := Start + Slices + 1;
StartIndex := SphereCoordIndex.Count;
NextIndex := StartIndex;
SphereCoordIndex.Count := SphereCoordIndex.Count + Slices * 4;
StackCircleCalc(CircleAngle, CircleY, CircleRadius);
SphereCoord.Items.L[Start] := StackTipCalc(TipAngle);
SphereColor.Items.L[Start] := TipColor;
Inc(Next);
for I := 0 to Slices - 1 do
begin
SphereCoord.Items.L[Next] := CirclePoint(CircleY, CircleRadius, I);
SphereColor.Items.L[Next] := CircleColor;
Inc(Next);
SphereCoordIndex.Items.L[NextIndex ] := Start;
SphereCoordIndex.Items.L[NextIndex + 1] := Start + 1 + I;
if I <> Slices - 1 then
SphereCoordIndex.Items.L[NextIndex + 2] := Start + 2 + I else
SphereCoordIndex.Items.L[NextIndex + 2] := Start + 1;
SphereCoordIndex.Items.L[NextIndex + 3] := -1;
NextIndex += 4;
end;
end;
procedure RenderNextStack(
const CircleColor: TVector3Single; const CircleAngle: Single);
var
CircleY, CircleRadius: Single;
I, Start, Next, StartIndex, NextIndex: Integer;
begin
Start := SphereCoord.Count;
Next := Start;
Assert(Start = SphereColor.Count);
SphereCoord.Count := Start + Slices;
SphereColor.Count := Start + Slices;
StartIndex := SphereCoordIndex.Count;
NextIndex := StartIndex;
SphereCoordIndex.Count := SphereCoordIndex.Count + Slices * 5;
StackCircleCalc(CircleAngle, CircleY, CircleRadius);
for I := 0 to Slices - 1 do
begin
SphereCoord.Items.L[Next] := CirclePoint(CircleY, CircleRadius, I);
SphereColor.Items.L[Next] := CircleColor;
Inc(Next);
SphereCoordIndex.Items.L[NextIndex ] := Start + I;
if I <> Slices - 1 then
begin
SphereCoordIndex.Items.L[NextIndex + 1] := Start + 1 + I;
SphereCoordIndex.Items.L[NextIndex + 2] := Start + 1 + I - Slices;
end else
begin
SphereCoordIndex.Items.L[NextIndex + 1] := Start;
SphereCoordIndex.Items.L[NextIndex + 2] := Start - Slices;
end;
SphereCoordIndex.Items.L[NextIndex + 3] := Start + I - Slices;
SphereCoordIndex.Items.L[NextIndex + 4] := -1;
NextIndex += 5;
end;
end;
procedure RenderLastStack(
const TipColor: TVector3Single; const TipAngle: Single);
var
I, Start, StartIndex, NextIndex: Integer;
begin
Start := SphereCoord.Count;
Assert(Start = SphereColor.Count);
SphereCoord.Count := Start + 1;
SphereColor.Count := Start + 1;
StartIndex := SphereCoordIndex.Count;
NextIndex := StartIndex;
SphereCoordIndex.Count := SphereCoordIndex.Count + Slices * 4;
SphereCoord.Items.L[Start] := StackTipCalc(TipAngle);
SphereColor.Items.L[Start] := TipColor;
for I := 0 to Slices - 1 do
begin
SphereCoordIndex.Items.L[NextIndex ] := Start;
if I <> Slices - 1 then
SphereCoordIndex.Items.L[NextIndex + 1] := Start - Slices + I + 1 else
SphereCoordIndex.Items.L[NextIndex + 1] := Start - Slices;
SphereCoordIndex.Items.L[NextIndex + 2] := Start - Slices + I;
SphereCoordIndex.Items.L[NextIndex + 3] := -1;
NextIndex += 4;
end;
end;
procedure RenderSky;
var
I, ColorCount, AngleCount: Integer;
Angle: PSingle;
Color: PVector3Single;
GroundHighestAngle: Single;
begin
{ calculate GroundHighestAngle, will be usable to optimize rendering sky.
GroundHighestAngle is measured in sky convention (0 = zenith, Pi = nadir).
If there is no sky I simply set GroundHighestAngle to sthg > Pi. }
if Node.FdGroundAngle.Count <> 0 then
GroundHighestAngle := Pi - Node.FdGroundAngle.Items.Last else
GroundHighestAngle := Pi + 1;
ColorCount := Node.FdSkyColor.Count;
AngleCount := Node.FdSkyAngle.Count;
Color := Node.FdSkyColor.Items.L;
Angle := Node.FdSkyAngle.Items.L;
if ColorCount <= 0 then
begin
OnWarning(wtMajor, 'VRML/X3D', 'Background node incorrect: Sky must have at least one color');
Exit;
end else
if AngleCount + 1 <> ColorCount then
begin
OnWarning(wtMajor, 'VRML/X3D', 'Background node incorrect: Sky must have exactly one more Color than Angles');
{ We know now that ColorCount >= 1, and of course AngleCount >= 0
(since array always has >= 0 items). So we correct one of them to be
smaller. }
if AngleCount + 1 > ColorCount then
AngleCount := ColorCount - 1 else
ColorCount := AngleCount + 1;
end;
Assert(ColorCount >= 1);
Assert(AngleCount + 1 = ColorCount);
ClearColor := Vector4Single(Color[0], 1.0);
if ColorCount > 1 then
begin
{ When ColorCount >= 2, the idea of rendering is to do:
- RenderFirstStack
- RenderNextStack many times
- RenderLastStack
But we try to break this early, to not waste time rendering
something that will be covered anyway by the ground sphere,
using GroundHighestAngle. }
NeedsSphere;
RenderFirstStack(Color[0], 0,
Color[1], Angle[0]);
for I := 1 to AngleCount - 1 do
begin
if Angle[I - 1] > GroundHighestAngle then Break;
RenderNextStack(Color[I + 1], Angle[I]);
end;
{ close the tip of the sky sphere with constant color (last on Color[] table) }
if Angle[AngleCount - 1] <= GroundHighestAngle then
RenderLastStack(Color[ColorCount - 1], Pi);
end;
end;
procedure RenderGround;
var
I: Integer;
ColorCount, AngleCount: Integer;
Angle: PSingle;
Color: PVector3Single;
begin
ColorCount := Node.FdGroundColor.Count;
AngleCount := Node.FdGroundAngle.Count;
Color := Node.FdGroundColor.Items.L;
Angle := Node.FdGroundAngle.Items.L;
if AngleCount <> 0 then
begin
if AngleCount + 1 <> ColorCount then
begin
OnWarning(wtMajor, 'VRML/X3D', 'Background node incorrect: Ground must have exactly one more Color than Angles');
if AngleCount + 1 > ColorCount then
AngleCount := ColorCount - 1 else
ColorCount := AngleCount + 1;
end;
Assert(AngleCount + 1 = ColorCount);
NeedsSphere;
RenderFirstStack(Color[0], Pi,
Color[1], Pi - Angle[0]);
for I := 1 to AngleCount - 1 do
RenderNextStack(Color[I + 1], Pi - Angle[I]);
end;
end;
begin
RootNode := TX3DRootNode.Create('', Node.BaseUrl);
SphereCreated := false;
MatrixTransform := TMatrixTransformNode.Create('', Node.BaseUrl);
MatrixTransform.FdMatrix.Value := Node.TransformRotation;
RootNode.FdChildren.Add(MatrixTransform);
RenderSky;
RenderGround;
RenderCubeSides;
Scene.Load(RootNode, true);
end;
procedure TBackground.Render(const Wireframe: boolean; const Frustum: TFrustum);
begin
Params.InShadow := false;
{ since we constructed Scene ourselves,
we know it only has ShadowVolumesReceivers=true shapes }
Params.ShadowVolumesReceivers := true;
if Wireframe then
Scene.Attributes.WireframeEffect := weWireframeOnly else
Scene.Attributes.WireframeEffect := weNormal;
{ TODO: in the old times, we had here an optimization:
if the background is not displayed as Wireframe,
and it has all 6 cube sides filled with textures without
an alpha channel, then there's no need to display sky/ground spheres,
and no need to even clear color buffer before.
We lose this optimization now, since we don't know now which cube sides
are successfully loaded and which have alpha. }
GLClear([cbColor], ClearColor);
{ Note: the Frustum is useless now, as it contains a shifted camera,
not just rotated. We pass it, but it will be ignored. }
Params.Transparent := false; Scene.Render(nil, Frustum, Params);
Params.Transparent := true ; Scene.Render(nil, Frustum, Params);
end;
procedure TBackground.FreeResources;
begin
Scene.FreeResources([frTextureDataInNodes]);
end;
procedure TBackground.UpdateTransform(const Transform: TMatrix4Single);
begin
MatrixTransform.FdMatrix.Send(Transform);
end;
end.
|