save_and_load.adoc 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. = Saving and Loading Games (.j3o)
  2. :revnumber: 2.0
  3. :revdate: 2020/07/15
  4. :keywords: convert, j3o, models, load, save, documentation, serialization, import, export, spatial, node, mesh, geometry, scenegraph, sdk
  5. Spatials (that is Nodes and Geometries) can contain audio and light nodes, particle emitters, controls, and user data (player score, health, inventory, etc). For your game distribution, you must convert all original models to a faster binary format. You save individual Spatials as well as scenes using `com.jme3.export.binary.BinaryExporter`.
  6. The jMonkeyEngine's binary file format is called `.j3o`. You can convert, view and edit .j3o files and their materials in the jMonkeyEngine xref:sdk:sdk.adoc[SDK] and compose scenes (this does not include editing meshes). For the conversion, you can either use the BinaryExporters, or a context menu in the SDK.
  7. [IMPORTANT]
  8. ====
  9. The jMonkeyEngine's serialization system is the `com.jme3.export.Savable` interface. JME3's BinaryExporter can write standard Java objects, JME3 objects, and primitive data types that are included in a xref:jme3/advanced/spatial.adoc[spatial's user data]. If you use custom game data classes, see below how to make them “Savable.
  10. ====
  11. There is also a com.jme3.export.xml.XMLExporter and com.jme3.export.xml.XMLImporter that similarly converts jme3 spatials to an XML format. But you wouldn't use that to load models at runtime (quite slow).
  12. == Sample Code
  13. * link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-examples/src/main/java/jme3test/tools/TestSaveGame.java[TestSaveGame.java]
  14. == Saving a Node
  15. The following example overrides `stop()` in SimpleApplication to save the rootNode to a file when the user quits the application. The saved rootNode is a normal .j3o binary file that you can open in the xref:sdk:sdk.adoc[SDK].
  16. [WARNING]
  17. ====
  18. Note that when you save a model that has textures, the references to those textures are stored as absolute paths, so when loading the j3o file again, the textures have to be accessible at the exact location (relative to the assetmanager root, by default the `assets` directory) they were loaded from. This is why the SDK manages the conversion on the project level.
  19. ====
  20. [source,java]
  21. ----
  22. /* This is called when the user quits the app. */
  23. @Override
  24. public void stop() {
  25. String userHome = System.getProperty("user.home");
  26. BinaryExporter exporter = BinaryExporter.getInstance();
  27. File file = new File(userHome+"/Models/"+"MyModel.j3o");
  28. try {
  29. exporter.save(rootNode, file);
  30. } catch (IOException ex) {
  31. Logger.getLogger(Main.class.getName()).log(Level.SEVERE, "Error: Failed to save game!", ex);
  32. }
  33. super.stop(); // continue quitting the game
  34. }
  35. ----
  36. == Loading a Node
  37. The following example overrides `simpleInitApp()` in SimpleApplication to load `Models/MyModel.j3o` when the game is initialized.
  38. [source,java]
  39. ----
  40. @Override
  41. public void simpleInitApp() {
  42. String userHome = System.getProperty("user.home");
  43. assetManager.registerLocator(userHome, FileLocator.class);
  44. Node loadedNode = (Node)assetManager.loadModel("Models/MyModel.j3o");
  45. loadedNode.setName("loaded node");
  46. rootNode.attachChild(loadedNode);
  47. }
  48. ----
  49. [TIP]
  50. ====
  51. Here you see why we save user data inside spatials – so it can be saved and loaded together with the .j3o file. If you have game data outside Spatials, you have to remember to save() and load(), and get() and set() it yourself.
  52. ====
  53. == Custom Savable Class
  54. JME's BinaryExporter can write standard Java objects (String, ArrayList, buffers, etc), JME objects (Savables, such as Material), and primitive data types (int, float, etc). If you are using any custom class together with a Spatial, then the custom class must implement the `com.jme3.export.Savable` interface. There are two common cases where this is relevant:
  55. * The Spatial is carrying any xref:jme3/advanced/custom_controls.adoc[Custom Controls]. +
  56. Example: You used something like `mySpatial.addControl(myControl);`
  57. * The Spatial's user data can contain a custom Java object. +
  58. Example: You used something like `mySpatial.setUserData("inventory", myInventory);`
  59. If your custom classes (the user data or the Controls) do not implement Savable, then the BinaryImporter/BinaryExporter cannot save the Spatial!
  60. So every time you create a custom Control or custom user data class, remember to implement Savable:
  61. [source,java]
  62. ----
  63. import com.jme3.export.InputCapsule;
  64. import com.jme3.export.JmeExporter;
  65. import com.jme3.export.JmeImporter;
  66. import com.jme3.export.OutputCapsule;
  67. import com.jme3.export.Savable;
  68. import com.jme3.material.Material;
  69. import java.io.IOException;
  70. public class MyCustomClass implements Savable {
  71. private int someIntValue; // some custom user data
  72. private float someFloatValue; // some custom user data
  73. private Material someJmeObject; // some custom user data
  74. ...
  75. // your other code...
  76. ...
  77. public void write(JmeExporter ex) throws IOException {
  78. OutputCapsule capsule = ex.getCapsule(this);
  79. capsule.write(someIntValue, "someIntValue", 1);
  80. capsule.write(someFloatValue, "someFloatValue", 0f);
  81. capsule.write(someJmeObject, "someJmeObject", new Material());
  82. }
  83. public void read(JmeImporter im) throws IOException {
  84. InputCapsule capsule = im.getCapsule(this);
  85. someIntValue = capsule.readInt( "someIntValue", 1);
  86. someFloatValue = capsule.readFloat( "someFloatValue", 0f);
  87. someJmeObject = capsule.readSavable("someJmeObject", new Material());
  88. }
  89. }
  90. ----
  91. To make a custom class savable:
  92. . Implement `Savable` and add the `write()` and `read()` methods as shown in the example above.
  93. . Do the following for each non-temporary class field:
  94. ** Add one line that ``write()``s the data to the JmeExport output capsule.
  95. *** Specify the variable to save, give it a String name (can be the same as the variable name), and specify a default value.
  96. ** Add one line that ``read…()``s the data to the JmeImport input capsule.
  97. *** On the left side of the assignment, specify the class field that you are restoring
  98. *** On the right side, use the appropriate `capsule.read…()` method for the data type. Specify the String name of the variable (must be the same as you used in the `write()` method), and again specify a default value.
  99. [IMPORTANT]
  100. ====
  101. As with all serialization, remember that if you ever change data types in custom classes, the updated read() methods will no longer be able to read your old files. Also there has to be a constructor that takes no Parameters.
  102. ====
  103. == Default Value
  104. The default value plays an important role in what data is saved to file.
  105. .write()
  106. [source, java]
  107. ----
  108. public void write(int value, String name, int defVal) throws IOException {
  109. if (value == defVal)
  110. return;
  111. writeAlias(name, BinaryClassField.INT);
  112. write(value);
  113. }
  114. ----
  115. The write methods of the link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/445f7ed010199d30c484fe75bacef4b87f2eb38e/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryOutputCapsule.java[BinaryOutputCapsule.java ] class do not write the `defVal` to file. Instead, they check to see if `value` is equal to `defVal`, and if so, will not write anything at all.
  116. There are very good reasons to do this.
  117. . It takes less space if everything is a default value.
  118. . You may decide on new defaults later and your objects will automatically upgrade if they didn’t have specifically overridden values.
  119. .read()
  120. [source, java]
  121. ----
  122. public int readInt(String name, int defVal) throws IOException {
  123. BinaryClassField field = cObj.nameFields.get(name);
  124. if (field == null || !fieldData.containsKey(field.alias))
  125. return defVal;
  126. return ((Integer) fieldData.get(field.alias)).intValue();
  127. }
  128. ----
  129. When reading your saved file, the link:https://github.com/jMonkeyEngine/jmonkeyengine/blob/445f7ed010199d30c484fe75bacef4b87f2eb38e/jme3-core/src/plugins/java/com/jme3/export/binary/BinaryInputCapsule.java[BinaryInputCapsule.java] class will see that the `name` field is `null` and this is when the defVal is set.
  130. [NOTE]
  131. ====
  132. If you rely on the compiler to initialize class or instance variables for you, this can lead too unintended consequences.
  133. For example:
  134. [source, java]
  135. ----
  136. capsule.write(someIntValue, "someIntValue", 1);
  137. ----
  138. If you let the compiler initialize `someIntValue`, it will initialize to zero and if it's not changed after initialization, zero will be written to file.
  139. [source, java]
  140. ----
  141. someIntValue = capsule.readInt( "someIntValue", 1);
  142. ----
  143. Now when `read` is called, it will see the "`someIntValue`" name and set the `someIntValue` variable to zero. Not one, as you were expecting. Keep this in mind when using Savable.
  144. ====