首页 > 解决方案 > 每个纹理都应该在 SDL 中拥有自己的专用渲染器吗?

问题描述

我正在尝试学习 SDL2,但从实际角度来看遇到了困难。我觉得我从抽象的角度对 SDL 窗口、渲染器和纹理有了很好的理解。但是,我觉得我需要更多地了解引擎盖下发生的事情才能正确使用它们。

例如,在创建纹理时,我需要提供对渲染器的引用。我觉得这很奇怪。纹理看起来像是加载到 VRAM 中的资源。为什么我需要为资源提供对渲染器的引用?我理解为什么有必要为渲染器提供对纹理的引用,但是,反之亦然,这没有任何意义。

所以这就引出了另一个问题。既然每个纹理都需要一个渲染器,那么每个纹理应该有自己的专用渲染器,还是应该多个纹理共享一个渲染器?

我觉得沿着一条路线与另一条路线相比会产生后果。

标签: sdlsdl-2

解决方案


Short Answers

I believe the reason a SDL_Texture requires a renderer is because some backend implementations (OpenGL?) have contexts (this is essentially what SDL_Renderer is) and the image data must be associated with that particular context. You cannot use a texture created in one context inside of another.

for your other question, no, you don't need or want a renderer for each texture. That probably would only produce correct results with the software backend for the same reason (context).


As @keltar correctly points out none of the renderer's will work with a texture that was created with a different renderer due to a check in SDL_RenderCopy. However, this is strictly an API requirement to keep things consistent, my point above is to highlight that even if that check were absent it would not work for backends such as OpenGL, but there is no technical reason it would not work for the software renderer.


Some Details about SDL_Renderer

Remember that SDL_Renderer is an abstract interface to multiple possible backends (OpenGL, OpenGLES, D3D, Metal, Software, more?). Each of these are going to possibly have restrictions on sharing data between contexts and therefore SDL has to limit itself in the same way to maintain sanity.

Example of OpenGL restrictions

Here is a good resource for general restrictions and platform dependent functionality on OpenGL contexts.

As you can see from that page that sharing between contexts has restrictions.

  1. Sharing can only occur in the same OpenGL implementation

This means that you certainly cant share between an SDL_Renderer using OpenGL an a different SDL_Renderer using another backend.

  1. You can share data between different OpenGL Contexts ... This is done using OS Specific extensions

Since SDL is cross platform this means they would have to write special code for each platform to support this, and all OpenGL implementations may not support it at all so its better for SDL to simply not support this either.

  1. each extra render context has a major impact of the applications performance

while not a restriction, it is a reason why adding support for sharing textures is not worthwhile for SDL.

Final Note: the 'S' in SDL stands for "simple". If you need to share data between contexts SDL is simply the wrong tool for the job.


推荐阅读