Debian Codegraph @

src/scene/load/x3dloadinternalobj.pas

raw
1 {
2 Copyright 2002-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 { Load Wavefront OBJ 3D format (with an accompanying MTL).
17 See [http://www.fileformat.info/format/wavefrontobj/]
18 and [http://www.fileformat.info/format/material/]. }
19 unit X3DLoadInternalOBJ;
20
21 {$I castleconf.inc}
22
23 interface
24
25 var
26 WavefrontPhongMaterials: Boolean = true;
27
28 implementation
29
30 uses Math, SysUtils, Classes, Generics.Collections,
31 CastleStringUtils, CastleFilesUtils, CastleLog, CastleVectors, CastleUtils,
32 CastleClassUtils, X3DLoadInternalUtils, CastleUriUtils, CastleColors,
33 CastleDownload, X3DNodes, X3DLoad;
34
35 { TWavefrontTexture ---------------------------------------------------------- }
36
37 type
38 TWavefrontTexture = record
39 URL: String;
40 BlendU, BlendV, Clamp: Boolean;
41 ColorCorrection: Boolean; // not for NormalTexture
42 Offset, Scale, Turbulence: TVector3;
43 BumpMultiplier: Single; // only for NormalTexture
44 procedure Init;
45 procedure ReadFromLine(const S: String);
46 function CreateNode(const BaseUrl: String): TImageTextureNode;
47 function CreateTextureTransformNode: TTextureTransform3DNode;
48 end;
49
50 procedure TWavefrontTexture.Init;
51 begin
52 URL := '';
53 BlendU := true;
54 BlendV := true;
55 Clamp := false;
56 ColorCorrection := true;
57 Offset := TVector3.Zero;
58 Scale := Vector3(1, 1, 1);
59 Turbulence := TVector3.Zero;
60 BumpMultiplier := 1;
61 end;
62
63 procedure TWavefrontTexture.ReadFromLine(const S: String);
64 var
65 SeekPos: Integer;
66
67 procedure ReadBoolean(var Value: Boolean);
68 var
69 Token: String;
70 begin
71 Token := NextToken(S, SeekPos);
72 if SameText(Token, 'on') then
73 Value := true
74 else
75 if SameText(Token, 'off') then
76 Value := false
77 else
78 WritelnWarning('Expected "on" of "off", got "%s"', [Token]);
79 end;
80
81 procedure ReadSingle(var Value: Single);
82 var
83 Token: String;
84 begin
85 Token := NextToken(S, SeekPos);
86 Value := StrToFloatDefDot(Token, Value);
87 end;
88
89 procedure ReadVector3(var Value: TVector3);
90 var
91 NewSeekPos, I: Integer;
92 Token: String;
93 begin
94 for I := 0 to 2 do
95 begin
96 NewSeekPos := SeekPos;
97 Token := NextToken(S, NewSeekPos);
98 try
99 Value.Data[I] := StrToFloatDefDot(Token, Value.Data[I]);
100 // update SeekPos if this is a successfull float, as Y and Z vector values are optional in MTL
101 SeekPos := NewSeekPos;
102 except
103 on EConvertError do
104 Exit; // Y and Z vector values are optional in MTL, so just exit if missing
105 end;
106 end;
107 end;
108
109 var
110 Token: String;
111 begin
112 Init;
113
114 SeekPos := 1;
115 repeat
116 Token := NextToken(S, SeekPos);
117 if Token = '' then break;
118
119 { See https://en.wikipedia.org/wiki/Wavefront_.obj_file#Texture_options
120 and http://paulbourke.net/dataformats/mtl/
121 for texture options spec. }
122 if Token = '-blendu' then
123 ReadBoolean(BlendU)
124 else if Token = '-blendv' then
125 ReadBoolean(BlendV)
126 else if Token = '-clamp' then
127 ReadBoolean(Clamp)
128 else if Token = '-cc' then
129 ReadBoolean(ColorCorrection)
130 else if (Token = '-boost') or (Token = '-texres') or (Token = '-imfchan') then
131 begin
132 // skip 1 next token
133 NextToken(S, SeekPos);
134 end else if Token = '-mm' then
135 begin
136 // skip 2 next tokens
137 NextToken(S, SeekPos);
138 NextToken(S, SeekPos);
139 end else if Token = '-o' then
140 ReadVector3(Offset)
141 else if Token = '-s' then
142 ReadVector3(Scale)
143 else if Token = '-t' then
144 ReadVector3(Turbulence)
145 else if Token = '-bm' then
146 ReadSingle(BumpMultiplier)
147 else
148 begin
149 if URL <> '' then
150 WritelnWarning('Texture line contains more than one URL (submit a CGE bug): "%s", "%s"', [
151 URL,
152 Token
153 ]);
154 URL := Token;
155 end;
156
157 until false;
158 end;
159
160 function TWavefrontTexture.CreateNode(const BaseUrl: String): TImageTextureNode;
161 begin
162 if URL <> '' then
163 begin
164 Result := TImageTextureNode.Create('', BaseUrl);
165 Result.SetUrl([SearchTextureFile(BaseUrl, URL)]);
166 Result.RepeatS := not Clamp;
167 Result.RepeatT := not Clamp;
168 end else
169 Result := nil;
170 end;
171
172 function TWavefrontTexture.CreateTextureTransformNode: TTextureTransform3DNode;
173 begin
174 if (URL <> '') and
175 ( (not TVector3.PerfectlyEquals(Scale, Vector3(1, 1, 1))) or
176 (not TVector3.PerfectlyEquals(Offset, Vector3(0, 0, 0)))
177 ) then
178 begin
179 Result := TTextureTransform3DNode.Create;
180 Result.Scale := Scale;
181 Result.Translation := Offset;
182 end else
183 Result := nil;
184 end;
185
186 { ---------------------------------------------------------------------------- }
187
188 type
189 TWavefrontMaterial = class
190 Name: string;
191 AmbientColor, DiffuseColor, SpecularColor, TransmissionColor: TVector3;
192 IlluminationModel: Single;
193 Opacity: Single;
194 SpecularExponent: Single;
195 Sharpness, IndexOfRefraction: Single;
196 DiffuseTexture: TWavefrontTexture;
197 NormalTexture: TWavefrontTexture;
198 RoughnessTexture: TWavefrontTexture;
199
200 { Initializes material with default values.
201 Since Wavefront specification doesn't say what the default values are,
202 we just assign something along the lines of default VRML material. }
203 constructor Create(const AName: string);
204 end;
205
206 TWavefrontMaterialList = class({$ifdef FPC}specialize{$endif} TObjectList<TWavefrontMaterial>)
207 { Find material with given name, @nil if not found. }
208 function TryFindName(const Name: string): TWavefrontMaterial;
209 end;
210
211 TWavefrontFace = class
212 VertIndices, TexCoordIndices, NormalIndices: TInt32List;
213 HasTexCoords: boolean;
214 HasNormals: boolean;
215
216 { Material assigned to this face. @nil means that no material was assigned. }
217 Material: TWavefrontMaterial;
218
219 constructor Create;
220 destructor Destroy; override;
221 end;
222
223 TWavefrontFaceList = {$ifdef FPC}specialize{$endif} TObjectList<TWavefrontFace>;
224
225 { 3D model in OBJ file format. }
226 TObject3DOBJ = class
227 strict private
228 { Lists to fill with vertex, tex coord and normal data }
229 Verts: TVector3List;
230 TexCoords: TVector2List;
231 Normals: TVector3List;
232
233 FFaces: TWavefrontFaceList;
234 FMaterials: TWavefrontMaterialList;
235
236 WarningPerVertexColorDone: Boolean;
237 WarningNanDone: Boolean;
238 public
239 Coord: TCoordinateNode;
240 TexCoord: TTextureCoordinateNode;
241 Normal: TNormalNode;
242
243 constructor Create(const Stream: TStream; const BaseUrl: String);
244 destructor Destroy; override;
245
246 property Faces: TWavefrontFaceList read FFaces;
247 property Materials: TWavefrontMaterialList read FMaterials;
248 end;
249
250 EInvalidOBJFile = class(Exception);
251
252 { Read string to TVector3, ignoring invalid ending,
253 so it handles even incorrect things like '0 0 0c',
254 see https://github.com/castle-engine/castle-engine/pull/76/ }
255 function Vector3FromStrPermissive(const S: string): TVector3;
256 const
257 OnlyNums = AllChars - ['0'..'9', '.', '-','+','e','E'];
258 var
259 SPosition: Integer;
260 begin
261 try
262 Result := Vector3FromStr(S);
263 except
264 on E: EConvertError do
265 begin
266 SPosition := 1;
267 Result.X := StrToFloatDot(NextToken(S, SPosition));
268 Result.Y := StrToFloatDot(NextToken(S, SPosition));
269 Result.Z := StrToFloatDot(NextToken(S, SPosition, OnlyNums));
270 if NextToken(S, SPosition) <> '' then
271 raise EConvertError.Create('Expected end of data when reading vector from string');
272 WritelnWarning('Invalid TVector3 format: "%s", ignored the incorrect characters at the end', [S]);
273 end;
274 end;
275 end;
276
277 { TWavefrontMaterial --------------------------------------------------------- }
278
279 constructor TWavefrontMaterial.Create(const AName: string);
280 begin
281 inherited Create;
282
283 Name := AName;
284
285 AmbientColor := Vector3(0.2, 0.2, 0.2);
286 DiffuseColor := Vector3(0.8, 0.8, 0.8);
287 SpecularColor := Vector3(0, 0, 0);
288
289 { This is not necessarily good, I don't use it anywhere for now }
290 TransmissionColor := Vector3(0, 0, 0);
291
292 { Blender exported writes such illumination, I guess it's good default }
293 IlluminationModel := 2;
294
295 Opacity := 1.0;
296
297 SpecularExponent := 1;
298 Sharpness := 60;
299 IndexOfRefraction := 1;
300
301 DiffuseTexture.Init;
302 NormalTexture.Init;
303 RoughnessTexture.Init;
304 end;
305
306 { TWavefrontMaterialList ---------------------------------------------------- }
307
308 function TWavefrontMaterialList.TryFindName(const Name: string):
309 TWavefrontMaterial;
310 var
311 I: Integer;
312 begin
313 for I := 0 to Count - 1 do
314 begin
315 Result := Items[I];
316 if Result.Name = Name then Exit;
317 end;
318 Result := nil;
319 end;
320
321 { TWavefrontFace ------------------------------------------------------------- }
322
323 constructor TWavefrontFace.Create;
324 begin
325 inherited;
326 VertIndices := TInt32List.Create;
327 TexCoordIndices := TInt32List.Create;
328 NormalIndices := TInt32List.Create;
329 end;
330
331 destructor TWavefrontFace.Destroy;
332 begin
333 FreeAndNil(VertIndices);
334 FreeAndNil(TexCoordIndices);
335 FreeAndNil(NormalIndices);
336 inherited;
337 end;
338
339 { TObject3DOBJ --------------------------------------------------------------- }
340
341 constructor TObject3DOBJ.Create(const Stream: TStream; const BaseUrl: String);
342
343 procedure ReadFacesFromOBJLine(const line: string; Material: TWavefrontMaterial);
344 var
345 Face: TWavefrontFace;
346
347 { Add indexes of next face vertex based on VertexStr. }
348 procedure ReadIndices(const VertexStr: string);
349 var
350 VertexSeekPos: Integer;
351
352 { Reads and updates VertexStr and VertexSeekPos, and sets
353 IndiceExists and adds to IndexList. IndiceExists is set to @false
354 if next indice is indeed empty,
355 or if we're standing at the end of VertexStr string.
356
357 Just call it in sequence to read indices from VertexStr.
358 Remember that empty indice may be followed by non-empty,
359 e.g. VectorStr = '2//3' is allowed, and means that vertex
360 index is 2, there's no texCoord index, and normal index is 3. }
361 procedure ReadIndex(out IndiceExists: boolean;
362 const IndexList: TInt32List; const Count: Cardinal);
363 var
364 NewVertexSeekPos: Integer;
365 Index: Integer;
366
367 begin
368 NewVertexSeekPos := VertexSeekPos;
369
370 while (NewVertexSeekPos <= Length(VertexStr)) and
371 (VertexStr[NewVertexSeekPos] <> '/') do
372 Inc(NewVertexSeekPos);
373
374 IndiceExists := NewVertexSeekPos > VertexSeekPos;
375 if IndiceExists then
376 begin
377 { get signed Index }
378 Index := StrToInt(CopyPos(VertexStr, VertexSeekPos, NewVertexSeekPos - 1));
379 if Index > 0 then
380 { we subtract 1, because indexed in OBJ are 1-based and we prefer 0-based }
381 IndexList.Add(Index - 1) else
382 if Index < 0 then
383 begin
384 Index := Index + Integer(Count);
385 if Index < 0 then
386 raise EInvalidOBJFile.Create('Invalid OBJ: Index is < 0 after summing with current count');
387 IndexList.Add(Index);
388 end else
389 raise EInvalidOBJFile.Create('Invalid OBJ: Index is 0 (should be < 0 for relative and > 0 for absolute index)');
390 end;
391
392 { We add +1 to skip our ending '/' char.
393 Note that we add this even if VertexSeekPos was already
394 > Length(VertexStr), but this is harmless. }
395 VertexSeekPos := NewVertexSeekPos + 1;
396 end;
397
398 var
399 IndiceHasVertex, IndiceHasTexCoord, IndiceHasNormal: boolean;
400 begin
401 VertexSeekPos := 1;
402
403 { read vertex index }
404 ReadIndex(IndiceHasVertex, Face.VertIndices, Verts.Count);
405 if not IndiceHasVertex then
406 raise EInvalidOBJFile.CreateFmt(
407 'Invalid OBJ vertex indexes "%s"', [VertexStr]);
408
409 { read texCoord index }
410 ReadIndex(IndiceHasTexCoord, Face.TexCoordIndices, TexCoords.Count);
411
412 { read normal index }
413 ReadIndex(IndiceHasNormal, Face.NormalIndices, Normals.Count);
414
415 { update Face.HasXxx using IndiceHasXxx }
416 Face.HasTexCoords := Face.HasTexCoords and IndiceHasTexCoord;
417 Face.HasNormals := Face.HasNormals and IndiceHasNormal;
418 end;
419
420 var
421 SeekPos: integer;
422
423 function NextVertex: string;
424 begin
425 Result := NextToken(Line, SeekPos);
426 if Result = '' then
427 raise EInvalidOBJFile.CreateFmt(
428 'Incomplete OBJ face specification "%s"', [Line]);
429 while SCharIs(Line, SeekPos, WhiteSpaces) do Inc(SeekPos);
430 end;
431
432 begin
433 { ReadIndices will eventually change this to @false, if for any
434 vertex normal or texCoord will not be present. }
435 Face := TWavefrontFace.Create;
436 Face.HasTexCoords := true;
437 Face.HasNormals := true;
438 Face.Material := Material;
439 Faces.Add(Face);
440
441 SeekPos := 1;
442 while SeekPos <= Length(Line) do
443 ReadIndices(NextVertex);
444 end;
445
446 function StrToFloatDotSafeNan(const S: String): Single;
447 begin
448 if SameText(S, 'nan') then
449 begin
450 if not WarningNanDone then
451 begin
452 WritelnWarning('Wavefront OBJ', 'Ignoring invalid "NaN" values in OBJ file');
453 WarningNanDone := true;
454 end;
455 Result := 0.0;
456 end else
457 Result := StrToFloatDot(S);
458 end;
459
460 function TexCoordFromObjStr(const line: string): TVector2;
461 var
462 SeekPos: integer;
463 begin
464 SeekPos := 1;
465 result.X := StrToFloatDotSafeNan(NextToken(line, SeekPos));
466 result.Y := StrToFloatDotSafeNan(NextToken(line, SeekPos));
467 { Note that additional numbers on this line
468 (possible in case of 3D tex coords) are ignored. }
469 end;
470
471 { Reads single line from Wavefront OBJ or materials file.
472 This takes care of stripping comments.
473 If current line is empty or only comment, LineTok = ''.
474 Otherwise, LineTok <> '' and LineAfterMarker contains the rest of the line. }
475 procedure ReadLine(Line: string; out LineTok, LineAfterMarker: string);
476 var
477 SeekPosAfterMarker: Integer;
478 begin
479 Line := STruncateHash(Line);
480
481 { calculate first line token }
482 SeekPosAfterMarker := 1;
483 LineTok := NextToken(Line, SeekPosAfterMarker);
484 if LineTok <> '' then
485 LineAfterMarker := Trim(SEnding(Line, SeekPosAfterMarker));
486 end;
487
488 procedure ReadMaterials(const URLSuffix: string);
489 var
490 IsMaterial: boolean;
491
492 function ReadRGBColor(const Line: string): TVector3;
493 var
494 FirstToken: string;
495 begin
496 FirstToken := NextTokenOnce(Line);
497 if SameText(FirstToken, 'xyz') or SameText(FirstToken, 'spectral') then
498 { we can't interpret other colors than RGB, so we silently ignore them }
499 Result := Vector3(1, 1, 1) else
500 Result := Vector3FromStrPermissive(Line);
501 end;
502
503 procedure CheckIsMaterial(const AttributeName: string);
504 begin
505 if not IsMaterial then
506 raise EInvalidOBJFile.CreateFmt(
507 'Material not named yet, but it''s %s specified', [AttributeName]);
508 end;
509
510 var
511 F: TTextReader;
512 LineTok, LineAfterMarker: string;
513 begin
514 { Specification doesn't say what to do when multiple matlib directives
515 encountered, i.e. when ReadMaterials is called multiple times.
516 I simply add to Materials list. }
517
518 { is some material in current file ? If false, then Materials is empty
519 or last material is from some other file. }
520 IsMaterial := false;
521
522 try
523 F := TTextReader.Create(CombineURI(BaseUrl, URLSuffix));
524 except
525 on E: Exception do
526 begin
527 WritelnWarning('Wavefront OBJ Material', E.Message);
528 Exit;
529 end;
530 end;
531 try
532 while not F.Eof do
533 begin
534 ReadLine(F.Readln, LineTok, LineAfterMarker);
535 if LineTok = '' then Continue;
536
537 case ArrayPosText(LineTok, ['newmtl', 'Ka', 'Kd', 'Ks', 'Tf', 'illum',
538 'd', 'Ns', 'sharpness', 'Ni', 'map_Kd', 'map_bump', 'bump', 'map_Pr', 'Pr']) of
539 0: begin
540 Materials.Add(TWavefrontMaterial.Create(LineAfterMarker));
541 IsMaterial := true;
542 end;
543 1: begin
544 CheckIsMaterial('ambient color (Ka)');
545 Materials.Last.AmbientColor := ReadRGBColor(LineAfterMarker);
546 end;
547 2: begin
548 CheckIsMaterial('diffuse color (Kd)');
549 Materials.Last.DiffuseColor := ReadRGBColor(LineAfterMarker);
550 end;
551 3: begin
552 CheckIsMaterial('specular color (Ks)');
553 Materials.Last.SpecularColor := ReadRGBColor(LineAfterMarker);
554 end;
555 4: begin
556 CheckIsMaterial('transmission filter color (Tf)');
557 Materials.Last.TransmissionColor := ReadRGBColor(LineAfterMarker);
558 end;
559 5: begin
560 CheckIsMaterial('illumination model (illum)');
561 Materials.Last.IlluminationModel := StrToFloatDot(LineAfterMarker);
562 end;
563 6: begin
564 CheckIsMaterial('dissolve (d)');
565 Materials.Last.Opacity := StrToFloatDot(LineAfterMarker);
566 end;
567 7: begin
568 CheckIsMaterial('specular exponent (Ns)');
569 Materials.Last.SpecularExponent := StrToFloatDot(LineAfterMarker);
570 if Materials.Last.SpecularExponent = 0 then
571 begin
572 WritelnWarning('Wavefront material "%s" specifies specular exponent (Ns) as zero, ignoring', [
573 Materials.Last.Name
574 ]);
575 Materials.Last.SpecularExponent := 1;
576 end;
577 end;
578 8: begin
579 CheckIsMaterial('sharpness');
580 Materials.Last.Sharpness := StrToFloatDot(LineAfterMarker);
581 end;
582 9: begin
583 CheckIsMaterial('index of refraction (Ni)');
584 Materials.Last.IndexOfRefraction := StrToFloatDot(LineAfterMarker);
585 end;
586 10:begin
587 CheckIsMaterial('diffuse map (map_Kd)');
588 Materials.Last.DiffuseTexture.ReadFromLine(lineAfterMarker);
589 end;
590 11, 12:
591 begin
592 CheckIsMaterial('bump map (map_bump)');
593 Materials.Last.NormalTexture.ReadFromLine(lineAfterMarker);
594 end;
595 13, 14:
596 begin
597 CheckIsMaterial('roughness map (map_Pr)');
598 Materials.Last.RoughnessTexture.ReadFromLine(lineAfterMarker);
599 end;
600 else { we ignore other linetoks };
601 end;
602 end;
603 finally FreeAndNil(F) end;
604 end;
605
606 { Read vertex position from "v" line in OBJ.
607 See https://en.wikipedia.org/wiki/Wavefront_.obj_file , it can have
608 - 3 components (x, y, z)
609 - 4 components (x, y, z, w)
610 - 6 components (x, y, z, r, g, b) }
611 function PositionFromObjStr(const S: String): TVector3;
612 var
613 SPosition: Integer;
614 Vector: array [4..7] of String;
615 Color: TCastleColorRGB;
616 W: Single;
617 I: Integer;
618 begin
619 SPosition := 1;
620 Result.X := StrToFloatDot(NextToken(S, SPosition));
621 Result.Y := StrToFloatDot(NextToken(S, SPosition));
622 Result.Z := StrToFloatDot(NextToken(S, SPosition));
623
624 { Account for additional components }
625 for I := 4 to 7 do
626 Vector[I] := NextToken(S, SPosition);
627
628 { 7 components (or more) -> error, too much }
629 if Vector[7] <> '' then
630 raise EConvertError.Create('Expected end of data when reading vector from string');
631
632 { 6 components, so "x y z r g b".
633 Testcase: banner.obj from https://kenney.nl/assets/mini-arena }
634 if Vector[6] <> '' then
635 begin
636 Color.X := StrToFloatDot(Vector[4]);
637 Color.Y := StrToFloatDot(Vector[5]);
638 Color.Z := StrToFloatDot(Vector[6]);
639 if not TCastleColorRGB.Equals(Color, WhiteRGB) then
640 begin
641 if not WarningPerVertexColorDone then
642 begin
643 WritelnWarning('Wavefront OBJ', 'Ignoring color components of vertex position, not supported');
644 WarningPerVertexColorDone := true;
645 end;
646 end;
647 Exit;
648 end;
649
650 { 5 components are not valid }
651 if Vector[5] <> '' then
652 raise EConvertError.Create('Unexpected 5 components in vertex position');
653
654 { 4 components, so "x y z w" }
655 if Vector[4] <> '' then
656 begin
657 W := StrToFloatDot(Vector[4]);
658 if not IsZero(W) then
659 Result := Result / W
660 else
661 raise EConvertError.Create('Expected W <> 0 in 4 components vertex position');
662 Exit;
663 end;
664
665 { If we got here, then we have 3 components, so "x y z", all good. }
666 end;
667
668 var
669 F: TTextReader;
670 LineTok, LineAfterMarker: string;
671 //GroupName: string;
672 UsedMaterial: TWavefrontMaterial;
673 begin
674 inherited Create;
675
676 FFaces := TWavefrontFaceList.Create(true);
677 FMaterials := TWavefrontMaterialList.Create(true);
678
679 UsedMaterial := nil;
680
681 F := TTextReader.Create(Stream, false);
682 try
683 Coord := TCoordinateNode.Create('ObjCoordinates');
684 TexCoord := TTextureCoordinateNode.Create('ObjTextureCoordinates');
685 Normal := TNormalNode.Create('ObjNormals');
686
687 Verts := Coord.FdPoint.Items;
688 TexCoords := TexCoord.FdPoint.Items;
689 Normals := Normal.FdVector.Items;
690
691 while not F.Eof do
692 begin
693 ReadLine(F.Readln, LineTok, LineAfterMarker);
694
695 { LineTok = '' means "this line is a comment" }
696 if LineTok = '' then Continue;
697
698 { specialized token line parsing }
699 case ArrayPosText(lineTok, ['v', 'vt', 'f', 'vn', 'g', 'mtllib', 'usemtl']) of
700 0: Verts.Add(PositionFromObjStr(lineAfterMarker));
701 1: TexCoords.Add(TexCoordFromObjStr(lineAfterMarker));
702 2: ReadFacesFromOBJLine(lineAfterMarker, UsedMaterial);
703 3: Normals.Add(Vector3FromStr(lineAfterMarker));
704 4: {GroupName := LineAfterMarker};
705 5: ReadMaterials(LineAfterMarker);
706 6: begin
707 if LineAfterMarker = '(null)' then
708 UsedMaterial := nil else
709 begin
710 UsedMaterial := Materials.TryFindName(LineAfterMarker);
711 if UsedMaterial = nil then
712 WritelnWarning('Wavefront OBJ', Format('Unknown material name "%s"',
713 [LineAfterMarker]));
714 end;
715 end;
716 else { we ignore other linetoks };
717 end;
718 end;
719 finally FreeAndNil(F) end;
720 end;
721
722 destructor TObject3DOBJ.Destroy;
723 begin
724 FreeIfUnusedAndNil(Coord);
725 FreeIfUnusedAndNil(TexCoord);
726 FreeIfUnusedAndNil(Normal);
727 FreeAndNil(FFaces);
728 FreeAndNil(FMaterials);
729 inherited;
730 end;
731
732 { LoadWavefrontOBJ ----------------------------------------------------------- }
733
734 function LoadWavefrontOBJ(const Stream: TStream; const BaseUrl: String): TX3DRootNode;
735 const
736 { When constructing large index arrays, we use larger Capacity
737 to make them faster.
738 TODO: would be better to allocate necessary space once, by assigning Count. }
739 IndicesCapacity = 100;
740
741 function MatOBJNameToX3DName(const MatOBJName: string): string;
742 begin
743 Result := 'Material_' + MatOBJName;
744 end;
745
746 function MaterialToX3D(const Material: TWavefrontMaterial): TAppearanceNode;
747 var
748 MatPhong: TMaterialNode;
749 MatPhysical: TPhysicalMaterialNode;
750 TextureTransform: TTextureTransform3DNode;
751 begin
752 Result := TAppearanceNode.Create(
753 MatOBJNameToX3DName(Material.Name), BaseUrl);
754
755 if WavefrontPhongMaterials then
756 begin
757 MatPhong := TMaterialNode.Create;
758 Result.Material := MatPhong;
759 MatPhong.AmbientIntensity := AmbientIntensity(
760 Material.AmbientColor, Material.DiffuseColor);
761 MatPhong.DiffuseColor := Material.DiffuseColor;
762 MatPhong.SpecularColor := Material.SpecularColor;
763 MatPhong.Transparency := 1 - Material.Opacity;
764 MatPhong.Shininess := Material.SpecularExponent / 128.0;
765
766 MatPhong.DiffuseTexture := Material.DiffuseTexture.CreateNode(BaseUrl);
767 MatPhong.NormalTexture := Material.NormalTexture.CreateNode(BaseUrl);
768 // if MatPhong.NormalTexture <> nil then
769 // MatPhong.NormalScale := Material.NormalTexture.BumpMultiplier;
770 end else
771 begin
772 MatPhysical := TPhysicalMaterialNode.Create;
773 Result.Material := MatPhysical;
774 MatPhysical.BaseColor := Material.DiffuseColor;
775 MatPhysical.Transparency := 1 - Material.Opacity;
776
777 MatPhysical.BaseTexture := Material.DiffuseTexture.CreateNode(BaseUrl);
778 MatPhysical.NormalTexture := Material.NormalTexture.CreateNode(BaseUrl);
779 MatPhysical.MetallicRoughnessTexture := Material.RoughnessTexture.CreateNode(BaseUrl);
780 // if MatPhysical.NormalTexture <> nil then
781 // MatPhysical.NormalScale := Material.NormalTexture.BumpMultiplier;
782 end;
783
784 TextureTransform := Material.DiffuseTexture.CreateTextureTransformNode;
785 if TextureTransform <> nil then
786 begin
787 Result.TextureTransform := TextureTransform;
788 if (Material.NormalTexture.URL <> '') and
789 ( (not TVector3.PerfectlyEquals(Material.NormalTexture.Scale, Material.DiffuseTexture.Scale)) or
790 (not TVector3.PerfectlyEquals(Material.NormalTexture.Offset, Material.DiffuseTexture.Offset))
791 ) then
792 WritelnWarning('OBJ texture transformation that differs for diffuse and normalMap is not supported; we will apply the same transformation for diffuse and normalMap.');
793 end;
794 end;
795
796 function DefaultAppearance: TAppearanceNode;
797 begin
798 Result := TAppearanceNode.Create;
799 if WavefrontPhongMaterials then
800 Result.Material := TMaterialNode.Create
801 else
802 Result.Material := TPhysicalMaterialNode.Create;
803 end;
804
805 var
806 Obj: TObject3DOBJ;
807 Faces: TIndexedFaceSetNode;
808 I: integer;
809 FacesWithTexCoord, FacesWithNormal: boolean;
810 FacesWithMaterial: TWavefrontMaterial;
811 Appearances: TX3DNodeList;
812 Shape: TShapeNode;
813 begin
814 Appearances := nil;
815
816 Result := TX3DRootNode.Create;
817 try
818 Result.HasForceVersion := true;
819 Result.ForceVersion := X3DVersion;
820
821 Obj := TObject3DOBJ.Create(Stream, BaseUrl);
822 try
823 Appearances := TX3DNodeList.Create(false);
824 Appearances.Count := Obj.Materials.Count;
825 for I := 0 to Obj.Materials.Count - 1 do
826 Appearances[I] := MaterialToX3D(Obj.Materials[I]);
827
828 I := 0;
829 while I < Obj.Faces.Count do
830 begin
831 FacesWithTexCoord := Obj.Faces[I].HasTexCoords;
832 FacesWithNormal := Obj.Faces[I].HasNormals;
833 FacesWithMaterial := Obj.Faces[I].Material;
834
835 Shape := TShapeNode.Create;
836 Result.AddChildren(Shape);
837
838 if FacesWithMaterial <> nil then
839 begin
840 { We find appearance by name, using FindName. We're sure
841 that we will find it --- because we added them all to Appearances. }
842 Shape.Appearance := Appearances.FindName(
843 MatOBJNameToX3DName(FacesWithMaterial.Name)) as TAppearanceNode;
844 end else
845 Shape.Appearance := DefaultAppearance;
846
847 { We don't do anything special for the case when FacesWithMaterial = nil
848 and FacesWithTexCoord = true. This may be generated e.g. by Blender
849 exporter, if Blender object has UV texture coords but no material.
850
851 We will then just output VRML/X3D texCoord
852 field, but without texture it will not have any effect.
853 This is natural, and there's no reason for now to do anything else. }
854
855 Faces := TIndexedFaceSetNode.Create;
856 Shape.Geometry := Faces;
857 Faces.CreaseAngle := NiceCreaseAngle;
858 { faces may be concave, see https://sourceforge.net/p/castle-engine/tickets/20
859 and https://sourceforge.net/p/castle-engine/tickets/19/ }
860 Faces.Convex := false;
861 Faces.Solid := false;
862 Faces.Coord := Obj.Coord;
863 Faces.FdCoordIndex.Items.Clear;
864 Faces.FdCoordIndex.Items.Capacity := IndicesCapacity;
865 if FacesWithTexCoord then
866 begin
867 Faces.TexCoord := Obj.TexCoord;
868 Faces.FdTexCoordIndex.Items.Clear;
869 Faces.FdTexCoordIndex.Items.Capacity := IndicesCapacity;
870 end;
871 if FacesWithNormal then
872 begin
873 Faces.Normal := Obj.Normal;
874 Faces.FdNormalIndex.Items.Clear;
875 Faces.FdNormalIndex.Items.Capacity := IndicesCapacity;
876 end;
877
878 { We add Faces as long as FacesWithXxx parameters stay the same.
879 We know that at least the next face is Ok. }
880 repeat
881 Faces.FdCoordIndex.Items.AddRange(Obj.Faces[I].VertIndices);
882 Faces.FdCoordIndex.Items.Add(-1);
883
884 if FacesWithTexCoord then
885 begin
886 Faces.FdTexCoordIndex.Items.AddRange(Obj.Faces[I].TexCoordIndices);
887 Faces.FdTexCoordIndex.Items.Add(-1);
888 end;
889
890 if FacesWithNormal then
891 begin
892 Faces.FdNormalIndex.Items.AddRange(Obj.Faces[I].NormalIndices);
893 Faces.FdNormalIndex.Items.Add(-1);
894 end;
895
896 Inc(I);
897 until (I >= Obj.Faces.Count) or
898 (FacesWithTexCoord <> Obj.Faces[I].HasTexCoords) or
899 (FacesWithNormal <> Obj.Faces[I].HasNormals) or
900 (FacesWithMaterial <> Obj.Faces[I].Material);
901 end;
902
903 for I := 0 to Appearances.Count - 1 do
904 Appearances[I].FreeIfUnused;
905 finally
906 FreeAndNil(Obj);
907 FreeAndNil(Appearances);
908 end;
909 except FreeAndNil(result); raise end;
910 end;
911
912 var
913 ModelFormat: TModelFormat;
914 initialization
915 ModelFormat := TModelFormat.Create;
916 ModelFormat.OnLoad := {$ifdef FPC}@{$endif} LoadWavefrontOBJ;
917 ModelFormat.MimeTypes.Add('application/x-wavefront-obj');
918 ModelFormat.FileFilterName := 'Wavefront (*.obj)';
919 ModelFormat.Extensions.Add('.obj');
920 RegisterModelFormat(ModelFormat);
921 end.