Debian Codegraph @

tools/castle-editor/code/castlesketchfab.pas

raw
1 {
2 Copyright 2023-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Searching, downloading models from Sketchfab.
17 This does most of the actual work and is used by FormImportSketchfab. }
18 unit CastleSketchfab;
19
20 interface
21
22 uses
23 { Using CThreads, as threads are required by TCastleDownload asynchronous version. }
24 {$ifdef UNIX} CThreads, {$endif}
25 SysUtils, Classes, Generics.Collections, FpJson, JsonParser, Zipper,
26 { Enable https downloads. }
27 {$ifdef FPC} OpenSslSockets, {$endif}
28 { CGE units }
29 CastleFilesUtils, CastleDownload, CastleStringUtils, CastleUriUtils, CastleLog,
30 CastleUtils, CastleClassUtils, CastleApplicationProperties, CastleImages;
31
32 const
33 { Sketchfab API returns thumbnails in various sizes,
34 we will pick the closest one to this. }
35 BestThumbnailSize = 256;
36
37 { The thumbnails in TSketchfabModel.ThumbnailImage are resized to this size.
38 This allows to display them nicely in LCL TListView (which requires
39 constant size for all images, otherwise it stretched them in ugly way).
40
41 The aspect ratio of ThumbnailOptimalWidth / ThumbnailOptimalHeight
42 follows the aspect ratio of most (but not all)
43 Sketchfab thumbnails, so they typically fill the desired area nicely
44 (without excessive white space around). }
45 ThumbnailOptimalWidth = BestThumbnailSize;
46 ThumbnailOptimalHeight = 144;
47
48 type
49 TSketchfabModel = class;
50
51 TSketchfabModelList = {$ifdef FPC}specialize{$endif} TObjectList<TSketchfabModel>;
52
53 { Notification when thumbnail is downloaded for given model.
54 When this is called, Sender.ThumbnailImage is non-nil for sure. }
55 TThumbnailDownloadedEvent = procedure (const Sender: TSketchfabModel) of object;
56
57 TSketchfabModel = class
58 private
59 DownloadURL: String;
60 ThumbnailDownload: TCastleDownload;
61 FThumbnailImage: TCastleImage;
62 FThumbnailImageError: Boolean;
63 procedure ThumbnailDownloadFinish(const Sender: TCastleDownload; var FreeSender: Boolean);
64 public
65 ModelId: String;
66
67 { Various additional info about model, set by @link(Search). }
68 Name, Description: String;
69 FaceCount: UInt64;
70 ThumbnailUrl, ViewerUrl: String;
71 License: String;
72
73 { Model name with all characters potentially unsafe for filename
74 removed/replaced + added model id as a suffix.
75 The idea is that this is unique, just like ModelId,
76 but it is also more recognizable for humans.
77
78 Sketchfab URLs are actually similar,
79 https://sketchfab.com/3d-models/anything-70a23788ef984a7a9a1c9a9fe6d5a651
80 redirects to
81 https://sketchfab.com/3d-models/cat-70a23788ef984a7a9a1c9a9fe6d5a651
82 The end is just model id,
83 the initial "cat" is only for humans. }
84 ModelPrettyId: String;
85
86 { Set to be notified when ThumbnailImage is downloaded successfully. }
87 OnThumbnailDownloaded: TThumbnailDownloadedEvent;
88
89 { When thumbnail image is downloaded, it is placed here right
90 before calling @link(OnThumbnailDownload). }
91 property ThumbnailImage: TCastleImage read FThumbnailImage;
92
93 { If thumbnail download was attempted but failed. }
94 property ThumbnailImageError: Boolean read FThumbnailImageError;
95
96 { Search Sketchfab for Query, return list of model ids. }
97 class function Search(const Query: String;
98 const AnimatedOnly: Boolean): TSketchfabModelList;
99
100 destructor Destroy; override;
101
102 { Set Download* fields based on ModelId. }
103 procedure StartDownload(const ApiToken: String);
104 { Use Download* fields to get model zip. }
105 procedure DownloadZip(const ZipFileName: String);
106 { Extract zip to a subdirectory in ExtractBasePath. }
107 procedure ExtractZip(const ZipFileName, ZipUnpackDir: String);
108
109 { Start downloading thumbnail,
110 to set @link(ThumbnailImage) and call @link(OnThumbnailDownloaded).
111 Does nothing if download is already in progress.
112 Calls @link(OnThumbnailDownloaded) immediately if thumbnail is already
113 downloaded. }
114 procedure StartThumbnailDownload;
115
116 { If the thumbnail download is in progress, abort it.
117 Sets ThumbnailDownloading to @false. }
118 procedure AbortThumbnailDownload;
119
120 { Are we currently downloading thumbnail.
121
122 This is set to @true by StartThumbnailDownload.
123
124 This changes to @false by
125
126 - AbortThumbnailDownload
127
128 - or when thumbnail is downloaded with success
129 (then we set ThumbnailImage to non-nil and call OnThumbnailDownloaded)
130
131 - or when thumbnail is downloaded with failure
132 (then we set ThumbnailImageError to @true). }
133 function ThumbnailDownloading: Boolean;
134 end;
135
136 implementation
137
138 uses FormProgress,
139 CastleVectors;
140
141 { TSketchfabModel (class methods) --------------------------------------------- }
142
143 class function TSketchfabModel.Search(const Query: String;
144 const AnimatedOnly: Boolean): TSketchfabModelList;
145
146 { Find thumbnail URL best matching given Size, in a JSON array
147 as returned by Sketchfab search query.
148 Returns '' if no thumbnail found. }
149 function SearchThumbnails(const Thumbnails: TJSONArray; const DesiredSize: Integer): String;
150 var
151 I: Integer;
152 Thumbnail: TJSONObject;
153 ThumbnailSize: Integer;
154 BestThumbnail: TJSONObject;
155 BestThumbnailSize: Integer;
156 begin
157 BestThumbnail := nil;
158 BestThumbnailSize := 0;
159 for I := 0 to Thumbnails.Count - 1 do
160 begin
161 Thumbnail := Thumbnails[I] as TJSONObject;
162 // average width and height
163 ThumbnailSize := (Thumbnail.Integers['width'] + Thumbnail.Integers['height']) div 2;
164 if (BestThumbnail = nil) or
165 ( Abs(ThumbnailSize - DesiredSize) <
166 Abs(BestThumbnailSize - DesiredSize) ) then
167 begin
168 BestThumbnail := Thumbnail;
169 BestThumbnailSize := ThumbnailSize;
170 end;
171 end;
172 if BestThumbnail <> nil then
173 begin
174 Result := BestThumbnail.Strings['url'];
175 // WritelnLog('Best thumbnail dimensions: %d x %d, url: %s', [
176 // BestThumbnail.Integers['width'],
177 // BestThumbnail.Integers['height'],
178 // Result
179 // ]);
180 end else
181 Result := '';
182 end;
183
184 function URICleanFilename(const S: String): String;
185 const
186 ValidFilenameChars = ['a'..'z', 'A'..'Z', '0'..'9', '-', '_', '.'];
187 begin
188 Result := LowerCase(S);
189 Result := SReplaceChars(Result, AllChars - ValidFilenameChars, '-');
190 end;
191
192 function SRemoveConsecuitive(const S: String; const C: Char): String;
193 var
194 SB: TStringBuilder;
195 I: Integer;
196 begin
197 SB := TStringBuilder.Create;
198 try
199 SB.Append(S[1]);
200 for I := 2 to Length(S) do
201 if (S[I] <> C) or (S[I - 1] <> C) then
202 SB.Append(S[I]);
203 Result := SB.ToString;
204 finally FreeAndNil(SB) end;
205 end;
206
207 var
208 Download: TCastleDownload;
209 Response: String;
210 JSONData: TJSONData;
211 JSONArray: TJSONArray;
212 JSONObject: TJSONObject;
213 I: Integer;
214 Model: TSketchfabModel;
215 SearchUrl: String;
216 begin
217 Result := TSketchfabModelList.Create(true);
218 Download := TCastleDownload.Create(nil);
219 try
220 { See https://docs.sketchfab.com/data-api/v3/index.html#!/search/get_v3_search_type_models
221 for documentation of this API.
222 Notes:
223
224 - The default "sort_by" is by relevance, which is just like in Sketchfab UI
225 on the website. No need to tweak this default.
226
227 - There is "file_format" API parameter but it is unclear should I specify
228 there glTF somehow.
229 It seems it allows to filter by source formats (like .blend, obj)
230 not by output formats. https://sketchfab.com/developers/download-api
231 says """Models are available in glTF, GLB, and USDZ formats.
232 Models are not currently available in their source formats such
233 as FBX and OBJ through the API.""
234
235 In all practical experiments, models we found have glTF versions.
236
237 - There is "pbr_type" and it is tempting to use it, as CGE doesn't
238 support fully Specular-Glossiness PBR workflow yet.
239 (And we're reluctant to support it, as it is deprecated in glTF 2.0.)
240 However, it seems we cannot tell there "unlit or metallic-roughness".
241 }
242 SearchUrl := 'https://api.sketchfab.com/v3/search?type=models&downloadable=true';
243 if AnimatedOnly then
244 SearchUrl += '&animated=true';
245 SearchUrl += '&q=' + InternalUriEscape(Query);
246 Download.Url := SearchUrl;
247
248 Download.Start;
249 TProgressForm.WaitFor('Searching Sketchfab', Download);
250 Response := StreamToString(Download.Contents);
251
252 JSONData := GetJSON(Response);
253
254 //WritelnLog('Got response, storing in response-search.json (for debug)');
255 //StringToFile('response-search.json', Response);
256
257 if JSONData.JSONType = jtObject then
258 begin
259 JSONArray := TJSONObject(JSONData).Arrays['results'];
260 for I := 0 to JSONArray.Count - 1 do
261 begin
262 JSONObject := JSONArray.Objects[I];
263
264 // sanity check
265 if not JSONObject.Booleans['isDownloadable'] then
266 begin
267 WritelnWarning('Model %s not downloadable, even though we requested only downloadable');
268 Continue;
269 end;
270
271 Model := TSketchfabModel.Create;
272 Model.ModelId := JSONObject.Strings['uid'];
273 Model.Name := JSONObject.Strings['name'];
274 Model.Description := JSONObject.Strings['description'];
275 Model.FaceCount := JSONObject.QWords['faceCount'];
276 Model.ThumbnailUrl := SearchThumbnails(JSONObject.Objects['thumbnails'].Arrays['images'], BestThumbnailSize);
277 Model.License := JSONObject.Objects['license'].Strings['label'];
278 Model.ViewerUrl := JSONObject.Strings['viewerUrl'];
279 Model.ModelPrettyId := SRemoveConsecuitive(
280 URICleanFilename(Model.Name) + '-' + Model.ModelId, '-');
281 Result.Add(Model);
282 end;
283 end else
284 raise Exception.Create('Unexpected JSON response: ' + Response);
285 finally
286 FreeAndNil(Download);
287 end;
288 end;
289
290 { TSketchfabModel (instance methods) ----------------------------------------- }
291
292 destructor TSketchfabModel.Destroy;
293 begin
294 FreeAndNil(ThumbnailDownload);
295 FreeAndNil(FThumbnailImage);
296 inherited;
297 end;
298
299 procedure TSketchfabModel.StartDownload(const ApiToken: String);
300 const
301 ApiUrl = 'https://api.sketchfab.com/v3/models';
302 var
303 Download: TCastleDownload;
304 Response: String;
305 JSONData: TJSONData;
306 DownloadSize: Int64;
307 begin
308 Download := TCastleDownload.Create(nil);
309 try
310 WritelnLog('Starting download of model id ' + ModelId);
311 Download.HttpHeader('Authorization', 'Token ' + ApiToken);
312 Download.Url := ApiUrl + '/' + ModelId + '/download';
313 Download.Start;
314 TProgressForm.WaitFor('Starting download of model', Download);
315 Response := StreamToString(Download.Contents);
316 finally
317 FreeAndNil(Download);
318 end;
319
320 //WritelnLog('Got response, storing in response-download.json (for debug)');
321 //StringToFile('response-download.json', Response);
322
323 JSONData := GetJSON(Response);
324 try
325 DownloadURL := JSONData.FindPath('gltf.url').AsString;
326 DownloadSize := JSONData.FindPath('gltf.size').AsInt64;
327 finally
328 FreeAndNil(JSONData);
329 end;
330
331 WritelnLog('Downloading model from: '+ DownloadURL);
332 WritelnLog('Download size: ' + SizeToStr(DownloadSize));
333 end;
334
335 procedure TSketchfabModel.DownloadZip(const ZipFileName: String);
336 var
337 Download: TCastleDownload;
338 begin
339 Download := TCastleDownload.Create(nil);
340 try
341 Download.Url := DownloadURL;
342 Download.Start;
343 TProgressForm.WaitFor('Downloading model', Download);
344 StreamSaveToFile(Download.Contents, ZipFileName);
345 WritelnLog('Model downloaded to: %s, file size: %s', [
346 ZipFileName,
347 SizeToStr(Download.Contents.Size)
348 ]);
349 finally
350 FreeAndNil(Download);
351 end;
352 end;
353
354 procedure TSketchfabModel.ExtractZip(const ZipFileName, ZipUnpackDir: String);
355 var
356 Zip: TUnZipper;
357 begin
358 { Unzip to given directory. }
359 if DirectoryExists(ZipUnpackDir) then
360 RemoveNonEmptyDir(ZipUnpackDir, true);
361 ForceDirectories(ZipUnpackDir);
362
363 Zip := TUnZipper.Create;
364 try
365 Zip.FileName := ZipFileName;
366 Zip.OutputPath := ZipUnpackDir;
367 Zip.Examine;
368 Zip.UnZipAllFiles;
369 finally
370 FreeAndNil(Zip);
371 end;
372
373 WritelnLog('Model extracted to: ' + ZipUnpackDir);
374 end;
375
376 procedure TSketchfabModel.StartThumbnailDownload;
377 begin
378 if not ThumbnailDownloading then
379 begin
380 if ThumbnailImage <> nil then
381 OnThumbnailDownloaded(Self)
382 else
383 begin
384 ThumbnailDownload := TCastleDownload.Create(nil);
385 ThumbnailDownload.Url := ThumbnailUrl;
386 ThumbnailDownload.OnFinish := @ThumbnailDownloadFinish;
387 ThumbnailDownload.Start;
388 end;
389 end;
390 end;
391
392 procedure TSketchfabModel.AbortThumbnailDownload;
393 begin
394 FreeAndNil(ThumbnailDownload);
395 end;
396
397 function TSketchfabModel.ThumbnailDownloading: Boolean;
398 begin
399 Result := ThumbnailDownload <> nil;
400 end;
401
402 { Make Image size exactly W x H.
403
404 Reason: Sketchfab thumbnails have various aspect ratios (some are square,
405 some are 16:9...),
406 also they are not guaranteed to match BestThumbnailSize even in one dimension.
407 And we need them to be exactly ThumbnailOptimalWidth x ThumbnailOptimalHeight,
408 as LCL TListView rendering will assume that, otherwise images are stretched
409 in ugly way. }
410 procedure FixImageSize(var Image: TCastleImage; const W, H: Integer);
411 var
412 NewW, NewH: Integer;
413 NewImage: TRGBImage;
414 begin
415 { Make at least one side equal to desired W or H. }
416 if Image.Width / Image.Height > W / H then
417 begin
418 NewW := W;
419 NewH := Round(W * Image.Height / Image.Width);
420 end else
421 begin
422 NewW := Round(H * Image.Width / Image.Height);
423 NewH := H;
424 end;
425
426 { Note: TCastleImage.Resize does nothing when NewW/H match current size.
427 So we don't check it here. }
428 Image.Resize(NewW, NewH);
429
430 { Too small? Then place in the center of white square. }
431 if (NewW < W) or (NewH < H) then
432 begin
433 NewImage := TRGBImage.Create(W, H);
434 NewImage.Clear(Vector4Byte(255, 255, 255, 255));
435 NewImage.DrawFrom(Image, (W - NewW) div 2, (H - NewH) div 2, dmOverwrite);
436 FreeAndNil(Image);
437 Image := NewImage;
438 end;
439 end;
440
441 procedure TSketchfabModel.ThumbnailDownloadFinish(
442 const Sender: TCastleDownload; var FreeSender: Boolean);
443 begin
444 Assert(FThumbnailImage = nil);
445 Assert(Sender = ThumbnailDownload);
446 ThumbnailDownload := nil;
447
448 if Sender.Status = dsSuccess then
449 begin
450 FThumbnailImage := LoadImage(Sender.Contents, Sender.MimeType, []);
451 FixImageSize(FThumbnailImage, ThumbnailOptimalWidth, ThumbnailOptimalHeight);
452 if Assigned(OnThumbnailDownloaded) then
453 OnThumbnailDownloaded(Self);
454 end else
455 begin
456 FThumbnailImageError := true;
457 WritelnWarning('Failed to download thumbnail for "%s" from Sketchfab: "%s"', [
458 Name,
459 Sender.ErrorMessage
460 ]);
461 end;
462 FreeSender := true;
463 end;
464
465 end.