Debian Codegraph @

src/base/castleutils_miscella.inc

raw
1 {%MainUnit castleutils.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 { Some miscellaneous things, too small to be included in separate files. }
18
19 {$ifdef read_interface}
20
21 { OS constants ---------------------------------------- }
22
23 const
24 { New line sequence, suitable for current OS. Short name for LineEnding. }
25 NL = LineEnding;
26
27 { basic exceptions ---------------------------------------- }
28
29 type
30 { Internal error (bug) in the program. Something that definitely should not
31 happen and indicates a bug that should be reported.
32
33 This exception must be shown to user (never silently ignored),
34 and usually the safest thing to do is to close the program at this point.
35
36 We will add to your error message (passed to the constructor) some
37 instructive message, like @code('Please submit this to the developers: '). }
38 EInternalError = class(Exception)
39 constructor Create(const S: string); overload;
40 constructor Create(const ErrorNumber: Int64); overload;
41 constructor CreateFmt(const s: string; const Args: array of const);
42 end;
43
44 ECheckFailed = class(Exception);
45
46 { Simple notify event with no Sender }
47 TSimpleNotifyEvent = procedure of object;
48
49 { Check condition.
50 @raises ECheckFailed Raised with ErrMessage if condition TrueValue if false. }
51 procedure Check(TrueValue: boolean; const ErrMessage: string = 'Check failed');
52
53 { Arrays searching ----------------------------------------------------------- }
54
55 { Search the array for a given value.
56 Returns index (zero-based) or -1 if not found.
57
58 Useful for writing case as:
59
60 @longCode(#
61 case ArrayPosStr(variable, [val1, val2]) of
62 0 : Something1;
63 1 : Something2;
64 else SomethingElse;
65 end;
66 #) }
67 function ArrayPosStr(const A: String; const Arr: array of String): Integer; overload;
68 function ArrayPosText(const A: String; const Arr: array of String;
69 IgnoreCase: boolean = true): Integer; overload;
70
71 function ArrayContainsString(const A: String; const Arr: array of String): Boolean;
72
73 { Iff functions ------------------------------------------------------------- }
74
75 { }
76 function Iff(boolval: boolean; trueval, falseval: string) : string; overload;
77 function Iff(boolval: boolean; trueval, falseval: Integer) : Integer; overload;
78 function Iff(boolval: boolean; trueval, falseval: Float) : Float; overload;
79 function Iff(boolval: boolean; trueval, falseval: Cardinal): Cardinal; overload;
80 function Iff(boolval: boolean; trueval, falseval: char) : char; overload;
81
82 { Some helpful version stuff ------------------------------------------------ }
83
84 const
85 { Castle Game Engine version. }
86 CastleEngineVersion = {$I castleversion.inc};
87
88 { Name and version of the Pascal compiler used to compile this unit.
89
90 @seealso TCastleApplicationProperties.Description
91 @seealso SPlatformDescription }
92 function SCompilerDescription: string;
93
94 { Describe current platform, OS, CPU.
95 This is all detected looking at compilation symbols defined when compiling this unit.
96
97 @seealso TCastleApplicationProperties.Description
98 @seealso SCompilerDescription }
99 function SPlatformDescription: String;
100
101 function SCastleEngineProgramHelpSuffix(const AppName, AppVersion: String; const Ignored: Boolean): String;
102 deprecated 'use ApplicationProperties.Description';
103
104 { If not TrueValue then RaiseLastOSError. }
105 procedure OSCheck(TrueValue: boolean); overload;
106 procedure OSCheck(TrueValue: boolean; const Place: string); overload;
107
108 type
109 { Descend from this to hide a parameterless constructor.
110
111 In Delphi, if you have multiple overloaded constructors (marked
112 with "overload"), the user can call any constructor of the ancestor
113 class that you have not "obscured" by a new definition.
114 In particular, if all your constructors have some parameters,
115 then user can "bypass" them by calling a parameterless constructor
116 defined by TObject.
117 Descend from this class to disallow this.
118 See
119 https://stackoverflow.com/questions/14003153/how-to-hide-the-inherited-tobject-constructor-while-the-class-has-overloaded-one
120 http://andy.jgknet.de/blog/2011/07/hiding-the-tobject-create-constructor/
121
122 Note that in FPC (in ObjFpc mode) this is not a problem,
123 as the standard overloading (without the "overload" keyword) is more sane:
124 the overloaded constructors obscure the ancestor constructors. }
125 {$warnings off}
126 TNoParameterlessContructor = class
127 strict private
128 constructor Create;
129 end;
130 {$warnings on}
131
132 { Like standard Format, but always uses dot (.) as a decimal separator
133 for the floating point numbers, regardless of the user's locale settings.
134
135 In general this ignores locale, so also ThousandSeparator doesn't matter
136 (conversion is done like it is #0). }
137 function FormatDot(const Fmt: String; const Args: array of const): String;
138
139 { Like standard FloatToStr, but always uses dot (.) as a decimal separator
140 for the floating point numbers, regardless of the user's locale settings.
141
142 In general this ignores locale, so also ThousandSeparator doesn't matter
143 (conversion is done like it is #0). }
144 function FloatToStrDot(const Value: Extended): String;
145
146 { Like standard FloatToStr, but always uses dot (.) as a decimal separator
147 for the floating point numbers, regardless of the user's locale settings.
148
149 In general this ignores locale, so also ThousandSeparator doesn't matter
150 (conversion is done like it is #0). }
151 function FloatToStrFDot(const Value: Extended;
152 const FloatFormat: TFloatFormat;
153 const Precision: Integer;
154 const Digits: Integer): String;
155
156 { Display float as nice concise number to read (but not necessarily with
157 absolute precision):
158 always decimal,
159 no digits after dot if not necessary,
160 show some digits (but not too many - right now 2) after dot if they are meaningful.
161
162 Like other ...Dot routines, always uses dot (.) as a decimal separator,
163 regardless of the user's locale settings. }
164 function FloatToStrDisplay(const AValue: Extended): String;
165
166 { Like standard TryStrToFloat, but always uses dot (.) as a decimal separator
167 for the floating point numbers, regardless of the user's locale settings.
168
169 Also it doesn't Trim the argument (so whitespace around number is @italic(not) tolerated),
170 and in general ignores locale (standard StrToFloat looks at ThousandSeparator). }
171 function TryStrToFloatDot(const S: String; out Value: Single): Boolean; overload;
172 function TryStrToFloatDot(const S: String; out Value: Double): Boolean; overload;
173 {$ifdef EXTENDED_OVERLOADS}
174 function TryStrToFloatDot(const S: String; out Value: Extended): Boolean; overload;
175 {$endif}
176
177 { Like standard StrToFloat, but always uses dot (.) as a decimal separator
178 for the floating point numbers, regardless of the user's locale settings.
179
180 Also it doesn't Trim the argument (so whitespace around number is @italic(not) tolerated),
181 and in general ignores locale (standard StrToFloat looks at ThousandSeparator). }
182 function StrToFloatDot(const S: String): Extended;
183
184 { Like standard StrToFloatDef, but always uses dot (.) as a decimal separator
185 for the floating point numbers, regardless of the user's locale settings.
186
187 Also it doesn't Trim the argument (so whitespace around number is @italic(not) tolerated),
188 and in general ignores locale (standard StrToFloat looks at ThousandSeparator). }
189 function StrToFloatDefDot(Const S: String; const Default: Extended): Extended;
190
191 type
192 { Application mode. }
193 TCastleApplicationMode = (
194 { Application is running.
195 We are not inside any editor (CGE editor, LCL/Delphi designer). }
196 appRunning,
197
198 { We are designing the application in CGE editor (or LCL/Delphi designer).
199 Simulation is not started. }
200 appDesign,
201
202 { We are designing the application and simulation has been started by user.
203 The main feature of simulation right now is to test the physics at design-time.
204 More features may be unlocked in particular components. }
205 appSimulation,
206
207 { We are designing the application and simulation has been started and paused by the user. }
208 appSimulationPaused
209 );
210
211 { Current application mode, see TCastleApplicationMode for various possible values. }
212 function CastleApplicationMode: TCastleApplicationMode;
213
214 { Are we in design-time now. Shortcut for CastleApplicationMode <> appRunning. }
215 function CastleDesignMode: Boolean;
216
217 var
218 { @exclude Write-able version of CastleApplicationMode. }
219 InternalCastleApplicationMode: TCastleApplicationMode;
220
221 { @exclude Path to editor data, in design mode.
222 Useful e.g. to initialize gizmo textures.
223
224 Note: always be prepared it may not be initialized (empty),
225 e.g. it is not initialized when using TCastleControl in Delphi IDE. }
226 InternalCastleDesignData: String;
227
228 { @exclude Refresh UI of CGE editor, because hierarchy of UI/transforms changed. }
229 InternalCastleDesignInvalidate: Boolean;
230
231 {$endif read_interface}
232
233 {$ifdef read_implementation}
234
235 constructor EInternalError.Create(const S: string);
236 begin
237 inherited Create('Internal error occured. Please submit a bugreport providing this information to the developers: ' + S);
238 // inherited Create('Internal error: something that should not ever happen... happened. ' +
239 // 'This indicates a bug in the program''s code (or something related, ' +
240 // 'like a shared library, that should be workarounded from the program then). ' +
241 // { 'Don''t panic - if you see this note then at least my code noticed the '+
242 // 'bug in some way, so it may be something simple and I can probably fix it '+
243 // '(or it''s external bug and I am not responsible for this...). '+}
244 // 'We definitely want you to report this as a bug! Please send this error-specific info: ' + S);
245 end;
246
247 constructor EInternalError.Create(const ErrorNumber: Int64);
248 begin
249 Create(IntToStr(ErrorNumber));
250 end;
251
252 constructor EInternalError.CreateFmt(const s: string; const Args: array of const);
253 begin
254 Create(Format(S, Args));
255 end;
256
257 procedure Check(TrueValue: boolean; const errMessage: string);
258 begin
259 if not TrueValue then raise ECheckFailed.Create(errMessage);
260 end;
261
262 { arrays searching ---------------------------------------- }
263
264 function ArrayPosStr(const A: String; const Arr: array of String): Integer;
265 begin
266 for Result := 0 to High(Arr) do
267 if Arr[Result] = A then
268 Exit;
269 Result := -1;
270 end;
271
272 function ArrayContainsString(const A: String; const Arr: array of String): Boolean;
273 begin
274 Result := ArrayPosStr(A, Arr) <> -1;
275 end;
276
277 function ArrayPosText(const A: String; const Arr: array of String;
278 IgnoreCase: boolean): Integer;
279 var
280 AA: string;
281 begin
282 if IgnoreCase then
283 begin
284 AA := AnsiUpperCase(A);
285 for Result := 0 to High(Arr) do
286 if AnsiUpperCase(Arr[Result]) = AA then
287 Exit;
288 Result := -1;
289 end else
290 Result := ArrayPosStr(A, Arr);
291 end;
292
293 { Iff functions ------------------------------------------------------------- }
294
295 function Iff(boolval: boolean; trueval, falseval: string) : string; begin if boolval then result := trueval else result := falseval end;
296 function Iff(boolval: boolean; trueval, falseval: Integer) : Integer; begin if boolval then result := trueval else result := falseval end;
297 function Iff(boolval: boolean; trueval, falseval: Float) : Float; begin if boolval then result := trueval else result := falseval end;
298 function Iff(boolval: boolean; trueval, falseval: Cardinal): Cardinal; begin if boolval then result := trueval else result := falseval end;
299 function Iff(boolval: boolean; trueval, falseval: char) : char; begin if boolval then result := trueval else result := falseval end;
300
301 { Various routines ------------------------------------------------------------ }
302
303 function SCompilerDescription: string;
304 begin
305 Result :=
306 {$ifdef FPC}
307 'FPC ' + {$I %FPCVERSION%}
308 {$else}
309
310 {$ifdef DCC}
311 { Make it clear we show compiler version, not Delphi version, as they are different things:
312 https://docwiki.embarcadero.com/RADStudio/Sydney/en/Compiler_Versions .
313 E.g. Delphi 11 = product version 28 = compiler version 35.
314 }
315 'Delphi (Compiler Version ' + FloatToStr(CompilerVersion) + ')'
316 {$else}
317
318 {$ifdef __GPC__}
319 'GNU Pascal'
320 {$else}
321
322 'Unrecognized compiler'
323
324 {$endif} {$endif} {$endif};
325 end;
326
327 function SPlatformDescription: String;
328 begin
329 Result := PlatformToStr(Platform) +
330 {$ifdef FPC}
331 ', OS: ' + {$I %FPCTARGETOS%} +
332 ', CPU: ' + {$I %FPCTARGETCPU%} +
333 {$else}
334 ', OS Version: ' + TOSVersion.ToString +
335 {$endif}
336 { Clearly stating CPU bits is more obvious in some cases.
337 E.g. this avoids the question "what does Arm mean, is it 32-bit or 64-bit Arm?". }
338 ' (code compiled for ' + IntToStr(SizeOf(Pointer) * 8) + '-bit architecture)';
339 end;
340
341 function SCastleEngineProgramHelpSuffix(const AppName, AppVersion: String; const Ignored: Boolean): String;
342 begin
343 Result :=
344 AppName + ' version ' + AppVersion + '.' + NL +
345 'Using Castle Game Engine ( https://castle-engine.io/ ) version ' + CastleEngineVersion + '.' + NL +
346 'Compiled with ' + SCompilerDescription + '.' + NL +
347 'Platform: ' + SPlatformDescription + '.';
348 end;
349
350 procedure OSCheck(TrueValue: boolean);
351 begin
352 if not TrueValue then RaiseLastOSError;
353 end;
354
355 procedure OSCheck(TrueValue: boolean; const Place: string);
356 begin
357 if not TrueValue then
358 try
359 RaiseLastOSError;
360 except on E: EOSError do
361 begin
362 E.Message := Place + ': ' + E.Message;
363 raise;
364 end;
365 end;
366 end;
367
368 constructor TNoParameterlessContructor.Create;
369 begin
370 raise Exception.Create('Parameterless constructor of ' + ClassName + ' should never be called');
371 end;
372
373 {$ifndef FPC}
374 { Delphi on Linux has weird bugs when one tries to use TFormatSettings.Create
375 too often, which would happen if we define
376
377 function DefaultFormatSettings: TFormatSettings;
378 begin
379 Result := TFormatSettings.Create;
380 end;
381
382 and then use e.g. FloatToStrDisplay from TVector3.ToString,
383 by printing in each update:
384
385 Writeln('Got SetRotation ', FRotation.ToString);
386
387 Doing this from TCastleTransform.SetRotation every frame
388 causes the screen to go black when rendering on Delphi/Linux.
389
390 Also FPC display is then never updated, and it seems
391 FRealFps or FOnlyRenderFps never changes.
392
393 Also sprite sheets animation then hangs from time to time.
394
395 Compiler bug? The relations are completely weird.
396 And the weird stuff is only on Delphi/Linux,
397 works fine with Delphi/Windows (and FPC naturally too, but FPC
398 has simpler DefaultFormatSettings).
399 Doing it in a simpler way, just initialize DefaultFormatSettings once,
400 works better and makes all above weird problems disappear. }
401
402 var
403 DefaultFormatSettings: TFormatSettings;
404 {$endif}
405
406 function FormatDot(const Fmt: String; const Args: array of const): String;
407 var
408 FormatSettings: TFormatSettings;
409 begin
410 FormatSettings := DefaultFormatSettings;
411 FormatSettings.DecimalSeparator := '.';
412 FormatSettings.ThousandSeparator := #0;
413 Result := Format(Fmt, Args, FormatSettings);
414 end;
415
416 function FloatToStrDot(const Value: Extended): String;
417 var
418 FormatSettings: TFormatSettings;
419 begin
420 FormatSettings := DefaultFormatSettings;
421 FormatSettings.DecimalSeparator := '.';
422 FormatSettings.ThousandSeparator := #0;
423 Result := FloatToStr(Value, FormatSettings);
424 end;
425
426 function FloatToStrFDot(const Value: Extended;
427 const FloatFormat: TFloatFormat;
428 const Precision: Integer;
429 const Digits: Integer): String;
430 var
431 FormatSettings: TFormatSettings;
432 begin
433 FormatSettings := DefaultFormatSettings;
434 FormatSettings.DecimalSeparator := '.';
435 FormatSettings.ThousandSeparator := #0;
436 Result := FloatToStrF(Value, FloatFormat, Precision, Digits, FormatSettings);
437 end;
438
439 function FloatToStrDisplay(const AValue: Extended): String;
440 begin
441 Result := FloatToStrFDot(AValue, ffFixed,
442 { With FPC, Precision = 0 is also OK, but with Delphi it's not,
443 it will use scientific notation then early, e.g. for 123.0.
444 See TTestCastleUtils.TestFloatToStrDisplay testcase. }
445 20,
446 2);
447
448 { We remove trailing zeroes after decimal separator, we don't need them.
449 A less hacky way (that doesn't involve string fixing) would be nicer,
450 but it doesn't seem possible based on FloatToStrF possibilities,
451 at least with FPC. }
452 if Pos('.', Result) <> 0 then
453 begin
454 while Result[Length(Result)] = '0' do
455 SetLength(Result, Length(Result) - 1);
456 // previous removals of zero possibly removed all zeroes after ., so remove .
457 if Result[Length(Result)] = '.' then
458 SetLength(Result, Length(Result) - 1);
459 end;
460 end;
461
462 (*
463 function TryStrToFloatDot(const S: String; out Value: Single): Boolean;
464 var
465 FormatSettings: TFormatSettings;
466 begin
467 FormatSettings := DefaultFormatSettings;
468 FormatSettings.DecimalSeparator := '.';
469 Result := TryStrToFloat(S, Value, FormatSettings);
470 end;
471
472 function TryStrToFloatDot(const S: String; out Value: Double): Boolean;
473 var
474 FormatSettings: TFormatSettings;
475 begin
476 FormatSettings := DefaultFormatSettings;
477 FormatSettings.DecimalSeparator := '.';
478 Result := TryStrToFloat(S, Value, FormatSettings);
479 end;
480
481 {$ifdef EXTENDED_OVERLOADS}
482 function TryStrToFloatDot(const S: String; out Value: Extended): Boolean;
483 var
484 FormatSettings: TFormatSettings;
485 begin
486 FormatSettings := DefaultFormatSettings;
487 FormatSettings.DecimalSeparator := '.';
488 Result := TryStrToFloat(S, Value, FormatSettings);
489 end;
490 {$endif}
491
492 function StrToFloatDot(const S: String): Extended;
493 var
494 FormatSettings: TFormatSettings;
495 begin
496 FormatSettings := DefaultFormatSettings;
497 FormatSettings.DecimalSeparator := '.';
498 Result := StrToFloat(S, FormatSettings);
499 end;
500
501 function StrToFloatDefDot(const S: String; const Default: Extended): Extended;
502 var
503 FormatSettings: TFormatSettings;
504 begin
505 FormatSettings := DefaultFormatSettings;
506 FormatSettings.DecimalSeparator := '.';
507 Result := StrToFloatDef(S, Default, FormatSettings);
508 end;
509 *)
510
511 { We use Val, instead of calling StrToFloat with modified TFormatSettings.
512 This makes our "Dot" routines slightly faster.
513 This matters e.g. when parsing 3D model formats that encode floats in text. }
514
515 function TryStrToFloatDot(const S: String; out Value: Single): Boolean;
516 var
517 Err: Integer;
518 begin
519 Val(S, Value, Err);
520 Result := Err = 0;
521 end;
522
523 function TryStrToFloatDot(const S: String; out Value: Double): Boolean;
524 var
525 Err: Integer;
526 begin
527 Val(S, Value, Err);
528 Result := Err = 0;
529 end;
530
531 {$ifdef EXTENDED_OVERLOADS}
532 function TryStrToFloatDot(const S: String; out Value: Extended): Boolean;
533 var
534 Err: Integer;
535 begin
536 Val(S, Value, Err);
537 Result := Err = 0;
538 end;
539 {$endif}
540
541 function StrToFloatDot(const S: String): Extended;
542 var
543 Err: Integer;
544 begin
545 Val(S, Result, Err);
546 if Err <> 0 then
547 raise EConvertError.CreateFmt('"%s" is an invalid float', [S]);
548 end;
549
550 function StrToFloatDefDot(const S: String; const Default: Extended): Extended;
551 var
552 Err: Integer;
553 begin
554 Val(S, Result, Err);
555 if Err <> 0 then
556 Result := Default;
557 end;
558
559 function CastleApplicationMode: TCastleApplicationMode;
560 begin
561 Result := InternalCastleApplicationMode;
562 end;
563
564 function CastleDesignMode: Boolean;
565 begin
566 Result := InternalCastleApplicationMode <> appRunning;
567 end;
568
569 {$endif read_implementation}