-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathApus.Engine.Scene.pas
More file actions
378 lines (322 loc) · 12.5 KB
/
Apus.Engine.Scene.pas
File metadata and controls
378 lines (322 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Base Scene and SceneEffect classes
//
// Copyright (C) 2022 Ivan Polyacov, Apus Software (ivan@apus-software.com)
// This file is licensed under the terms of BSD-3 license (see license.txt)
// This file is a part of the Apus Game Engine (http://apus-software.com/engine/)
unit Apus.Engine.Scene;
interface
uses Apus.Core, Apus.Classes, Apus.Containers;
type
TGameScene=class;
// Базовый эффект для background-сцены
TSceneEffect=class
timer:integer; // время (в тысячных секунды), прошедшее с момента начала эффекта
duration:integer; // время, за которое эффект должен выполнится
done:boolean; // Флаг, сигнализирующий о том, что эффект завершен
target:TGameScene;
name:String8; // description for debug reasons
constructor Create(scene:TGameScene;TotalTime:integer); // создать эффект на заданное время (в мс.)
procedure DrawScene; virtual; abstract; // Процедура должна полностью выполнить отрисовку сцены с эффектом (в текущий RT)
destructor Destroy; override;
end;
// Base scene switcher interface
TSceneSwitcher=class
class var defaultSwitcher:TSceneSwitcher; // global scene switcher is here
procedure SwitchToScene(name:string8); virtual; abstract; // switch to a fullscreen scene
procedure ShowWindowScene(name:string8;modal:boolean=true); virtual; abstract; // show a windowed scene
procedure HideWindowScene(name:string8); virtual; abstract; // hide a windowed scene
end;
TSceneStatus=(ssFrozen, // scene is completely frozen (not processed, not rendered)
ssBackground, // scene is processed but not rendered
ssActive); // scene is active: processed and rendered
// -------------------------------------------------------------------
// TGameScene — a visual layer bound to a window.
//
// Lifecycle:
// Create(window) — any thread. Set up all state not requiring a render context.
// Load — called automatically, not from the render thread.
// Load heavy resources here (textures, data).
// InitGfx — render thread, once, automatic. Allocate render targets, shaders, etc.
// Most scenes leave this empty. Never call manually.
// Process — called at specified frequency while not frozen.
// Render — render thread, each frame while active.
// -------------------------------------------------------------------
TGameScene=class(TNamedObject)
ownerWindow:pointer; // window that owns this scene (Apus.Engine.Window.TWindow)
status:TSceneStatus;
fullscreen:boolean; // true - opaque scene, no any underlying scenes can be seen, false - scene layer is drawn above underlying image
frequency:integer; // Сколько раз в секунду нужно вызывать обработчик сцены (0 - каждый кадр)
effect:TSceneEffect; // Эффект, применяемый при выводе сцены
zOrder:integer; // Определяет порядок отрисовки сцен
activated:boolean; // true если сцена уже начала показываться или показалась, но еще не имеет эффекта закрытия
shadowColor:cardinal; // если не 0, то рисуется перед отрисовкой сцены
ignoreKeyboardEvents:boolean; // если true - такая сцена не будет получать сигналы о клавиатурном вводе, даже будучи верхней
gfxInitialized:boolean; // true after InitGfx was called by the render loop
loaded:boolean; // true after Load has completed
// Внутренние величины
accumTime:integer; // накопленное время (в мс)
constructor Create(fullscreen:boolean=true); overload;
// Unified constructor: optional scene name and optional owner window object.
// If wnd=nil then scene is attached to global window (when available).
constructor Create(sceneName:string='';fullscreen:boolean=true;wnd:TObject=nil); overload;
destructor Destroy; override;
// Вызывается из конструктора, можно переопределить для инициализации без влезания в конструктор
// !!! Call this manually from constructor!
procedure onCreate; virtual;
// Для изменения статуса использовать только это!
procedure SetStatus(st:TSceneStatus); virtual;
// status=ssActive
function IsActive:boolean;
// Called automatically outside the render thread to load heavy resources
procedure Load; virtual;
// Called once by the render loop before the first Render(). Never call manually.
// Override only to allocate GPU resources (render targets, shaders, etc.)
procedure InitGfx; virtual;
// Called with the specified frequency (regardless of the FPS) unless scene is Frozen
// Can return false if scene doesn't change and doesn't need to be rendered
function Process:boolean; virtual;
// Рисование сцены. Вызывается каждый кадр только если сцена активна и изменилась
// На момент вызова установлен RenderTarget и все готово к рисованию
// Если сцена соержит свой слой UI, то этот метод должен вызвать
// рисовалку UI для его отображения
procedure Render; virtual;
// Check if there are any key events in the keys buffer
function KeyPressed:boolean; virtual;
// Read buffered key event: 0xAAAABBCC or 0 if no any keys were pressed
// AAAA - unicode char, BB - scancode, CC - ansi char
function ReadKey:cardinal; virtual;
// Записать клавишу в буфер
procedure WriteKey(key:cardinal); virtual;
// Очистить буфер нажатий
procedure ClearKeyBuf; virtual;
// Смена режима (что именно изменилось - можно узнать косвенно)
procedure ModeChanged; virtual;
// Сообщение о том, что область отрисовки (она может быть частью окна) изменила размер, сцена может отреагировать на это
procedure onResize; virtual;
// События мыши
procedure onMouseMove(x,y:integer); virtual;
procedure onMouseBtn(btn:byte;pressed:boolean); virtual;
procedure onMouseWheel(delta:integer); virtual;
procedure onShow; virtual; // called when status changed to Active
procedure onHide; virtual; // called when status changed from Active
procedure onEvent(eventPart:String8;tag:NativeInt); virtual; // called when 'Scenes\[SceneName]\xxx' event is fired, "xxx" part is passed
// For non-fullscreen scenes return occupied area
function GetArea:TRect; virtual; abstract;
// Return scene UI root object when available (nil for non-UI scenes)
function GetUIRoot:TObject; virtual;
// Call "Load" for all scenes (if applicable)
class procedure LoadAllScenes;
protected
class function ClassHash:pointer; override;
private
// Keyboard input
keyBuffer:TQueue;
end;
implementation
uses SysUtils,
Apus.Strings,
Apus.EventMan,
Apus.Conv,
Apus.Lib,
Apus.Engine.Window,
Apus.Engine.API;
var
scenesHash:TObjectHash; // used to search scenes by name
scenesToLoad:TObjectList; // order of scenes to load
eventSet:boolean=false;
// SCENES\* handler
procedure EventHandler(event:TEventStr;tag:TTag);
var
scene:TGameScene;
p:integer;
name:String8;
begin
p:=event.IndexOf('\',8);
name:=Copy(event,8,p-8);
scene:=TGameScene.FindByName(name) as TGameScene;
if scene<>nil then
scene.onEvent(Copy(event,p+1,1000),tag);
end;
{ TGameScene }
class function TGameScene.ClassHash: pointer;
begin
result:=@scenesHash;
end;
procedure TGameScene.ClearKeyBuf;
begin
keyBuffer.Clear;
end;
constructor TGameScene.Create(fullScreen:boolean=true);
begin
ownerWindow:=nil;
status:=ssFrozen;
self.fullscreen:=fullscreen;
frequency:=0;
keyBuffer.Init(64);
zorder:=0;
activated:=false;
effect:=nil;
name:=ClassName;
ignoreKeyboardEvents:=false;
if classType=TGameScene then onCreate; // each generic child class must call this in the constructors last string
scenesToLoad.Add(self);
if not eventSet then begin
eventSet:=true;
SetEventHandler('SCENES\',eventHandler,emInstant);
end;
end;
constructor TGameScene.Create(sceneName:string;fullscreen:boolean;wnd:TObject);
var
targetWnd:TWindow;
begin
Create(fullscreen);
if sceneName<>'' then
name:=sceneName;
if wnd=nil then
targetWnd:=window
else
if wnd is TWindow then
targetWnd:=TWindow(wnd)
else
targetWnd:=nil;
if (targetWnd<>nil) and (ownerWindow=nil) then
targetWnd.AddScene(self);
end;
destructor TGameScene.Destroy;
begin
if status<>ssFrozen then
raise EError.Create('Scene must be frozen before deletion: '+name+' ('+ClassName+')');
scenesToLoad.Remove(self);
end;
procedure TGameScene.InitGfx;
begin
end;
function TGameScene.IsActive: boolean;
begin
result:=status=ssActive;
end;
procedure TGameScene.ModeChanged;
begin
end;
procedure TGameScene.onMouseBtn(btn: byte; pressed: boolean);
begin
end;
procedure TGameScene.onMouseMove(x, y: integer);
begin
end;
procedure TGameScene.onMouseWheel(delta:integer);
begin
end;
procedure TGameScene.onResize;
begin
end;
procedure TGameScene.onShow;
begin
end;
procedure TGameScene.onHide;
begin
end;
function TGameScene.Process:boolean;
begin
result:=true;
end;
function TGameScene.GetUIRoot:TObject;
begin
result:=nil;
end;
procedure TGameScene.onCreate;
begin
end;
procedure TGameScene.onEvent(eventPart:String8;tag:NativeInt);
begin
end;
procedure TGameScene.Load;
begin
loaded:=true;
end;
class procedure TGameScene.LoadAllScenes;
var
scene:TGameScene;
begin
Log.Force('Loading all scenes');
repeat
scene:=scenesToLoad.RemoveFirst as TGameScene;
if scene=nil then break;
if not scene.loaded then begin
Log.Msg('Loading scene: "%s"',[scene.name]);
scene.Load;
Log.Msg('Scene "%s" loaded!',[scene.name]);
scene.loaded:=true;
end;
until false;
Log.Force('All scenes loaded!');
end;
function TGameScene.KeyPressed:boolean;
begin
result:=not keyBuffer.Empty;
end;
function TGameScene.ReadKey:cardinal;
var
item,next:TDataItem;
begin
if keyBuffer.Get(item) then begin
result:=cardinal(item.data);
if not keyBuffer.Empty then begin
// It's possible that one keystroke event is logged twice: once for KEY event and then for CHAR event
// So check this out: if this event is for KEY and there is another for CHAR - drop this one and return the second one.
keyBuffer.Get(next);
if (next.data) and $FF00=(item.data) and $FF00 then // same scancode — return CHAR event
result:=cardinal(next.data)
else
keyBuffer.Add(next); // put back (although order may change)
end;
end else
result:=0;
end;
procedure TGameScene.WriteKey(key:cardinal);
var
item:TDataItem;
begin
item.data:=integer(key);
keyBuffer.Add(item);
end;
procedure TGameScene.Render;
begin
end;
procedure TGameScene.SetStatus(st:TSceneStatus);
var
wasActive:boolean;
begin
if status=st then exit; // no change
wasActive:=status=ssActive;
if (st=ssActive) and not loaded then
Log.Msg('WARN! Activating scene "%s" which was not loaded',[name]);
if st=ssActive then onShow; // make sure to call this BEFORE the scene become active
status:=st;
activated:=st=ssActive;
if wasActive and (status<>ssActive) then onHide;
end;
{ TSceneEffect }
constructor TSceneEffect.Create(scene:TGameScene;TotalTime:integer);
begin
done:=false;
duration:=TotalTime;
if duration=0 then duration:=10;
timer:=0;
if scene.effect<>nil then begin
Log.Force('New scene effect replaces old one! '+scene.name+' previous='+scene.effect.name);
scene.effect.Free;
end;
scene.effect:=self;
target:=scene;
name:=self.ClassName+' for '+scene.name+' created '+FormatDateTime('nn:ss.zzz',Now);
Log.Msg('Effect %s: %s',[Conv.ToStr(self),name]);
end;
destructor TSceneEffect.Destroy;
begin
Log.Msg('Scene effect %s deleted: %s',[Conv.ToStr(self),name]);
inherited;
end;
initialization
scenesHash.Init(40);
end.