Debian Codegraph @

src/scene/x3d/x3dnodes_standard_texturing.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2002-2022 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18 { Base for all nodes which specify texture coordinates. }
19 TAbstractTextureCoordinateNode = class(TAbstractGeometricPropertyNode)
20 {$I auto_generated_node_helpers/x3dnodes_x3dtexturecoordinatenode.inc}
21 end;
22
23 { Base for all nodes which specify a texture coordinate, but not MultiTextureCoordinate. }
24 TAbstractSingleTextureCoordinateNode = class(TAbstractTextureCoordinateNode)
25 {$I auto_generated_node_helpers/x3dnodes_x3dsingletexturecoordinatenode.inc}
26 end;
27
28 TInternalRendererResource = class
29 end;
30
31 { Base for all nodes which specify a texture, possibly multi-texture. }
32 TAbstractTextureNode = class(TAbstractAppearanceChildNode)
33 strict private
34 FInternalRendererResource: TInternalRendererResource;
35 FContextCloseEventSetup: Boolean;
36 procedure SetInternalRendererResource(const Value: TInternalRendererResource);
37 procedure GLContextCloseEvent(Sender: TObject);
38 strict protected
39 { Alpha channel detected from image contents (or children nodes),
40 ignoring our FdAlphaChannel field.
41 Actually set only when image data is loaded
42 (e.g. TAbstractTexture2DNode.IsTextureLoaded in case of TAbstractTexture2DNode
43 descendant). }
44 function AlphaChannelData: TAlphaChannel; virtual;
45 public
46 { Internal data stored here and used by the renderer.
47 Specific to this TX3DNode.
48
49 This holds a reference count to OpenGL resource in RendererCache,
50 freeing this InternalRendererResource decreases the reference count,
51 and it is done when destroying this node or when last GL context
52 is lost.
53
54 @exclude }
55 property InternalRendererResource: TInternalRendererResource
56 read FInternalRendererResource write SetInternalRendererResource;
57
58 { Free InternalRendererResource, if any. }
59 procedure InternalRendererResourceFree;
60
61 destructor Destroy; override;
62
63 { Short description how texture is defined, is it inline or loaded
64 from URL, is it video of simple image texture.
65 "none" if it's not defined at all.
66
67 Calling this @italic(may not) cause automatically loading
68 the texture data (for exampe, from file in case of TAbstractTexture2DNode).
69 So it cannot describe the actually loaded data.
70
71 In this class, simply returns X3DType.
72 Override to say something more descriptive. }
73 function TextureDescription: string; virtual;
74
75 { Alpha channel of the loaded texture data.
76 Looks at loaded texture data, and at alphaChannel field
77 (see https://castle-engine.io/x3d_extensions.php#section_ext_alpha_channel_detection ).
78 In case of MultiTexture node, looks at children. }
79 function AlphaChannelFinal: TAlphaChannel; virtual;
80 {$I auto_generated_node_helpers/x3dnodes_x3dtexturenode.inc}
81 end;
82
83 { Base for all nodes which specify a texture, but not multi-texture. }
84 TAbstractSingleTextureNode = class(TAbstractTextureNode)
85 public
86 function AlphaChannelFinal: TAlphaChannel; override;
87
88 {$I auto_generated_node_helpers/x3dnodes_x3dsingletexturenode.inc}
89 end;
90
91 { 2D texture. }
92 TAbstractTexture2DNode = class(TAbstractSingleTextureNode)
93 private
94 { Together we call FTextureImage, FTextureComposite,
95 FTextureVideo, FAlphaChannelData as "texture data". }
96
97 { FTextureImage is <> nil if texture is currently loaded (IsTextureLoaded)
98 and it was loaded to an image (not video).
99
100 Note that this may still have zero size (IsEmpty = @true),
101 IsTextureImage checks this also. }
102 FTextureImage: TEncodedImage;
103
104 { Only if FTextureImage is <> nil, then FTextureComposite may also be <> nil,
105 it this image is part of Composite file. }
106 FTextureComposite: TCompositeImage;
107
108 { Analogous to FTextureImage, this is the loaded video file.
109 Assigned here, should always have TVideo.Loaded = @true. }
110 FTextureVideo: TVideo;
111
112 FAlphaChannelData: TAlphaChannel;
113
114 { Non-nil only if FTextureImage, FTextureComposite or FTextueVideo
115 should be freed using
116 UsedCache (TextureImage_DecReference or Video_DecReference).
117 Also loaded FTextureVideo should always have it's own Cache property set
118 to this. }
119 UsedCache: TTexturesVideosCache;
120
121 FIsTextureLoaded: boolean;
122 procedure SetIsTextureLoaded(Value: boolean);
123 procedure FreeAndNilTextureData;
124 strict protected
125 FTextureUsedFullUrl: String;
126
127 { Loads texture data (image or video file).
128
129 It should set either FTextureImage or FTextureVideo to something non-nil
130 (don't care here about the previous value of these fields --- it's for
131 sure @nil). If FTextureImage is set, you can also set FTextureComposite.
132 If you leave them as @nil, this means that loading failed
133 (and WritelnWarning didn't cause an exception).
134 You should also set FAlphaChannelData.
135
136 You do not care in this method about things like
137 IsImageLoaded --- this method should just always,
138 unconditionally, make everything it can do to load texture data from
139 file(s).
140
141 You can use WritelnWarning inside,
142 so we're prepared that this may even exit with exception
143 (since WritelnWarning can raise exception).
144
145 If you set FTextureImage, you have to set it to something
146 returned by LoadTextureImage. See TextureImage docs.
147
148 Set WasCacheUsed here. @true means you loaded the data using Cache.
149 For FTextureVideo, it's Cache property should also be set to
150 our Cache, this happens automatically in Video_IncReference.
151
152 Also, set FTextureUsedFullUrl here.
153
154 In this class, this simply produces WritelnWarning with
155 "not implemented" message and returns @nil. It's not declared
156 as abstract, because there may be classes descending from this,
157 and we want to at least be able to parse them
158 and then ignore (while not overriden abstract method would cause
159 simple crashes). }
160 procedure LoadTextureData(out WasCacheUsed: boolean); virtual;
161
162 function AlphaChannelData: TAlphaChannel; override;
163 public
164 constructor Create(const AX3DName: string = ''; const ABaseUrl: String = ''); override;
165 destructor Destroy; override;
166
167 { TextureImage, TextureComposite and TextureVideo contain actual texture data.
168 TextureImage may come from inline VRML texture or could be loaded
169 from file (including from some URL), this doesn't concern you here.
170
171 Calls to TextureImage, TextureVideo, IsTextureImage, IsTextureVideo,
172 TextureComposite
173 will automatically load the data, so in simple situations you really
174 don't need to do anything. Just check and use them when you want,
175 and things will just work. See IsTextureLoaded for more control
176 about loading / unloading.
177
178 Note that either one of TextureImage or TextureVideo may be @nil,
179 if the other one is loaded. Or when loading failed
180 (warning will be reported by WritelnWarning).
181 IsTextureImage checks that TextureImage is non-nil (so it's successfully
182 loaded) and additionally that texture size is not zero.
183 Similar for IsTextureVideo.
184
185 Note that when image failed to load, or URL was just empty,
186 we can have IsTextureLoaded = @true but both IsTextureImage = @false
187 and IsTextureVideo = @false.
188
189 TextureImage may have any class allowed by LoadTextureImage.
190
191 @groupBegin }
192 function TextureImage: TEncodedImage;
193 function IsTextureImage: boolean;
194 function TextureComposite: TCompositeImage;
195 function TextureVideo: TVideo;
196 function IsTextureVideo: boolean;
197 { @groupEnd }
198
199 { Is the texture data already loaded.
200 Since the texture will be loaded automatically, you're usually
201 not interested in this property. You can read it to e.g. predict
202 if next TextureImage / TextureVideo call may take a long time.
203 (You know that if IsTextureLoaded = @true then TextureImage
204 just returns ready image instantly).
205
206 You can also set IsTextureLoaded.
207 Setting to @true means that you request the texture to be loaded @italic(now),
208 if it's not loaded already. Setting to @false may be useful if you want
209 to release resources (e.g. when you want to keep TTextureNode instance
210 loaded but you know that you will not need
211 TextureImage / TextureComposite / TextureVideo anymore).
212 You can also set it to @false and then back to @true if you want to
213 request reloading the texture from URL (e.g. if you suspect that
214 the URL contents changed).
215
216 Note that IsTextureLoaded is set to @true, even if actual loading
217 failed. You still have to check afterwards IsTextureImage and
218 IsTextureVideo to know if loading was actually successful.
219 This is deliberate --- it means that each call to TextureImage etc.
220 will not unnecessarily read the disk (or even connect to internet)
221 when the file does not exist. Also, the loading errors reported
222 by WritelnWarning will not be repeated --- they will
223 occur only once, when IsTextureLoaded changes from @false to @true. }
224 property IsTextureLoaded: boolean
225 read FIsTextureLoaded write SetIsTextureLoaded;
226
227 { Once the texture data (image or video) is loaded,
228 this is set to the URL that was used to load,
229 or '' if no URL was used. "No URL was used" may mean that
230 no URL was valid, or inlined image was used.
231
232 This is always a full, expanded (i.e. not relative) URL.
233
234 In case of data: URLs, this doesn't contain actual data (it would
235 be too long then, and TextureUsedFullUrl is mainly for showing to the
236 user), it's cutted. }
237 property TextureUsedFullUrl: String read FTextureUsedFullUrl;
238
239 {$I auto_generated_node_helpers/x3dnodes_x3dtexture2dnode.inc}
240 end;
241
242 TAbstractX3DTexture2DNode = TAbstractTexture2DNode deprecated 'use TAbstractTexture2DNode';
243
244 { Base for all nodes which specify a transformation of texture coordinates. }
245 TAbstractTextureTransformNode = class(TAbstractAppearanceChildNode)
246 public
247 function TransformMatrix: TMatrix4; virtual; abstract;
248 {$I auto_generated_node_helpers/x3dnodes_x3dtexturetransformnode.inc}
249 end;
250
251 { Base for all nodes which specify a texture coordinate transform, but not MultiTextureTransform. }
252 TAbstractSingleTextureTransformNode = class(TAbstractTextureTransformNode)
253 {$I auto_generated_node_helpers/x3dnodes_x3dsingletexturetransformnode.inc}
254 end;
255
256 { Texture image loaded from a file. }
257 TImageTextureNode = class(TAbstractTexture2DNode)
258 strict private
259 function LoadOptions: TLoadImageOptions;
260 strict protected
261 procedure LoadTextureData(out WasCacheUsed: boolean); override;
262 public
263 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
264
265 function TextureDescription: string; override;
266
267 { Load image contents from a stream.
268
269 If UpdateUrl is not empty, then this also sets the @link(FdUrl) field
270 to the indicated value (without actually loading the image from this URL).
271 This is useful if you later may serialize this TImageTextureNode:
272 thus URL will represent this image in the output.
273 Note: aside from normal URLs (file, http and such protocols),
274 you can always set this URL to a "data URI" that would encode the image contents.
275 See CGE example tools/to-data-uri/to-data-uri.lpr for an example. }
276 procedure LoadFromStream(const Stream: TStream; const MimeType: String; const UpdateUrl: String);
277
278 { Load image contents from a ready TEncodedImage instance.
279
280 If TakeImageOwnership = @true then we take given Image reference,
281 and the lifetime of this Image object will be further managed by this TImageTextureNode
282 class (so you should no longer free it yourself).
283 If TakeImageOwnership = @false then we only copy Image contents
284 (this is slower, but it means that ownership and freeing of given
285 Image instance remains on your side).
286
287 If UpdateUrl is not empty, then this also sets the @link(FdUrl) field
288 to the indicated value (without actually loading the image from this URL).
289 This is useful if you later may serialize this TImageTextureNode:
290 thus URL will represent this image in the output.
291 Note: aside from normal URLs (file, http and such protocols),
292 you can always set this URL to a "data URI" that would encode the image contents.
293 See CGE example tools/to-data-uri/to-data-uri.lpr for an example. }
294 procedure LoadFromImage(const Image: TEncodedImage;
295 const TakeImageOwnership: Boolean; const UpdateUrl: String);
296
297 {$I auto_generated_node_helpers/x3dnodes_imagetexture.inc}
298 end;
299
300 { Movie file, that can be played and displayed as a texture. }
301 TMovieTextureNode = class(TAbstractTexture2DNode)
302 strict private
303 FDuration: TFloatTime;
304 FTimeFunctionality: TTimeDependentFunctionality;
305 { Final length (in seconds) of this movie, adjusted by Speed.
306 See @link(TTimeDependentFunctionality.CycleInterval),
307 this must return the relevant value. }
308 function GetCycleInterval: TFloatTime;
309 function IgnoreWhenActive(const ChangingField: TX3DField; const Event: TX3DEvent;
310 const Value: TX3DField; const Time: TX3DTime): Boolean;
311 function IgnoreStopTime(const ChangingField: TX3DField; const Event: TX3DEvent;
312 const Value: TX3DField; const Time: TX3DTime): Boolean;
313 strict protected
314 procedure LoadTextureData(out WasCacheUsed: boolean); override;
315 public
316 constructor Create(const AX3DName: String = ''; const ABaseUrl: String = ''); override;
317 function TextureDescription: string; override;
318
319 { Duration of this movie, in seconds.
320 Duration is initialized from loaded video length (default is -1).
321 So it's automatically initialized when you call IsTextureVideo,
322 TextureVideo methods.
323
324 This is not multiplied by @link(Speed).
325 Use @code(MyMovieTextureNode.TimeFunctionality.CycleInterval)
326 to get this duration multiplied by Abs(Speed).
327
328 This duration is not reset when video is freed (like when you set
329 IsTextureLoaded to @false, maybe implicitly by calling
330 TCastleSceneCore.FreeResources with frTextureDataInNodes).
331 This way this is available even you freed the texture video data to
332 save memory. }
333 property Duration: TFloatTime read FDuration;
334
335 {$I auto_generated_node_helpers/x3dnodes_movietexture.inc}
336 end;
337
338 { Application of several individual textures on top of each other,
339 used instead of a single texture when desired. }
340 TMultiTextureNode = class(TAbstractTextureNode)
341 public
342 function AlphaChannelData: TAlphaChannel; override;
343 {$I auto_generated_node_helpers/x3dnodes_multitexture.inc}
344 end;
345
346 { Multiple texture coordinates per vertex,
347 to be used with multi-texturing by @link(TMultiTextureNode). }
348 TMultiTextureCoordinateNode = class(TAbstractTextureCoordinateNode)
349 {$I auto_generated_node_helpers/x3dnodes_multitexturecoordinate.inc}
350 end;
351
352 { Multiple texture transforms,
353 to be used with multi-texturing by @link(TMultiTextureNode). }
354 TMultiTextureTransformNode = class(TAbstractTextureTransformNode)
355 public
356 { For MultiTextureTransform, this always raises an internal error.
357 Reason: you cannot get single texture transform matrix from
358 MultiTextureTransform.
359
360 @raises(EInternalError Always, since this method has no sense
361 for MultiTextureTransform.) }
362 function TransformMatrix: TMatrix4; override;
363
364 {$I auto_generated_node_helpers/x3dnodes_multitexturetransform.inc}
365 end;
366
367 { Texture specified as an explicit array of pixel values (see @link(FdImage) field).
368
369 This is useful when authoring X3D, as you can place texture contents directly
370 inside the X3D file (without the need for any external file).
371
372 PixelTexture is also comfortable when using Object Pascal to construct
373 the X3D graph. In this case, it allows to provide an image as a ready
374 TCastleImage instance, by changing the value of the
375 @code(TPixelTextrueNode.FdImage.Value).
376
377 An alternative to PixelTexture is to use "data URI".
378 With "data URI", you can embed any file contents inside an URL.
379 This way, you can use @link(TImageTextureNode ImageTexture),
380 and inside @code(ImageTexture.url) field
381 you can place an embedded image contents (instead of a normal URL or filename).
382 To convert your image file to a "data URI", you can our tool "to_data_uri".
383 The image contents stay compressed this way (although expressed in base64),
384 so it may be more compact than PixelTexture.
385 }
386 TPixelTextureNode = class(TAbstractTexture2DNode)
387 strict protected
388 procedure LoadTextureData(out WasCacheUsed: boolean); override;
389 public
390 function TextureDescription: string; override;
391 {$I auto_generated_node_helpers/x3dnodes_pixeltexture.inc}
392 end;
393
394 { Internal TPixelTextureNode descendant for nodes that may be used
395 by many scenes at once (right now this just means: FontTexture),
396 Such nodes need special protection to not free their rendering resources
397 too early (e.g. when TCastleScene using them is destroyed). }
398 TInternalReusedPixelTextureNode = class(TPixelTextureNode)
399
400 end;
401
402 { 2D texture coordinates used by vertex-based geometry nodes. }
403 TTextureCoordinateNode = class(TAbstractSingleTextureCoordinateNode)
404 {$I auto_generated_node_helpers/x3dnodes_texturecoordinate.inc}
405 end;
406
407 { Automatic generation of texture coordinates. }
408 TTextureCoordinateGeneratorNode = class(TAbstractSingleTextureCoordinateNode)
409 {$I auto_generated_node_helpers/x3dnodes_texturecoordinategenerator.inc}
410 end;
411
412 { Boundary modes for texture coordinates.
413 See @link(TTexturePropertiesNode.BoundaryModeS),
414 @link(TTexturePropertiesNode.BoundaryModeT),
415 @link(TTexturePropertiesNode.BoundaryModeR). }
416 TBoundaryMode = (
417 bmClamp, //< Clamp texture coordinates to [0..1]. Equivalent to bmClampToEdge.
418 bmClampToEdge, //< Clamp texture coordinates to [0..1].
419 bmClampToBoundaryUnsupported, //< Clamp texture coordinates to [0..1]. Equivalent to bmClampToEdge. See https://castle-engine.io/x3d_implementation_texturing.php.
420 bmMirroredRepeat, //< Repeat the texture, switching between original and flipped texture.
421 bmRepeat //< Repeat the texture.
422 );
423
424 { Adjust the texture application properties. }
425 TTexturePropertiesNode = class(TAbstractNode)
426 strict private
427 function GetMinificationFilter: TAutoMinificationFilter;
428 procedure SetMinificationFilter(const Value: TAutoMinificationFilter);
429 function GetMagnificationFilter: TAutoMagnificationFilter;
430 procedure SetMagnificationFilter(const Value: TAutoMagnificationFilter);
431 public
432 property MagnificationFilter: TAutoMagnificationFilter
433 read GetMagnificationFilter write SetMagnificationFilter;
434
435 property MinificationFilter: TAutoMinificationFilter
436 read GetMinificationFilter write SetMinificationFilter;
437
438 {$I auto_generated_node_helpers/x3dnodes_textureproperties.inc}
439 end;
440
441 { 2D transformation that can be applied to texture coordinates (e.g. from
442 @link(TTextureCoordinateNode). }
443 TTextureTransformNode = class(TAbstractSingleTextureTransformNode)
444 public
445 function TransformMatrix: TMatrix4; override;
446 {$I auto_generated_node_helpers/x3dnodes_texturetransform.inc}
447 end;
448
449 {$endif read_interface}
450
451 {$ifdef read_implementation}
452
453 { TAbstractTextureNode ------------------------------------------------------- }
454
455 procedure TAbstractTextureNode.SetInternalRendererResource(const Value: TInternalRendererResource);
456 begin
457 if FInternalRendererResource <> Value then
458 begin
459 FInternalRendererResource := Value;
460 if not FContextCloseEventSetup then
461 begin
462 FContextCloseEventSetup := true;
463 ApplicationProperties.OnGLContextCloseObject.Add(
464 {$ifdef FPC}@{$endif} GLContextCloseEvent);
465 end;
466 end;
467 end;
468
469 procedure TAbstractTextureNode.GLContextCloseEvent(Sender: TObject);
470 begin
471 InternalRendererResourceFree;
472 end;
473
474 procedure TAbstractTextureNode.InternalRendererResourceFree;
475 begin
476 FreeAndNil(FInternalRendererResource);
477 end;
478
479 destructor TAbstractTextureNode.Destroy;
480 begin
481 GLContextCloseEvent(nil);
482 if FContextCloseEventSetup then
483 ApplicationProperties.OnGLContextCloseObject.Remove(
484 {$ifdef FPC}@{$endif} GLContextCloseEvent);
485 inherited;
486 end;
487
488 function TAbstractTextureNode.AlphaChannelData: TAlphaChannel;
489 begin
490 Result := acNone;
491 end;
492
493 function TAbstractTextureNode.AlphaChannelFinal: TAlphaChannel;
494 begin
495 Result := AlphaChannelData;
496 end;
497
498 function TAbstractTextureNode.TextureDescription: string;
499 begin
500 Result := X3DType;
501 end;
502
503 { TAbstractSingleTextureNode -------------------------------------------------------- }
504
505 function TAbstractSingleTextureNode.AlphaChannelFinal: TAlphaChannel;
506 var
507 Res: TAutoAlphaChannel;
508 begin
509 Res := AlphaChannel;
510 if Res = acAuto then
511 Result := AlphaChannelData
512 else
513 Result := Res;
514 end;
515
516 { TAbstractTexture2DNode ----------------------------------------------------------- }
517
518 constructor TAbstractTexture2DNode.Create(const AX3DName: string = ''; const ABaseUrl: String = '');
519 begin
520 inherited;
521 UsedCache := nil;
522 FIsTextureLoaded := false;
523 end;
524
525 destructor TAbstractTexture2DNode.Destroy;
526 begin
527 FreeAndNilTextureData;
528 inherited;
529 end;
530
531 procedure TAbstractTexture2DNode.FreeAndNilTextureData;
532 begin
533 if FTextureImage <> nil then
534 begin
535 if UsedCache <> nil then
536 begin
537 UsedCache.TextureImage_DecReference(FTextureImage, FTextureComposite);
538 UsedCache := nil;
539 end else
540 begin
541 FreeAndNil(FTextureImage);
542 FreeAndNil(FTextureComposite);
543 end;
544 end;
545
546 if FTextureVideo <> nil then
547 begin
548 if UsedCache <> nil then
549 begin
550 UsedCache.Video_DecReference(FTextureVideo);
551 UsedCache := nil;
552 end else
553 FreeAndNil(FTextureVideo);
554 end;
555 end;
556
557 function TAbstractTexture2DNode.TextureImage: TEncodedImage;
558 begin
559 { Setting IsTextureLoaded property will initialize FTextureImage. }
560 IsTextureLoaded := true;
561
562 Result := FTextureImage;
563 end;
564
565 function TAbstractTexture2DNode.IsTextureImage: boolean;
566 begin
567 Result := (TextureImage <> nil) and (not TextureImage.IsEmpty);
568 end;
569
570 function TAbstractTexture2DNode.TextureComposite: TCompositeImage;
571 begin
572 { Setting IsTextureLoaded property will initialize
573 FTextureImage, FTextureComposite. }
574 IsTextureLoaded := true;
575
576 Result := FTextureComposite;
577 end;
578
579 function TAbstractTexture2DNode.TextureVideo: TVideo;
580 begin
581 { Setting IsTextureLoaded property will initialize FTextureVideo. }
582 IsTextureLoaded := true;
583
584 Result := FTextureVideo;
585 end;
586
587 function TAbstractTexture2DNode.IsTextureVideo: boolean;
588 begin
589 Result := (TextureVideo <> nil) and
590 (TextureVideo.Width <> 0) and
591 (TextureVideo.Height <> 0);
592 end;
593
594 procedure TAbstractTexture2DNode.SetIsTextureLoaded(Value: boolean);
595
596 procedure DoLoadTexture;
597 var
598 WasCacheUsed: boolean;
599 begin
600 FreeAndNilTextureData;
601
602 LoadTextureData(WasCacheUsed);
603 if WasCacheUsed then
604 UsedCache := X3DCache;
605 end;
606
607 begin
608 if Value <> FIsTextureLoaded then
609 begin
610 if Value then
611 begin
612 { actually load the texture }
613 DoLoadTexture;
614 end else
615 begin
616 { unload the texture }
617 FreeAndNilTextureData;
618 end;
619
620 FIsTextureLoaded := Value;
621 end;
622 end;
623
624 procedure TAbstractTexture2DNode.LoadTextureData(out WasCacheUsed: boolean);
625 begin
626 WasCacheUsed := false;
627 FTextureUsedFullUrl := '';
628
629 WritelnWarning('VRML/X3D', Format('Loading textures from "%s" node not implemented', [X3DType]));
630 end;
631
632 function TAbstractTexture2DNode.AlphaChannelData: TAlphaChannel;
633 begin
634 Result := FAlphaChannelData;
635 end;
636
637 { TImageTextureNode ---------------------------------------------------------- }
638
639 constructor TImageTextureNode.Create(const AX3DName, ABaseUrl: String);
640 begin
641 inherited;
642 AddFunctionality(TUrlFunctionality.Create(Self));
643 end;
644
645 function TImageTextureNode.LoadOptions: TLoadImageOptions;
646 begin
647 Result := [];
648 if FlipVertically then
649 Include(Result, liFlipVertically);
650 end;
651
652 procedure TImageTextureNode.LoadTextureData(out WasCacheUsed: boolean);
653 var
654 I: Integer;
655 FullUrl, ErrorMessage: string;
656 Success: boolean;
657 begin
658 WasCacheUsed := false;
659 FTextureUsedFullUrl := '';
660 Success := false;
661 ErrorMessage := '';
662
663 for I := 0 to FdUrl.Count - 1 do
664 if FdUrl.Items[I] = '' then
665 begin
666 { Special error message in this case, otherwise empty URL
667 would be expanded by PathFromBaseUrl to directory
668 and produce unclear error message. }
669 ErrorMessage := ErrorMessage + NL + ' Empty URL ignored';
670 end else
671 begin
672 FullUrl := PathFromBaseUrl(FdUrl.Items[I]);
673 try
674 FTextureImage := X3DCache.TextureImage_IncReference(
675 FullUrl, FTextureComposite, FAlphaChannelData, LoadOptions);
676 WasCacheUsed := true;
677 if WarnAboutAbsoluteFilenames and
678 AbsoluteFileURI(FdUrl.Items[I]) and
679 { AbsoluteFileURI mistakes Blender relative paths '//xxx' as absolute,
680 so eliminate them below. }
681 not BlenderRelativePath(FdUrl.Items[I]) then
682 WritelnWarning('VRML/X3D', Format('Loaded data from an absolute filename "%s", this makes the data possibly unportable (it will probably not work on other systems/locations). Always use relative paths.',
683 [FdUrl.Items[I]]));
684 FTextureUsedFullUrl := UriDisplay(FullUrl);
685 Success := true;
686 Break;
687 except
688 on E: Exception do
689 { Silence the Exception, continue trying to load more textures. }
690 ErrorMessage := ErrorMessage + NL + ' ' + Format(SLoadError,
691 [E.ClassName, 'texture', UriDisplay(FullUrl), E.Message]);
692 end;
693 end;
694
695 if ErrorMessage <> '' then
696 begin
697 if Success then
698 WritelnLog('Texture', 'Some of the texture URLs failed to load, although we found one URL that succeeded:' +
699 ErrorMessage)
700 else
701 WritelnWarning('Texture', 'Cannot load the texture:' + ErrorMessage);
702 end;
703 { Note that when Success = false but ErrorMessage = '', then we're quiet
704 about it. This happens when Urls.Count = 0. }
705 end;
706
707 function TImageTextureNode.TextureDescription: string;
708 begin
709 if TextureUsedFullUrl <> '' then
710 Result := 'image from file "' + TextureUsedFullUrl + '"' else
711 Result := 'none';
712 end;
713
714 procedure TImageTextureNode.LoadFromStream(const Stream: TStream; const MimeType: String; const UpdateUrl: String);
715 var
716 Image: TEncodedImage;
717 begin
718 Image := LoadEncodedImage(Stream, MimeType, [], LoadOptions);
719 LoadFromImage(Image, true, UpdateUrl);
720 end;
721
722 procedure TImageTextureNode.LoadFromImage(const Image: TEncodedImage;
723 const TakeImageOwnership: Boolean; const UpdateUrl: String);
724 var
725 SavedChanged: TX3DChange;
726 begin
727 FreeAndNilTextureData;
728
729 if TakeImageOwnership then
730 FTextureImage := Image
731 else
732 FTextureImage := Image.CreateCopy;
733
734 { update things that need to be updated when loading image }
735 FAlphaChannelData := FTextureImage.AlphaChannel;
736 FIsTextureLoaded := true;
737 UsedCache := nil;
738
739 if UpdateUrl <> '' then
740 begin
741 FTextureUsedFullUrl := UpdateUrl;
742 { Deliberately change FdUrl value in low-level fashion,
743 without triggering Scene.InternalChangedField,
744 because we never want to actually load contents of UpdateUrl. }
745 FdUrl.Items.Clear;
746 FdUrl.Items.Add(UpdateUrl);
747 end;
748
749 if Scene <> nil then
750 begin
751 { Call InternalChangedField(FdUrl) to update rendering resources
752 determined by the new TImageTextureNode.TextureImage.
753 But use special mode, chTextureRendererProperties,
754 instead of default chTextureImage, because chTextureImage unloads
755 image (set IsTextureLoaded:=false) which would reject the image contents
756 we just loaded. }
757 SavedChanged := FdUrl.ChangeAlways;
758 FdUrl.ChangeAlways := chTextureRendererProperties;
759 Scene.InternalChangedField(FdUrl);
760 FdUrl.ChangeAlways := SavedChanged;
761 end;
762 end;
763
764 { TMovieTextureNode ---------------------------------------------------------- }
765
766 constructor TMovieTextureNode.Create(const AX3DName, ABaseUrl: String);
767 begin
768 inherited;
769 FdStartTime.OnInputIgnore := {$ifdef FPC}@{$endif} IgnoreWhenActive;
770 FdStopTime.OnInputIgnore := {$ifdef FPC}@{$endif} IgnoreStopTime;
771 FDuration := -1;
772
773 AddFunctionality(TUrlFunctionality.Create(Self));
774
775 FTimeFunctionality := TTimeDependentFunctionality.Create(Self);
776 FTimeFunctionality.Fdloop := FdLoop;
777 FTimeFunctionality.FdpauseTime := FdPauseTime;
778 FTimeFunctionality.FdresumeTime := FdResumeTime;
779 FTimeFunctionality.FdstartTime := FdStartTime;
780 FTimeFunctionality.FdstopTime := FdStopTime;
781 FTimeFunctionality.EventisActive:= EventisActive;
782 FTimeFunctionality.EventisPaused := EventisPaused;
783 FTimeFunctionality.EventelapsedTime := EventelapsedTime;
784 FTimeFunctionality.OnCycleInterval := {$ifdef FPC}@{$endif} GetCycleInterval;
785
786 AddFunctionality(FTimeFunctionality);
787 end;
788
789 function TMovieTextureNode.IgnoreWhenActive(
790 const ChangingField: TX3DField; const Event: TX3DEvent;
791 const Value: TX3DField; const Time: TX3DTime): Boolean;
792 begin
793 Result := {(InternalNeverIgnore = 0) and} FTimeFunctionality.IsActive;
794 end;
795
796 function TMovieTextureNode.IgnoreStopTime(
797 const ChangingField: TX3DField; const Event: TX3DEvent;
798 const Value: TX3DField; const Time: TX3DTime): Boolean;
799 begin
800 Result := {(InternalNeverIgnore = 0) and}
801 FTimeFunctionality.IsActive and
802 ( (Value as TSFTime).Value <= FdStartTime.Value );
803 end;
804
805 procedure TMovieTextureNode.LoadTextureData(out WasCacheUsed: boolean);
806
807 function LoadOptions: TLoadImageOptions;
808 begin
809 Result := [];
810 if FlipVertically then
811 Include(Result, liFlipVertically);
812 end;
813
814 var
815 I: Integer;
816 FullUrl: String;
817 begin
818 WasCacheUsed := true;
819 FTextureUsedFullUrl := '';
820
821 for I := 0 to FdUrl.Count - 1 do
822 begin
823 FullUrl := PathFromBaseUrl(FdUrl.Items[I]);
824 try
825 FTextureVideo := X3DCache.Video_IncReference(
826 FullUrl, FAlphaChannelData, LoadOptions);
827
828 { if loading succeded, set WasCacheUsed and others and break. }
829 WasCacheUsed := true;
830 FTextureUsedFullUrl := FullUrl;
831 FDuration := FTextureVideo.TimeDuration;
832 if Scene <> nil then
833 EventDuration_Changed.Send(FDuration, Scene.NextEventTime);
834 Break;
835 except
836 on E: Exception do
837 { Remember that WritelnWarning *may* raise an exception. }
838 WritelnWarning('Video', Format(SLoadError,
839 [E.ClassName, 'video', UriDisplay(FullUrl), E.Message]));
840 end;
841 end;
842 end;
843
844 function TMovieTextureNode.GetCycleInterval: TFloatTime;
845 var
846 Sp: Single;
847 begin
848 Sp := Speed;
849 if Sp <> 0 then
850 Result := FDuration / Abs(Sp)
851 else
852 Result := 0;
853 end;
854
855 function TMovieTextureNode.TextureDescription: string;
856 begin
857 if TextureUsedFullUrl <> '' then
858 Result := 'video from file "' + TextureUsedFullUrl + '"' else
859 Result := 'none';
860 end;
861
862 function TMultiTextureNode.AlphaChannelData: TAlphaChannel;
863 var
864 ChildTex: TX3DNode;
865 I: Integer;
866 begin
867 Result := acNone;
868 for I := 0 to FdTexture.Count - 1 do
869 begin
870 ChildTex := FdTexture[I];
871 if (ChildTex <> nil) and
872 (ChildTex is TAbstractSingleTextureNode) then
873 AlphaMaxVar(Result, TAbstractSingleTextureNode(ChildTex).AlphaChannelFinal);
874 end;
875 end;
876
877 function TMultiTextureTransformNode.TransformMatrix: TMatrix4;
878 begin
879 raise EInternalError.Create('You cannot get single TransformMatrix from MultiTextureTransform node');
880 Result := TMatrix4.Identity; { avoid warnings that result not set }
881 end;
882
883 { TPixelTextureNode ---------------------------------------------------------- }
884
885 procedure TPixelTextureNode.LoadTextureData(out WasCacheUsed: boolean);
886 begin
887 WasCacheUsed := false;
888
889 if not FdImage.Value.IsEmpty then
890 begin
891 FTextureImage := FdImage.Value.MakeCopy;
892 FAlphaChannelData := FdImage.Value.AlphaChannel;
893 end;
894 end;
895
896 function TPixelTextureNode.TextureDescription: string;
897 begin
898 if not FdImage.Value.IsEmpty then
899 result := Format('inlined image (width = %d; height = %d; with alpha = %s)',
900 [ FdImage.Value.Width,
901 FdImage.Value.Height,
902 BoolToStr(FdImage.Value.HasAlpha, true) ]) else
903 result := 'none';
904 end;
905
906 const
907 BoundaryModeNames: array [TBoundaryMode] of string = (
908 'CLAMP',
909 'CLAMP_TO_EDGE',
910 'CLAMP_TO_BOUNDARY',
911 'MIRRORED_REPEAT',
912 'REPEAT'
913 );
914
915 function TTexturePropertiesNode.GetMinificationFilter: TAutoMinificationFilter;
916 var
917 S: string;
918 begin
919 S := UpperCase(FdMinificationFilter.Value);
920
921 if S = 'AVG_PIXEL' then Result := minLinear else
922 if S = 'AVG_PIXEL_AVG_MIPMAP' then Result := minLinearMipmapLinear else
923 if S = 'AVG_PIXEL_NEAREST_MIPMAP' then Result := minLinearMipmapNearest else
924 if S = 'NEAREST_PIXEL_AVG_MIPMAP' then Result := minNearestMipmapLinear else
925 if S = 'NEAREST_PIXEL_NEAREST_MIPMAP' then Result := minNearestMipmapNearest else
926 if S = 'NEAREST_PIXEL' then Result := minNearest else
927
928 if S = 'DEFAULT' then Result := minDefault else
929 if S = 'FASTEST' then Result := minFastest else
930 if S = 'NICEST' then Result := minNicest else
931
932 if S = 'NEAREST' then
933 begin
934 WritelnWarning('VRML/X3D', Format('"%s" is not allowed texture minification, this is an InstantReality extension, please fix to "NEAREST_PIXEL"', [S]));
935 Result := minNearest;
936 end else
937
938 if S = 'LINEAR' then
939 begin
940 WritelnWarning('VRML/X3D', Format('"%s" is not allowed texture minification, this is an InstantReality extension, please fix to "AVG_PIXEL"', [S]));
941 Result := minLinear;
942 end else
943
944 begin
945 Result := minDefault;
946 WritelnWarning('VRML/X3D', Format('Unknown texture minification filter "%s"', [S]));
947 end;
948 end;
949
950 procedure TTexturePropertiesNode.SetMinificationFilter(const Value: TAutoMinificationFilter);
951 const
952 Names: array [TAutoMinificationFilter] of string = (
953 'NEAREST_PIXEL',
954 'AVG_PIXEL',
955 'NEAREST_PIXEL_NEAREST_MIPMAP',
956 'NEAREST_PIXEL_AVG_MIPMAP',
957 'AVG_PIXEL_NEAREST_MIPMAP',
958 'AVG_PIXEL_AVG_MIPMAP',
959 'DEFAULT',
960 'FASTEST',
961 'NICEST'
962 );
963 begin
964 FdMinificationFilter.Send(Names[Value]);
965 end;
966
967 function TTexturePropertiesNode.GetMagnificationFilter: TAutoMagnificationFilter;
968 var
969 S: string;
970 begin
971 S := UpperCase(FdMagnificationFilter.Value);
972
973 if S = 'AVG_PIXEL' then Result := magLinear else
974 if S = 'NEAREST_PIXEL' then Result := magNearest else
975
976 if S = 'DEFAULT' then Result := magDefault else
977 if S = 'FASTEST' then Result := magFastest else
978 if S = 'NICEST' then Result := magNicest else
979
980 if S = 'NEAREST' then
981 begin
982 WritelnWarning('VRML/X3D', Format('"%s" is not allowed texture magnification, this is an InstantReality extension, please fix to "NEAREST_PIXEL"', [S]));
983 Result := magNearest;
984 end else
985
986 if S = 'LINEAR' then
987 begin
988 WritelnWarning('VRML/X3D', Format('"%s" is not allowed texture magnification, this is an InstantReality extension, please fix to "AVG_PIXEL"', [S]));
989 Result := magLinear;
990 end else
991
992 begin
993 Result := magDefault;
994 WritelnWarning('VRML/X3D', Format('Unknown texture minification filter "%s"', [S]));
995 end;
996 end;
997
998 procedure TTexturePropertiesNode.SetMagnificationFilter(const Value: TAutoMagnificationFilter);
999 const
1000 Names: array [TAutoMagnificationFilter] of string = (
1001 'NEAREST_PIXEL',
1002 'AVG_PIXEL',
1003 'DEFAULT',
1004 'FASTEST',
1005 'NICEST'
1006 );
1007 begin
1008 FdMagnificationFilter.Send(Names[Value]);
1009 end;
1010
1011 { TTextureTransformNode ------------------------------------------------------ }
1012
1013 function TTextureTransformNode.TransformMatrix: TMatrix4;
1014 begin
1015 { Yes, VRML 2 and X3D specs say in effect that the order of operations
1016 is *reversed* with regards to VRML 1 spec.
1017 VRML 1 spec says it's (in order) scale, rotation, translation.
1018 VRML 2 / X3D spec say it's (in order) translation, rotation, scale.
1019
1020 Moreover, VRML 2 / X3D spec give explicit formula which we follow:
1021 Tc' = -C * S * R * C * T * Tc
1022
1023 To test that this order matters, check e.g. VRML NIST test suite,
1024 "Appearance -> TextureTransform" tests 15, 16 (ImageTexture),
1025 31, 32 (MovieTexture) and 47, 48 (PixelTexture).
1026 Current implementation passes it (results match images).
1027 Also, results match Xj3d and OpenVRML results.
1028
1029 Other links:
1030
1031 - At least looking at source code, some old version of
1032 FreeWRL had it reversed (matching VRML 1):
1033 [http://search.cpan.org/src/LUKKA/FreeWRL-0.14/VRMLFunc.xs]
1034 function TextureTransform_Rend.
1035
1036 - Other: [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4320634] }
1037
1038 Result :=
1039 TranslationMatrix(Vector3( -FdCenter.Value[0], -FdCenter.Value[1], 0 )) *
1040 ScalingMatrix(Vector3( FdScale.Value[0], FdScale.Value[1], 1 )) *
1041 RotationMatrixRad(FdRotation.Value, Vector3(0, 0, 1)) *
1042 TranslationMatrix( Vector3(
1043 FdTranslation.Value[0] + FdCenter.Value[0],
1044 FdTranslation.Value[1] + FdCenter.Value[1], 0));
1045 end;
1046
1047 procedure RegisterTexturingNodes;
1048 begin
1049 NodesManager.RegisterNodeClasses([
1050 TImageTextureNode,
1051 TMovieTextureNode,
1052 TMultiTextureNode,
1053 TMultiTextureCoordinateNode,
1054 TMultiTextureTransformNode,
1055 TPixelTextureNode,
1056 TTextureCoordinateNode,
1057 TTextureCoordinateGeneratorNode,
1058 TTexturePropertiesNode,
1059 TTextureTransformNode
1060 ]);
1061 end;
1062
1063 {$endif read_implementation}