Skip to content

Commit

Permalink
ref[GdScript]: GdScript protocol
Browse files Browse the repository at this point in the history
  • Loading branch information
jaysunxiao committed Jul 16, 2024
1 parent b1cbc73 commit 6fbebb9
Show file tree
Hide file tree
Showing 9 changed files with 120 additions and 108 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public static String formatTemplate(String template, Map<CodeTemplatePlaceholder
if (formatLine.contains(codeTemplatePlaceholder.placeholder)) {
var placeholder = placeholderMap.get(codeTemplatePlaceholder);
if (placeholder == null) {
throw new RunException("placeholder:[{}] not exist, and add [{}] to your placeholderMap", placeholder, placeholder);
throw new RunException("placeholder:[{}] not exist, and add [{}] to your placeholderMap", codeTemplatePlaceholder, codeTemplatePlaceholder);
}
formatLine = formatLine.replace(codeTemplatePlaceholder.placeholder, placeholder);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,10 @@ public void mergerProtocol(List<ProtocolRegistration> registrations) throws IOEx
for (var registration : registrations) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
protocol_manager_registrations.append(StringUtils.format("{}: Protocols.{},", protocol_id, protocol_name)).append(LS);

protocol_manager_registrations.append(StringUtils.format("protocols[{}] = Protocols.{}Registration.new()", protocol_id, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolClassMap[{}] = Protocols.{}", protocol_id, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolIdMap[Protocols.{}] = {}", protocol_name, protocol_id)).append(LS);
}
var placeholderMap = Map.of(CodeTemplatePlaceholder.protocol_imports, protocol_imports.toString()
, CodeTemplatePlaceholder.protocol_manager_registrations, StringUtils.substringBeforeLast(protocol_manager_registrations.toString(), StringUtils.COMMA));
Expand All @@ -103,28 +106,19 @@ public void mergerProtocol(List<ProtocolRegistration> registrations) throws IOEx
logger.info("Generated GdScript protocol manager file:[{}] is in path:[{}]", protocolManagerFile.getName(), protocolManagerFile.getAbsolutePath());


var protocol_imports_protocols = new StringBuilder();
protocol_imports = new StringBuilder();
var protocol_class = new StringBuilder();
var protocol_registration = new StringBuilder();
protocol_imports.append(StringUtils.format("const ByteBuffer = preload(\"res://{}/ByteBuffer.gd\")", protocolOutputRootPath)).append(LS);
for (var registration : registrations) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
var protocolTemplate = ClassUtils.getFileFromClassPathToString("gdscript/ProtocolClassTemplate.gd");
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_id, String.valueOf(protocol_id)
, CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_note, GenerateProtocolNote.protocol_note(protocol_id, CodeLanguage.GdScript)
, CodeTemplatePlaceholder.protocol_field_definition, protocol_field_definition(registration)
, CodeTemplatePlaceholder.protocol_write_serialization, protocol_write_serialization(registration)
, CodeTemplatePlaceholder.protocol_read_deserialization, protocol_read_deserialization(registration)
, CodeTemplatePlaceholder.protocol_json, protocol_json(registration)
, CodeTemplatePlaceholder.protocol_to_string, protocol_to_string(registration)
));
protocol_class.append(formatProtocolTemplate).append(LS);
protocol_class.append(protocol_class(registration)).append(LS);
protocol_registration.append(protocol_registration(registration)).append(LS);
}
var protocolTemplate = ClassUtils.getFileFromClassPathToString("gdscript/ProtocolsTemplate.gd");
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_imports, protocol_imports_protocols.toString()
CodeTemplatePlaceholder.protocol_imports, protocol_imports.toString()
, CodeTemplatePlaceholder.protocol_class, protocol_class.toString()
, CodeTemplatePlaceholder.protocol_registration, protocol_registration.toString()
));
var outputPath = StringUtils.format("{}/Protocols.gd", protocolOutputPath);
var file = new File(outputPath);
Expand All @@ -145,7 +139,9 @@ public void foldProtocol(List<ProtocolRegistration> registrations) throws IOExce
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
protocol_imports.append(StringUtils.format("const {} = preload(\"res://{}/{}/{}.gd\")", protocol_name, protocolOutputRootPath, GenerateProtocolPath.protocolPathSlash(protocol_id), protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("{}: {},", protocol_id, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocols[{}] = {}.{}Registration.new()", protocol_id, protocol_name, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolClassMap[{}] = {}.{}", protocol_id, protocol_name, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolIdMap[{}.{}] = {}", protocol_name, protocol_name, protocol_id)).append(LS);
}
var placeholderMap = Map.of(CodeTemplatePlaceholder.protocol_imports, protocol_imports.toString()
, CodeTemplatePlaceholder.protocol_manager_registrations, StringUtils.substringBeforeLast(protocol_manager_registrations.toString(), StringUtils.COMMA));
Expand All @@ -162,13 +158,9 @@ public void foldProtocol(List<ProtocolRegistration> registrations) throws IOExce
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_id, String.valueOf(protocol_id)
, CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_note, GenerateProtocolNote.protocol_note(protocol_id, CodeLanguage.GdScript)
, CodeTemplatePlaceholder.protocol_imports, protocol_imports_fold(registration)
, CodeTemplatePlaceholder.protocol_field_definition, protocol_field_definition(registration)
, CodeTemplatePlaceholder.protocol_write_serialization, protocol_write_serialization(registration)
, CodeTemplatePlaceholder.protocol_read_deserialization, protocol_read_deserialization(registration)
, CodeTemplatePlaceholder.protocol_json, protocol_json(registration)
, CodeTemplatePlaceholder.protocol_to_string, protocol_to_string(registration)
, CodeTemplatePlaceholder.protocol_class, protocol_class(registration)
, CodeTemplatePlaceholder.protocol_registration, protocol_registration(registration)
));
var outputPath = StringUtils.format("{}/{}/{}.gd", protocolOutputPath, GenerateProtocolPath.protocolPathSlash(protocol_id), protocol_name);
var file = new File(outputPath);
Expand All @@ -186,11 +178,14 @@ public void defaultProtocol(List<ProtocolRegistration> registrations) throws IOE
var protocolManagerTemplate = ClassUtils.getFileFromClassPathToString("gdscript/ProtocolManagerTemplate.gd");
var protocol_imports = new StringBuilder();
var protocol_manager_registrations = new StringBuilder();
protocol_imports.append(StringUtils.format("const ByteBuffer = preload(\"res://{}/ByteBuffer.gd\")", protocolOutputRootPath)).append(LS);
for (var registration : registrations) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
protocol_imports.append(StringUtils.format("const {} = preload(\"res://{}/{}.gd\")", protocol_name, protocolOutputRootPath, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("{}: {},", protocol_id, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocols[{}] = {}.{}Registration.new()", protocol_id, protocol_name, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolClassMap[{}] = {}.{}", protocol_id, protocol_name, protocol_name)).append(LS);
protocol_manager_registrations.append(StringUtils.format("protocolIdMap[{}.{}] = {}", protocol_name, protocol_name, protocol_id)).append(LS);
}
var placeholderMap = Map.of(CodeTemplatePlaceholder.protocol_imports, protocol_imports.toString()
, CodeTemplatePlaceholder.protocol_manager_registrations, StringUtils.substringBeforeLast(protocol_manager_registrations.toString(), StringUtils.COMMA));
Expand All @@ -207,13 +202,9 @@ public void defaultProtocol(List<ProtocolRegistration> registrations) throws IOE
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_id, String.valueOf(protocol_id)
, CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_note, GenerateProtocolNote.protocol_note(protocol_id, CodeLanguage.GdScript)
, CodeTemplatePlaceholder.protocol_imports, protocol_imports_default(registration)
, CodeTemplatePlaceholder.protocol_field_definition, protocol_field_definition(registration)
, CodeTemplatePlaceholder.protocol_write_serialization, protocol_write_serialization(registration)
, CodeTemplatePlaceholder.protocol_read_deserialization, protocol_read_deserialization(registration)
, CodeTemplatePlaceholder.protocol_json, protocol_json(registration)
, CodeTemplatePlaceholder.protocol_to_string, protocol_to_string(registration)
, CodeTemplatePlaceholder.protocol_class, protocol_class(registration)
, CodeTemplatePlaceholder.protocol_registration, protocol_registration(registration)
));
var outputPath = StringUtils.format("{}/{}.gd", protocolOutputPath, protocol_name);
var file = new File(outputPath);
Expand All @@ -222,20 +213,49 @@ public void defaultProtocol(List<ProtocolRegistration> registrations) throws IOE
}
}

private void createTemplateFile() throws IOException {
private void createTemplateFile() {
var byteBufferFile = new File(StringUtils.format("{}/{}", protocolOutputPath, "ByteBuffer.gd"));
var byteBufferTemplate = ClassUtils.getFileFromClassPathToString("gdscript/buffer/ByteBuffer.gd");
var byteBufferTemplate = ClassUtils.getFileFromClassPathToString("gdscript/ByteBuffer.gd");
FileUtils.writeStringToFile(byteBufferFile, StringUtils.format(byteBufferTemplate, protocolOutputRootPath), false);
}

private String protocol_class(ProtocolRegistration registration) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
var protocolTemplate = ClassUtils.getFileFromClassPathToString("gdscript/ProtocolClassTemplate.gd");
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_note, GenerateProtocolNote.protocol_note(protocol_id, CodeLanguage.GdScript)
, CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_id, String.valueOf(protocol_id)
, CodeTemplatePlaceholder.protocol_field_definition, protocol_field_definition(registration)
, CodeTemplatePlaceholder.protocol_json, protocol_json(registration)
, CodeTemplatePlaceholder.protocol_to_string, protocol_to_string(registration)
));
return formatProtocolTemplate;
}

private String protocol_registration(ProtocolRegistration registration) {
var protocol_id = registration.protocolId();
var protocol_name = registration.protocolConstructor().getDeclaringClass().getSimpleName();
var protocolTemplate = ClassUtils.getFileFromClassPathToString("gdscript/ProtocolRegistrationTemplate.gd");
var formatProtocolTemplate = CodeTemplatePlaceholder.formatTemplate(protocolTemplate, Map.of(
CodeTemplatePlaceholder.protocol_name, protocol_name
, CodeTemplatePlaceholder.protocol_id, String.valueOf(protocol_id)
, CodeTemplatePlaceholder.protocol_write_serialization, protocol_write_serialization(registration)
, CodeTemplatePlaceholder.protocol_read_deserialization, protocol_read_deserialization(registration)
));
return formatProtocolTemplate;
}

private String protocol_imports_fold(ProtocolRegistration registration) {
var protocolId = registration.getId();
var subProtocols = ProtocolAnalysis.getAllSubProtocolIds(protocolId);
var importBuilder = new StringBuilder();
importBuilder.append(StringUtils.format("const ByteBuffer = preload(\"res://{}/ByteBuffer.gd\")", protocolOutputRootPath)).append(LS);
for (var subProtocolId : subProtocols) {
var name = EnhanceObjectProtocolSerializer.getProtocolClassSimpleName(subProtocolId);
importBuilder.append(StringUtils.format("const {} = preload(\"res://{}/{}/{}.gd\")", name, protocolOutputRootPath, GenerateProtocolPath.protocolPathSlash(protocolId), name)).append(LS);
var protocolName = EnhanceObjectProtocolSerializer.getProtocolClassSimpleName(subProtocolId);
importBuilder.append(StringUtils.format("const {} = preload(\"res://{}/{}/{}.gd\").{}"
, protocolName, protocolOutputRootPath, GenerateProtocolPath.protocolPathSlash(protocolId), protocolName, protocolName)).append(LS);
}
return importBuilder.toString();
}
Expand All @@ -244,9 +264,10 @@ private String protocol_imports_default(ProtocolRegistration registration) {
var protocolId = registration.getId();
var subProtocols = ProtocolAnalysis.getAllSubProtocolIds(protocolId);
var importBuilder = new StringBuilder();
importBuilder.append(StringUtils.format("const ByteBuffer = preload(\"res://{}/ByteBuffer.gd\")", protocolOutputRootPath)).append(LS);
for (var subProtocolId : subProtocols) {
var protocolName = EnhanceObjectProtocolSerializer.getProtocolClassSimpleName(subProtocolId);
importBuilder.append(StringUtils.format("const {} = preload(\"res://{}/{}.gd\")", protocolName, protocolOutputRootPath, protocolName)).append(LS);
importBuilder.append(StringUtils.format("const {} = preload(\"res://{}/{}.gd\").{}", protocolName, protocolOutputRootPath, protocolName, protocolName)).append(LS);
}
return importBuilder.toString();
}
Expand Down Expand Up @@ -356,7 +377,7 @@ private String protocol_read_deserialization(ProtocolRegistration registration)
if (field.isAnnotationPresent(Compatible.class)) {
gdBuilder.append("if buffer.compatibleRead(beforeReadIndex, length):").append(LS);
var compatibleReadObject = gdSerializer(fieldRegistration.serializer()).readObject(gdBuilder, 1, field, fieldRegistration);
gdBuilder.append(TAB_ASCII).append(StringUtils.format("packet.{} = {};", field.getName(), compatibleReadObject)).append(LS);
gdBuilder.append(TAB_ASCII).append(StringUtils.format("packet.{} = {}", field.getName(), compatibleReadObject)).append(LS);
continue;
}
var readObject = gdSerializer(fieldRegistration.serializer()).readObject(gdBuilder, 0, field, fieldRegistration);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const ProtocolManager = preload("res://{}/ProtocolManager.gd")
const ProtocolManager = preload("res://zfoogd/ProtocolManager.gd")

const EMPTY: String = ""

Expand Down Expand Up @@ -39,9 +39,12 @@ func compatibleRead(beforeReadIndex: int, length: int) -> bool:
return length != -1 && getReadOffset() < length + beforeReadIndex

# -------------------------------------------------get/set-------------------------------------------------
func getBuffer() -> StreamPeerBuffer:
return buffer

func setWriteOffset(writeIndex: int) -> void:
if (writeIndex > buffer.get_size()):
var template = "writeIndex[{}] out of bounds exception: readerIndex: {}, writerIndex: {} (expected: 0 <= readerIndex <= writerIndex <= capacity: {})"
var template = "writeIndex[{}] out of bounds exception: readOffset: {}, writeOffset: {} (expected: 0 <= readOffset <= writeOffset <= capacity: {})"
printerr(template.format([writeIndex, readOffset, writeOffset, buffer.get_size()], "{}"))
return
writeOffset = writeIndex
Expand All @@ -52,7 +55,7 @@ func getWriteOffset() -> int:

func setReadOffset(readIndex: int) -> void:
if (readIndex > writeOffset):
var template = "readIndex[{}] out of bounds exception: readerIndex: {}, writerIndex: {} (expected: 0 <= readerIndex <= writerIndex <= capacity: {})"
var template = "readIndex[{}] out of bounds exception: readOffset: {}, writeOffset: {} (expected: 0 <= readOffset <= writeOffset <= capacity: {})"
printerr(template.format([readIndex, readOffset, writeOffset, buffer.size()], "{}"))
return
readOffset = readIndex
Expand All @@ -64,15 +67,18 @@ func getReadOffset() -> int:
func isReadable() -> bool:
return writeOffset > readOffset

func toBytes() -> PackedByteArray:
return buffer.data_array.slice(0, writeOffset)

# -------------------------------------------------write/read-------------------------------------------------
func writePackedByteArray(value: PackedByteArray):
func writeBytes(value: PackedByteArray):
var length: int = value.size()
buffer.put_partial_data(value)
writeOffset += length
pass

func toPackedByteArray() -> PackedByteArray:
return buffer.data_array.slice(0, writeOffset)
func readBytes(length: int) -> PackedByteArray:
return buffer.data_array.slice(0, length)

func writeBool(value: bool) -> void:
var byte: int = 1 if value else 0
Expand Down Expand Up @@ -303,10 +309,7 @@ func readPacket(protocolId):
var protocolRegistration = ProtocolManager.getProtocol(protocolId)
return protocolRegistration.read(self)

func newInstance(protocolId: int):
return ProtocolManager.newInstance(protocolId)

func writeBooleanArray(array):
func writeBoolArray(array):
if (array == null):
writeInt(0)
else:
Expand All @@ -315,7 +318,7 @@ func writeBooleanArray(array):
writeBool(element)
pass

func readBooleanArray() -> Array[bool]:
func readBoolArray() -> Array[bool]:
var array: Array[bool] = []
var size = readInt()
if (size > 0):
Expand Down Expand Up @@ -454,7 +457,8 @@ func writePacketArray(array, protocolId):

func readPacketArray(protocolId):
var protocolRegistration = ProtocolManager.getProtocol(protocolId)
var array = Array([], typeof(protocolRegistration), StringName("RefCounted"), protocolRegistration)
var protocol = ProtocolManager.getProtocolClass(protocolId)
var array = Array([], typeof(protocol), StringName("RefCounted"), protocol)
var size = readInt()
if (size > 0):
for index in range(size):
Expand Down
Loading

0 comments on commit 6fbebb9

Please sign in to comment.