load_texture.gui_script 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. local function set_message(text)
  2. gui.set_text(gui.get_node("message"), text) -- <11>
  3. end
  4. local function set_image(self, texture_id, image_data)
  5. if self.texture_id then -- <8>
  6. gui.delete_texture(self.texture_id)
  7. self.texture_id = nil
  8. end
  9. local img = image.load(image_data) -- <9>
  10. if not img then
  11. set_message("Unable to load image")
  12. return
  13. end
  14. if gui.new_texture(texture_id, img.width, img.height, img.type, img.buffer) then -- <10>
  15. self.texture_id = texture_id -- <11>
  16. gui.set_texture(gui.get_node("img"), texture_id) -- <12>
  17. set_message("Set new texture")
  18. else
  19. set_message("Unable to create texture")
  20. end
  21. end
  22. local load_image
  23. load_image = function(url)
  24. http.request(url, "GET", function(self, id, res) -- <6>
  25. -- redirect?
  26. if res.status == 302 or res.status == 301 then -- <7>
  27. set_message("Redirect: " .. res.headers.location)
  28. load_image(res.headers.location)
  29. -- ok or cached?
  30. elseif res.status == 200 or res.status == 304 then -- <7>
  31. set_image(self, url, res.response)
  32. -- error
  33. else
  34. set_message("Unable to get image: " .. res.response)
  35. end
  36. end)
  37. end
  38. local function load_random(self)
  39. local url = "https://picsum.photos/id/"..math.random(1, 10).."/200/300.jpg" -- <3>
  40. set_message("Loading...") -- <4>
  41. load_image(url) -- <5>
  42. end
  43. function init(self)
  44. msg.post(".", "acquire_input_focus") -- <1>
  45. load_random(self) -- <2>
  46. end
  47. function on_input(self, action_id, action)
  48. if action_id == hash("touch") and action.pressed then
  49. if gui.pick_node(gui.get_node("button"), action.x, action.y) then -- <13>
  50. load_random(self) -- <2>
  51. end
  52. end
  53. end
  54. --[[
  55. 1. Tell the engine that this game object wants to receive input.
  56. 2. Start loading random image
  57. 3. Generate a URL to a random image
  58. 4. Change the label text.
  59. 5. Call function load image from URL
  60. 6. Make an HTTP request and handle redirects
  61. 7. Check server response
  62. 8. Remove previous texture if any
  63. 9. Create an image resource from loaded image data
  64. 10. Create a new texture using image resource
  65. 11. Save the texture id
  66. 12. Set new texture as node texture
  67. 13. Check if the click position (`action.x` and `action.y`) is within the boundaries of
  68. the button node.
  69. --]]