runtime_file_loading_and_saving.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. .. _doc_runtime_loading_and_saving:
  2. Runtime file loading and saving
  3. ===============================
  4. .. seealso::
  5. See :ref:`doc_saving_games` for information on saving and loading game progression.
  6. Sometimes, :ref:`exporting packs, patches, and mods <doc_exporting_pcks>` is not
  7. ideal when you want players to be able to load user-generated content in your
  8. project. It requires users to generate a PCK or ZIP file through the Godot
  9. editor, which contains resources imported by Godot.
  10. Example use cases for runtime file loading and saving include:
  11. - Loading texture packs designed for the game.
  12. - Loading user-provided audio tracks and playing them back in an in-game radio station.
  13. - Loading custom levels or 3D models that can be designed with any 3D DCC that
  14. can export to glTF (including glTF scenes saved by Godot at runtime).
  15. - Using user-provided fonts for menus and HUD.
  16. - Saving/loading a file format that can contain multiple files but can still
  17. easily be read by other applications (ZIP).
  18. - Loading files created by another game or program, or even game data files from
  19. another game not made with Godot.
  20. Runtime file loading can be combined with :ref:`HTTP requests <doc_http_request_class>`
  21. to load resources from the Internet directly.
  22. .. warning::
  23. Do **not** use this runtime loading approach to load resources that are part
  24. of the project, as it's less efficient and doesn't allow benefiting from
  25. Godot's resource handling functionality (such as translation remaps). See
  26. :ref:`doc_import_process` for details.
  27. .. seealso::
  28. You can see how saving and loading works in action using the
  29. `Run-time File Saving and Loading (Serialization) demo project <https://github.com/godotengine/godot-demo-projects/blob/master/loading/runtime_save_load>`__.
  30. Plain text and binary files
  31. ---------------------------
  32. Godot's :ref:`class_FileAccess` class provides methods to access files on the
  33. filesystem for reading and writing:
  34. ::
  35. func save_file(content):
  36. var file = FileAccess.open("/path/to/file.txt", FileAccess.WRITE)
  37. file.store_string(content)
  38. func load_file():
  39. var file = FileAccess.open("/path/to/file.txt", FileAccess.READ)
  40. var content = file.get_as_text()
  41. return content
  42. To handle custom binary formats (such as loading file formats not supported by
  43. Godot), :ref:`class_FileAccess` provides several methods to read/write integers,
  44. floats, strings and more. These FileAccess methods have names that start with
  45. ``get_`` and ``store_``.
  46. If you need more control over reading binary files or need to read binary
  47. streams that are not part of a file, :ref:`class_PackedByteArray` provides
  48. several helper methods to decode/encode series of bytes to integers, floats,
  49. strings and more. These PackedByteArray methods have names that start with
  50. ``decode_`` and ``encode_``. See also :ref:`doc_binary_serialization_api`.
  51. .. _doc_runtime_file_loading_and_saving_images:
  52. Images
  53. ------
  54. Image's :ref:`Image.load_from_file <class_Image_method_load_from_file>` static method
  55. handles everything, from format detection based on file extension to reading the
  56. file from disk.
  57. If you need error handling or more control (such as changing the scale a SVG is
  58. loaded at), use one of the following methods depending on the file format:
  59. - :ref:`Image.load_jpg_from_buffer <class_Image_method_load_jpg_from_buffer>`
  60. - :ref:`Image.load_ktx_from_buffer <class_Image_method_load_ktx_from_buffer>`
  61. - :ref:`Image.load_png_from_buffer <class_Image_method_load_png_from_buffer>`
  62. - :ref:`Image.load_svg_from_buffer <class_Image_method_load_svg_from_buffer>`
  63. or :ref:`Image.load_svg_from_string <class_Image_method_load_svg_from_string>`
  64. - :ref:`Image.load_tga_from_buffer <class_Image_method_load_tga_from_buffer>`
  65. - :ref:`Image.load_webp_from_buffer <class_Image_method_load_webp_from_buffer>`
  66. Several image formats can also be saved by Godot at runtime using the following
  67. methods:
  68. - :ref:`Image.save_png <class_Image_method_save_png>`
  69. or :ref:`Image.save_png_to_buffer <class_Image_method_save_png_to_buffer>`
  70. - :ref:`Image.save_webp <class_Image_method_save_webp>`
  71. or :ref:`Image.save_webp_to_buffer <class_Image_method_save_webp_to_buffer>`
  72. - :ref:`Image.save_jpg <class_Image_method_save_jpg>`
  73. or :ref:`Image.save_jpg_to_buffer <class_Image_method_save_jpg_to_buffer>`
  74. - :ref:`Image.save_exr <class_Image_method_save_exr>`
  75. or :ref:`Image.save_exr_to_buffer <class_Image_method_save_exr_to_buffer>`
  76. *(only available in editor builds, cannot be used in exported projects)*
  77. The methods with the ``to_buffer`` suffix save the image to a PackedByteArray
  78. instead of the filesystem. This is useful to send the image over the network or
  79. into a ZIP archive without having to write it on the filesystem. This can
  80. increase performance by reducing I/O utilization.
  81. Example of loading an image and displaying it in a :ref:`class_TextureRect` node
  82. (which requires conversion to :ref:`class_ImageTexture`):
  83. ::
  84. # Load an image of any format supported by Godot from the filesystem.
  85. var image = Image.load_from_file(path)
  86. $TextureRect.texture = ImageTexture.create_from_image(image)
  87. # Save the loaded Image to a PNG image.
  88. image.save_png("/path/to/file.png")
  89. # Save the converted ImageTexture to a PNG image.
  90. $TextureRect.texture.get_image().save_png("/path/to/file.png")
  91. .. _doc_runtime_file_loading_and_saving_audio_video_files:
  92. Audio/video files
  93. -----------------
  94. Godot supports loading Ogg Vorbis audio at runtime. Note that not *all* files
  95. with an ``.ogg`` extension may be Ogg Vorbis files. Some may be Ogg Theora
  96. videos, or contain Opus audio within an Ogg container. These files will **not**
  97. load correctly as audio files in Godot.
  98. Example of loading an Ogg Vorbis audio file in an :ref:`class_AudioStreamPlayer` node:
  99. ::
  100. $AudioStreamPlayer.stream = AudioStreamOggVorbis.load_from_file(path)
  101. Example of loading an Ogg Theora video file in a :ref:`class_VideoStreamPlayer` node:
  102. ::
  103. var video_stream_theora = VideoStreamTheora.new()
  104. # File extension is ignored, so it is possible to load Ogg Theora videos
  105. # that have an `.ogg` extension this way.
  106. video_stream_theora.file = "/path/to/file.ogv"
  107. $VideoStreamPlayer.stream = video_stream_theora
  108. # VideoStreamPlayer's Autoplay property won't work if the stream is empty
  109. # before this property is set, so call `play()` after setting `stream`.
  110. $VideoStreamPlayer.play()
  111. .. note::
  112. Godot doesn't support runtime loading of MP3 or WAV files yet. Until this is
  113. implemented, it's feasible to implement runtime WAV loading using a script
  114. since :ref:`class_AudioStreamWAV`'s ``data`` property is exposed to
  115. scripting.
  116. It's still possible to *save* WAV files using
  117. :ref:`AudioStreamWAV.save_to_wav <class_AudioStreamWAV_method_save_to_wav>`, which is useful
  118. for procedurally generated audio or microphone recordings.
  119. .. _doc_runtime_file_loading_and_saving_3d_scenes:
  120. 3D scenes
  121. ---------
  122. Godot has first-class support for glTF 2.0, both in the editor and exported
  123. projects. Using :ref:`class_gltfdocument` and :ref:`class_gltfstate` together,
  124. Godot can load and save glTF files in exported projects, in both text
  125. (``.gltf``) and binary (``.glb``) formats. The binary format should be preferred
  126. as it's faster to write and smaller, but the text format is easier to debug.
  127. Example of loading a glTF scene and appending its root node to the scene:
  128. ::
  129. # Load an existing glTF scene.
  130. # GLTFState is used by GLTFDocument to store the loaded scene's state.
  131. # GLTFDocument is the class that handles actually loading glTF data into a Godot node tree,
  132. # which means it supports glTF features such as lights and cameras.
  133. var gltf_document_load = GLTFDocument.new()
  134. var gltf_state_load = GLTFState.new()
  135. var error = gltf_document_load.append_from_file("/path/to/file.gltf", gltf_state_load)
  136. if error == OK:
  137. var gltf_scene_root_node = gltf_document_load.generate_scene(gltf_state_load)
  138. add_child(gltf_scene_root_node)
  139. else:
  140. show_error("Couldn't load glTF scene (error code: %s)." % error_string(error))
  141. # Save a new glTF scene.
  142. var gltf_document_save := GLTFDocument.new()
  143. var gltf_state_save := GLTFState.new()
  144. gltf_document_save.append_from_scene(gltf_scene_root_node, gltf_state_save)
  145. # The file extension in the output `path` (`.gltf` or `.glb`) determines
  146. # whether the output uses text or binary format.
  147. # `GLTFDocument.generate_buffer()` is also available for saving to memory.
  148. gltf_document_save.write_to_filesystem(gltf_state_save, path)
  149. .. _doc_runtime_file_loading_and_saving_fonts:
  150. Fonts
  151. -----
  152. :ref:`FontFile.load_dynamic_font <class_FontFile_method_load_bitmap_font>` supports the following
  153. font file formats: TTF, OTF, WOFF, WOFF2, PFB, PFM
  154. On the other hand, :ref:`FontFile.load_bitmap_font <class_FontFile_method_load_bitmap_font>` supports
  155. the `BMFont <https://www.angelcode.com/products/bmfont/>`__ format (``.fnt`` or ``.font``).
  156. Additionally, it is possible to load any font that is installed on the system using
  157. Godot's support for :ref:`doc_using_fonts_system_fonts`.
  158. Example of loading a font file automatically according to its file extension,
  159. then adding it as a theme override to a :ref:`class_Label` node:
  160. ::
  161. var path = "/path/to/font.ttf"
  162. var path_lower = path.to_lower()
  163. var font_file = FontFile.new()
  164. if (
  165. path_lower.ends_with(".ttf")
  166. or path_lower.ends_with(".otf")
  167. or path_lower.ends_with(".woff")
  168. or path_lower.ends_with(".woff2")
  169. or path_lower.ends_with(".pfb")
  170. or path_lower.ends_with(".pfm")
  171. ):
  172. font_file.load_dynamic_font(path)
  173. elif path_lower.ends_with(".fnt") or path_lower.ends_with(".font"):
  174. font_file.load_bitmap_font(path)
  175. else:
  176. push_error("Invalid font file format.")
  177. if not font_file.data.is_empty():
  178. # If font was loaded successfully, add it as a theme override.
  179. $Label.add_theme_font_override("font", font_file)
  180. ZIP archives
  181. ------------
  182. Godot supports reading and writing ZIP archives using the :ref:`class_zipreader`
  183. and :ref:`class_zippacker` classes. This supports any ZIP file, including files
  184. generated by Godot's "Export PCK/ZIP" functionality (although these will contain
  185. imported Godot resources rather than the original project files).
  186. .. note::
  187. Use :ref:`ProjectSettings.load_resource_pack <class_ProjectSettings_method_load_resource_pack>`
  188. to load PCK or ZIP files exported by Godot as
  189. :ref:`additional data packs <doc_exporting_pcks>`. That approach is preferred
  190. for DLCs, as it makes interacting with additional data packs seamless (virtual filesystem).
  191. This ZIP archive support can be combined with runtime image, 3D scene and audio
  192. loading to provide a seamless modding experience without requiring users to go
  193. through the Godot editor to generate PCK/ZIP files.
  194. Example that lists files in a ZIP archive in an :ref:`class_ItemList` node,
  195. then writes contents read from it to a new ZIP archive (essentially duplicating the archive):
  196. ::
  197. # Load an existing ZIP archive.
  198. var zip_reader = ZIPReader.new()
  199. zip_reader.open(path)
  200. var files = zip_reader.get_files()
  201. # The list of files isn't sorted by default. Sort it for more consistent processing.
  202. files.sort()
  203. for file in files:
  204. $ItemList.add_item(file, null)
  205. # Make folders disabled in the list.
  206. $ItemList.set_item_disabled(-1, file.ends_with("/"))
  207. # Save a new ZIP archive.
  208. var zip_packer = ZIPPacker.new()
  209. var error = zip_packer.open(path)
  210. if error != OK:
  211. push_error("Couldn't open path for saving ZIP archive (error code: %s)." % error_string(error))
  212. return
  213. # Reuse the above ZIPReader instance to read files from an existing ZIP archive.
  214. for file in zip_reader.get_files():
  215. zip_packer.start_file(file)
  216. zip_packer.write_file(zip_reader.read_file(file))
  217. zip_packer.close_file()
  218. zip_packer.close()