texture.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * 3D Engine
  3. * texture.c:
  4. * Based on pikuma.com 3D software renderer in C
  5. * Copyright (c) 2021 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 07/03/2021.
  8. */
  9. #include <stdlib.h>
  10. #include <upng.h>
  11. #include <texture.h>
  12. /***********************************************************************************************************************
  13. * Public functions
  14. **********************************************************************************************************************/
  15. void loadTextureDateFromPng(texture_t *tex, const char *filepath)
  16. {
  17. if (tex->png != NULL)
  18. {
  19. upng_free(tex->png);
  20. tex->png = NULL;
  21. }
  22. tex->png = upng_new_from_file(filepath);
  23. if (tex->png != NULL)
  24. {
  25. upng_decode(tex->png);
  26. if (upng_get_error(tex->png) == UPNG_EOK)
  27. {
  28. tex->data = (colour_t *)upng_get_buffer(tex->png);
  29. tex->width = upng_get_width(tex->png);
  30. tex->height = upng_get_height(tex->png);
  31. }
  32. }
  33. }
  34. void textureCleanup(texture_t *tex)
  35. {
  36. if (tex->png != NULL)
  37. {
  38. upng_free(tex->png);
  39. tex->png = NULL;
  40. }
  41. /* uPNG do free the buffer for us. */
  42. tex->data = NULL;
  43. }
  44. colour_t getTextureColour(texture_t *texture, tex2_t *position)
  45. {
  46. colour_t ret = 0;
  47. int32_t texX = FP_GET_INT(position->u);
  48. int32_t texY = FP_GET_INT(position->v);
  49. while(texX < 0) { texX += texture->width; }
  50. while(texY < 0) { texY += texture->height; }
  51. texX = texX % texture->width;
  52. texY = texY % texture->height;
  53. switch(upng_get_format(texture->png))
  54. {
  55. case UPNG_LUMINANCE8:
  56. ret = ((uint8_t *)texture->data)[(texY * texture->width) + texX];
  57. break;
  58. case UPNG_RGBA8:
  59. ret = ((colour_t *)texture->data)[(texY * texture->width) + texX];
  60. break;
  61. default:
  62. break;
  63. }
  64. return ret;
  65. }