EntityIdMapper.gd 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. @tool
  2. class_name EntityIDMapper
  3. extends Node
  4. @export_tool_button("Update ID's") var button = update_map
  5. @export var auto_update := true
  6. static var map := {}
  7. const MAP_PATH := "res://EntityIDMap.json"
  8. const base64_charset := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
  9. var selectors_to_add := []
  10. func _ready() -> void:
  11. map = JSON.parse_string(FileAccess.open(MAP_PATH, FileAccess.READ).get_as_text())
  12. if Engine.is_editor_hint() == false and OS.is_debug_build() and auto_update:
  13. update_map()
  14. func update_map() -> void:
  15. map = JSON.parse_string(FileAccess.open(MAP_PATH, FileAccess.READ).get_as_text())
  16. get_ids()
  17. save_to_json()
  18. print("done")
  19. func clear_map() -> void:
  20. map = {}
  21. save_to_json()
  22. func get_ids() -> void:
  23. var id := 0
  24. for i: EditorTileSelector in get_tree().get_nodes_in_group("Selectors"):
  25. if i.type != 1 or i.entity_scene == null:
  26. continue
  27. var selector_id := encode_to_base64_2char(id)
  28. var value = get_selector_info_arr(i)
  29. id += 1
  30. if map.has(selector_id):
  31. if map.values().find(value) != -1:
  32. continue
  33. else:
  34. selector_id = encode_to_base64_2char(map.size())
  35. map.set(selector_id, get_selector_info_arr(i))
  36. static func get_selector_info_arr(selector: EditorTileSelector) -> Array:
  37. return [selector.entity_scene.resource_path, str(selector.tile_offset.x) + "," + str(selector.tile_offset.y)]
  38. func save_to_json() -> void:
  39. var file = FileAccess.open(MAP_PATH, FileAccess.WRITE)
  40. file.store_string(JSON.stringify(map, "\t", false))
  41. file.close()
  42. static func get_map_id(entity_scene := "") -> String:
  43. var idx := 0
  44. for i in map.values():
  45. if i[0] == entity_scene:
  46. return map.keys()[idx]
  47. idx += 1
  48. return ""
  49. func encode_to_base64_2char(value: int) -> String:
  50. if value < 0 or value >= 4096:
  51. push_error("Value out of range for 2-char base64 encoding.")
  52. return ""
  53. var char1 = base64_charset[(value >> 6) & 0b111111] # Top 6 bits
  54. var char2 = base64_charset[value & 0b111111] # Bottom 6 bits
  55. return char1 + char2
  56. func decode_from_base64_2char(encoded: String) -> int:
  57. if encoded.length() != 2:
  58. push_error("Encoded string must be exactly 2 characters.")
  59. return -1
  60. var idx1 = base64_charset.find(encoded[0])
  61. var idx2 = base64_charset.find(encoded[1])
  62. if idx1 == -1 or idx2 == -1:
  63. push_error("Invalid character in base64 string.")
  64. return -1
  65. return (idx1 << 6) | idx2