SDL_surface_pixel_impl.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Copyright 1997-2023 Sam Lantinga <slouken@libsdl.org>
  3. Copyright 2023 Collabora Ltd.
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL3/SDL.h"
  19. /* Internal implementation of SDL_ReadSurfacePixel, shared between SDL_shape
  20. * and SDLTest */
  21. static int SDL_ReadSurfacePixel_impl(SDL_Surface *surface, int x, int y, Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a)
  22. {
  23. Uint32 pixel = 0;
  24. size_t bytes_per_pixel;
  25. void *p;
  26. if (surface == NULL || surface->format == NULL || surface->pixels == NULL) {
  27. return SDL_InvalidParamError("surface");
  28. }
  29. if (x < 0 || x >= surface->w) {
  30. return SDL_InvalidParamError("x");
  31. }
  32. if (y < 0 || y >= surface->h) {
  33. return SDL_InvalidParamError("y");
  34. }
  35. if (r == NULL) {
  36. return SDL_InvalidParamError("r");
  37. }
  38. if (g == NULL) {
  39. return SDL_InvalidParamError("g");
  40. }
  41. if (b == NULL) {
  42. return SDL_InvalidParamError("b");
  43. }
  44. if (a == NULL) {
  45. return SDL_InvalidParamError("a");
  46. }
  47. bytes_per_pixel = surface->format->BytesPerPixel;
  48. if (bytes_per_pixel > sizeof(pixel)) {
  49. return SDL_InvalidParamError("surface->format->BytesPerPixel");
  50. }
  51. SDL_LockSurface(surface);
  52. p = (Uint8 *)surface->pixels + y * surface->pitch + x * bytes_per_pixel;
  53. /* Fill the appropriate number of least-significant bytes of pixel,
  54. * leaving the most-significant bytes set to zero */
  55. #if SDL_BYTEORDER == SDL_BIG_ENDIAN
  56. SDL_memcpy(((Uint8 *) &pixel) + (sizeof(pixel) - bytes_per_pixel), p, bytes_per_pixel);
  57. #else
  58. SDL_memcpy(&pixel, p, bytes_per_pixel);
  59. #endif
  60. SDL_GetRGBA(pixel, surface->format, r, g, b, a);
  61. SDL_UnlockSurface(surface);
  62. return 0;
  63. }