Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
RenderSurfaceHostBase.cs
6using SkiaSharp;
7
8namespace Gondwana.Rendering;
9
14public abstract class RenderSurfaceHostBase : IDisposable
15{
17 public Diagnostics.TelemetrySource? Telemetry { get; internal set; }
18
19 internal RenderFrameMailbox FrameMailbox { get; } = new();
20 internal bool UsesRenderFrameSnapshots => !OperatingSystem.IsBrowser() && Backbuffer is GpuBackbuffer;
21 internal virtual void ProduceRenderFrameSnapshot(long tick) { }
22
32 {
33 Effects = new EffectsManager(this);
34 RenderSurfaceHostRegistry.Register(this);
35 }
36
42
46 public abstract BackbufferBase Backbuffer { get; }
47
49 public float PresentationScale => RenderSurfaceAdapter?.PresentationScale ?? 0f;
50
51 internal virtual void RequestRenderScale(float scale) { }
52 internal virtual void InvalidatePresentation() { }
53
57 public abstract Scene Scene { get; }
58
64
76 public abstract ViewManager ViewManager { get; }
77
81 public EffectsManager Effects { get; }
82
87 public event Action<GpuRenderSynchronizationDiagnostics>? GpuRenderSynchronizationDiagnosticsCalculated;
88
115 public SKImage? GlRenderAndSnapshot()
116 {
117 if (!Backbuffer.IsGlThreadRendered)
118 return null;
119
120 if (UsesRenderFrameSnapshots)
121 return ReplayRenderFrameSnapshot();
122
123 bool collectSynchronizationDiagnostics =
125
126 long waitStarted = collectSynchronizationDiagnostics
127 ? HighResTimer.GetCurrentTick()
128 : 0;
129
130 long lockAcquired = 0;
131 long lockReleased = 0;
132 SKImage? image;
133
134 RenderStateSynchronization.EnterGpuRender();
135
136 try
137 {
138 if (collectSynchronizationDiagnostics)
139 lockAcquired = HighResTimer.GetCurrentTick();
140
141 var tick = HighResTimer.GetCurrentTick();
142
143 RenderToBackbuffer(tick);
144 Backbuffer.EndFrame();
145
146 image = Backbuffer.Snapshot();
147
148 Backbuffer.BeginFrame();
149
150 if (collectSynchronizationDiagnostics)
151 lockReleased = HighResTimer.GetCurrentTick();
152 }
153 finally
154 {
155 RenderStateSynchronization.ExitGpuRender();
156 }
157
158 if (collectSynchronizationDiagnostics)
159 {
162 HighResTimer.GetDuration(waitStarted, lockAcquired) * 1000d,
163 HighResTimer.GetDuration(lockAcquired, lockReleased) * 1000d));
164 }
165
166 return image;
167 }
168
169 private SKImage? ReplayRenderFrameSnapshot()
170 {
172 long telemetryGeneration = Telemetry?.BeginSample() ?? 0;
173 bool collectDiagnostics = diagnostics is not null || telemetryGeneration != 0;
174 var slot = FrameMailbox.TryAcquire();
175
176 if (slot is null)
177 return Backbuffer.Snapshot();
178
179 long acquired = !collectDiagnostics ? 0 : HighResTimer.GetCurrentTick();
180 var counters = !collectDiagnostics ? default : FrameMailbox.Counters;
181 long replayEnd = acquired;
182 bool replayCompleted = false;
183 long pictureReplayTicks = 0;
184 long backbufferFlushTicks = 0;
185 long snapshotTicks = 0;
186 int commands = !collectDiagnostics ? 0 : slot.Frame!.CommandCount;
187 double age = !collectDiagnostics ? 0 : HighResTimer.GetDuration(slot.Frame!.ProducedTick, acquired) * 1000d;
188
189 try
190 {
191 var frame = slot.Frame!;
192
193 // A logical resize invalidates geometry, but context/MSAA recreation does
194 // not: recordings contain CPU resources and are uploaded by the current GL context.
195 if (frame.Width != Backbuffer.Width || frame.Height != Backbuffer.Height)
196 {
197 long snapshotStart = !collectDiagnostics ? 0 : HighResTimer.GetCurrentTick();
198 var resizedSnapshot = Backbuffer.Snapshot();
199
200 if (collectDiagnostics)
201 snapshotTicks = HighResTimer.GetCurrentTick() - snapshotStart;
202
203 return resizedSnapshot;
204 }
205
206 Backbuffer.BeginFrame();
207
208 long pictureStart = !collectDiagnostics ? 0 : HighResTimer.GetCurrentTick();
209 frame.Replay(Backbuffer.Canvas);
210 long pictureEnd = !collectDiagnostics ? 0 : HighResTimer.GetCurrentTick();
211
212 Backbuffer.EndFrame();
213 long flushEnd = !collectDiagnostics ? 0 : HighResTimer.GetCurrentTick();
214 replayCompleted = true;
215
216 if (collectDiagnostics)
217 {
218 pictureReplayTicks = pictureEnd - pictureStart;
219 backbufferFlushTicks = flushEnd - pictureEnd;
220 replayEnd = flushEnd;
221 }
222
223 long snapshotStartTick = !collectDiagnostics ? 0 : HighResTimer.GetCurrentTick();
224 var snapshot = Backbuffer.Snapshot();
225
226 if (collectDiagnostics)
227 snapshotTicks = HighResTimer.GetCurrentTick() - snapshotStartTick;
228
229 return snapshot;
230 }
231 finally
232 {
233 try
234 {
235 Backbuffer.BeginFrame();
236 }
237 finally
238 {
239 FrameMailbox.Release(slot);
240 }
241
242 if (collectDiagnostics)
243 {
244 double replayMs = HighResTimer.GetDuration(acquired, replayEnd) * 1000d;
245 double pictureMs = HighResTimer.GetDuration(0, pictureReplayTicks) * 1000d;
246 double flushMs = HighResTimer.GetDuration(0, backbufferFlushTicks) * 1000d;
247 double snapshotMs = HighResTimer.GetDuration(0, snapshotTicks) * 1000d;
248
249 if (telemetryGeneration != 0)
250 {
251 if (replayCompleted)
252 {
253 Telemetry!.Record(telemetryGeneration, "replay.cpu.ms", replayMs);
254 Telemetry.Record(telemetryGeneration, "picture.cpu.ms", pictureMs);
255 Telemetry.Record(telemetryGeneration, "backbuffer.flush.cpu.ms", flushMs);
256 }
257
258 Telemetry!.Record(telemetryGeneration, "snapshot.cpu.ms", snapshotMs);
259 Telemetry.Record(telemetryGeneration, "snapshot.age.ms", age);
260 Telemetry.Record(telemetryGeneration, "mailbox.published.lifetime", counters.Published);
261 Telemetry.Record(telemetryGeneration, "mailbox.dropped.lifetime", counters.Dropped);
262 Telemetry.Record(telemetryGeneration, "mailbox.slots", counters.InUse);
263 Telemetry.Record(telemetryGeneration, "snapshot.commands.approximate", commands);
264 }
265
266 diagnostics?.Invoke(
267 new(0, 0)
268 {
269 ReplayMilliseconds = replayMs,
270 PictureReplayMilliseconds = pictureMs,
271 BackbufferFlushMilliseconds = flushMs,
272 SnapshotMilliseconds = snapshotMs,
273 SnapshotAgeMilliseconds = age,
274 PublishedSnapshots = counters.Published,
275 DroppedSnapshots = counters.Dropped,
276 SnapshotSlotsInUse = counters.InUse,
277 SnapshotCommandCount = commands
278 });
279 }
280 }
281 }
282
295 public bool GlRenderToCanvas(SKCanvas destinationCanvas)
296 {
297 ArgumentNullException.ThrowIfNull(destinationCanvas);
298
299 if (!Backbuffer.IsGlThreadRendered)
300 return false;
301
302 if (UsesRenderFrameSnapshots)
303 {
304 using var image = ReplayRenderFrameSnapshot();
305 DrawCurrentSurface(destinationCanvas);
306 return true;
307 }
308
309 RenderStateSynchronization.EnterGpuRender();
310
311 try
312 {
313 var tick = HighResTimer.GetCurrentTick();
314
315 RenderToBackbuffer(tick);
316 Backbuffer.EndFrame();
317
318 try
319 {
320 DrawCurrentSurface(destinationCanvas);
321 return true;
322 }
323 finally
324 {
325 Backbuffer.BeginFrame();
326 }
327 }
328 finally
329 {
330 RenderStateSynchronization.ExitGpuRender();
331 }
332 }
333
345 public bool GlDrawCurrentFrameToCanvas(SKCanvas destinationCanvas)
346 {
347 ArgumentNullException.ThrowIfNull(destinationCanvas);
348
349 if (!Backbuffer.IsGlThreadRendered)
350 return false;
351
352 DrawCurrentSurface(destinationCanvas);
353 return true;
354 }
355
356 private void DrawCurrentSurface(SKCanvas canvas)
357 {
358 var presentation = RenderSurfaceAdapter?.Presentation ?? default;
359 canvas.Clear(Backbuffer.ClearColor);
360
361 if (presentation.Scale <= 0)
362 return;
363
364 canvas.Save();
365
366 try
367 {
368 canvas.Translate(presentation.DestinationRect.Left, presentation.DestinationRect.Top);
369 canvas.Scale(presentation.Scale);
370
371 bool needsLinearSampling =
372 Engine.Instance.Configuration.RenderScalingFilter == RenderScalingFilter.Linear &&
373 (presentation.Scale != 1f ||
374 presentation.DestinationRect.Left != MathF.Floor(presentation.DestinationRect.Left) ||
375 presentation.DestinationRect.Top != MathF.Floor(presentation.DestinationRect.Top));
376
377 if (needsLinearSampling)
378 {
379 // Skia's DrawSurface does not expose sampling and ignores SKPaint.FilterQuality.
380 // A scoped snapshot is a GPU texture view, not a readback or an intermediate copy.
381 using var image = Backbuffer.Snapshot();
382
383 canvas.DrawImage(
384 image,
385 0,
386 0,
387 RenderSurfaceAdapterBase.PresentationSampling);
388 }
389 else
390 {
391 canvas.DrawSurface(Backbuffer.Canvas.Surface, 0, 0);
392 }
393 }
394 finally
395 {
396 canvas.Restore();
397 }
398 }
399
418 public SKImage? GlSnapshotCurrentFrame()
419 {
420 if (!Backbuffer.IsGlThreadRendered)
421 return null;
422
423 return Backbuffer.Snapshot();
424 }
425
431 internal abstract void RenderToBackbuffer(long tick);
432
437 internal abstract void PresentBackbufferToAdapter();
438
453 public void Dispose()
454 {
455 lock (RenderStateSynchronization.SyncRoot)
456 Dispose(true);
457
458 GC.SuppressFinalize(this);
459 }
460
474 protected virtual void Dispose(bool disposing)
475 {
476 Telemetry?.Dispose();
477
478 if (disposing)
479 {
480 FrameMailbox.Dispose();
481 Effects.Dispose();
482 }
483
484 RenderSurfaceHostRegistry.Unregister(this);
485 }
486}
Bounded extension source. Define measurements once, capture a generation before work,...
Owns and advances display effects for one RenderSurfaceHost.
Represents a base class for managing a graphical backbuffer, and is the in-memory surface where rende...
int Width
Gets the current Backbuffer width in a thread-safe manner.
int Height
Gets the current Backbuffer height in a thread-safe manner.
SKColor ClearColor
Gets or sets the color used to clear the drawing surface.
SKCanvas Canvas
Gets the SkiaSharp canvas used for drawing operations on this backbuffer.
Provides a fully GPU-rendered backbuffer implementation using SkiaSharp and OpenGL.
Represents the abstract base class for render surface adapters that present backbuffer output to a de...
PresentationTransform Presentation
Current immutable aspect-preserving mapping of Backbuffer ScreenPx to adapter pixels.
Represents a base class for hosting a render surface, providing functionality for managing rendering ...
RenderSurfaceHostBase()
Initializes a new instance of the RenderSurfaceHostBase class and registers it with the RenderSurface...
EffectsManager Effects
Gets the manager that owns presentation effects for this render surface.
Action< GpuRenderSynchronizationDiagnostics >? GpuRenderSynchronizationDiagnosticsCalculated
Occurs after a GPU render/snapshot call when a subscriber requests timing for the shared render-state...
virtual void Dispose(bool disposing)
Releases resources used by this RenderSurfaceHostBase instance and unregisters it from the RenderSurf...
Diagnostics.? TelemetrySource Telemetry
Neutral session-local measurements for this host; null when source capacity is exhausted or the share...
Scene Scene
Gets the source Scenes.Scene used for rendering operations.
RenderSurfaceAdapterBase? RenderSurfaceAdapter
Gets the platform-specific RenderSurfaceAdapterBase responsible for rendering the image from the Back...
float PresentationScale
Actual scale used to fit this Backbuffer into its current adapter.
ViewManager ViewManager
Gets the view manager that controls camera positions, viewports, and multi-view rendering for this re...
bool GlDrawCurrentFrameToCanvas(SKCanvas destinationCanvas)
Draws the existing GPU backbuffer surface directly to another GPU canvas without rendering a new scen...
void Dispose()
Releases all resources used by this RenderSurfaceHostBase instance.
SKImage? GlRenderAndSnapshot()
Renders the current scene frame on the active GL/WebGL thread and returns a snapshot of the GPU backb...
BackbufferBase Backbuffer
Gets the in-memory BackbufferBase associated with the current rendering context.
bool GlRenderToCanvas(SKCanvas destinationCanvas)
Renders the current scene frame and draws the GPU backbuffer surface directly to another GPU canvas....
SKImage? GlSnapshotCurrentFrame()
Returns a snapshot of the current GPU backbuffer without rendering a new scene frame.
record GpuRenderSynchronizationDiagnostics(double LockWaitMilliseconds, double LockHeldMilliseconds)
Captures time spent waiting for and holding the shared live render-state synchronization gate.
@ Linear
Bilinear presentation filtering.