initial RPC renderer (#92)

Reviewed-on: https://codeberg.org/StreamGraph/StreamGraph/pulls/92
Co-authored-by: Lera Elvoé <yagich@poto.cafe>
Co-committed-by: Lera Elvoé <yagich@poto.cafe>
This commit is contained in:
Lera Elvoé 2024-03-05 07:09:36 +00:00 committed by yagich
parent 6d3cc87fad
commit 715086f204
66 changed files with 2112 additions and 5 deletions

View file

@ -118,3 +118,215 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## WebSocket Server
Upstream: [GitHub](https://github.com/godotengine/godot-demo-projects/tree/master/networking/websocket_chat)
License: MIT
File(s): `rpc_renderer/web_socket_server.gd`
### License text
```
Copyright (c) 2014-present Godot Engine contributors.
Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```
## Zodot
Upstream: [GitHub](https://github.com/rametta/zodot)
License: Apache-2.0
File(s): `addons/zodot/*`
### License text
```
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2023 Jason Rametta
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```

7
addons/zodot/plugin.cfg Normal file
View file

@ -0,0 +1,7 @@
[plugin]
name="Zodot"
description="Lightweight Data Validation"
author="Jason Rametta"
version="1.0"
script="zodot.gd"

View file

@ -0,0 +1,16 @@
class_name z_aabb extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_AABB
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,35 @@
class_name z_array extends Zodot
var _schema: Zodot
var _non_empty = false
func _init(schema = null):
_schema = schema
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_ARRAY
func non_empty() -> z_array:
_non_empty = true
return self
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
if _non_empty and value.is_empty():
return ZodotResult.constraint_error(field, "Array must not be empty")
if _schema != null:
for i in range(value.size()):
var result = _schema.parse(value[i], field + "[{i}]".format({ "i": i }))
if not result.ok():
return result
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_basis extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_BASIS
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,33 @@
class_name z_boolean extends Zodot
enum Kind {
ONLY_TRUE,
ONLY_FALSE,
BOTH
}
var _kind = Kind.BOTH
func _init(kind: Kind) -> void:
_kind = kind
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_BOOL
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
if _kind == Kind.ONLY_TRUE and value != true:
return ZodotResult.constraint_error(field, "Value must be only be true")
if _kind == Kind.ONLY_FALSE and value != false:
return ZodotResult.constraint_error(field, "Value must be only be false")
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_callable extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_CALLABLE
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_color extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_COLOR
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,35 @@
class_name z_dictionary extends Zodot
var _schema: Zodot
var _non_empty = false
func _init(schema = null):
_schema = schema
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_DICTIONARY
func non_empty() -> z_dictionary:
_non_empty = true
return self
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
if _non_empty and value.is_empty():
return ZodotResult.constraint_error(field, "Dictionary must not be empty")
if _schema != null:
for key in value:
var result = _schema.parse(value[key], field + "[{key}]".format({ "key": key }))
if not result.ok():
return result
return ZodotResult.good(value)

View file

@ -0,0 +1,31 @@
class_name z_enum extends Zodot
static func get_enum_value(key, e):
var value = null
if typeof(key) == TYPE_STRING:
var converted = key.to_upper().replace(' ', '_')
if e.keys().has(converted):
value = e[converted]
else:
if e.values().has(key):
value = key
return value
var _enum
func _init(enum_type: Variant):
_enum = enum_type
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if get_enum_value(value, _enum) == null:
return ZodotResult.constraint_error(field, "Value is not valid enum member")
return ZodotResult.good(value)

View file

@ -0,0 +1,33 @@
class_name z_float extends Zodot
var _max
var _min
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_FLOAT
func minimum(m: float) -> z_float:
_min = m
return self
func maximum(m: float) -> z_float:
_max = m
return self
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
if _min != null and value < _min:
return ZodotResult.constraint_error(field, "Value {value} smaller than min {min}".format({ "value": value, "min": _min }))
if _max != null and value > _max:
return ZodotResult.constraint_error(field, "Value {value} larger than max {max}".format({ "value": value, "max": _max }))
return ZodotResult.good(value)

View file

@ -0,0 +1,33 @@
class_name z_integer extends Zodot
var _max
var _min
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_INT
func minimum(m: int) -> z_integer:
_min = m
return self
func maximum(m: int) -> z_integer:
_max = m
return self
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
if _min != null and value < _min:
return ZodotResult.constraint_error(field, "Value {value} smaller than min {min}".format({ "value": value, "min": _min }))
if _max != null and value > _max:
return ZodotResult.constraint_error(field, "Value {value} larger than max {max}".format({ "value": value, "max": _max }))
return ZodotResult.good(value)

View file

@ -0,0 +1,21 @@
class_name z_literal extends Zodot
var _value: Variant
func _init(value: Variant):
_value = value
func _valid_type(value: Variant) -> bool:
return true
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if value == _value:
return ZodotResult.good(value)
return ZodotResult.constraint_error(field, "Value is not equal to literal")

View file

@ -0,0 +1,16 @@
class_name z_max extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_MAX
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_nil extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_NIL
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_node_path extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_NODE_PATH
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_object extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_OBJECT
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_byte_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_BYTE_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_color_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_COLOR_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_float32_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_FLOAT32_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_float64_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_FLOAT64_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_int32_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_INT32_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_int64_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_INT64_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_string_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_STRING_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_vector2_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_VECTOR2_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_packed_vector3_array extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PACKED_VECTOR3_ARRAY
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_plane extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PLANE
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_projection extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_PROJECTION
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_quaternion extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_QUATERNION
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_rect2 extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_RECT2
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_rect2i extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_RECT2I
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_rid extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_RID
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,38 @@
class_name z_schema extends Zodot
var _schema: Dictionary
# schema: Dictionary<string, Zodot>
func _init(schema: Dictionary):
_schema = schema
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _nullable and value == null:
return ZodotResult.constraint_error(field, "Missing dictionary")
for _field in _schema:
var field_name = _field
if field:
field_name = "{field1}.{field2}".format({ "field1": field, "field2": _field })
var field_validator: Zodot = _schema[_field]
if not field_validator._nullable and not value.has(_field):
return ZodotResult.constraint_error(field_name, "Dictionary missing key")
if not value.has(_field) and field_validator._nullable:
continue
var result: ZodotResult = field_validator.parse(value[_field], field_name)
if not result.ok():
return result
value[_field] = result.data
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_signal extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_SIGNAL
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,41 @@
class_name z_string extends Zodot
var _non_empty = false
var _max
var _min
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_STRING
func non_empty() -> z_string:
_non_empty = true
return self
func minimum(m: int) -> z_string:
_min = m
return self
func maximum(m: int) -> z_string:
_max = m
return self
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
if _non_empty and value == "":
return ZodotResult.constraint_error(field, "Value must not be empty")
if _min != null and len(value) < _min:
return ZodotResult.constraint_error(field, "Value {value} length is smaller than min {min}".format({ "value": value, "min": _min }))
if _max != null and len(value) > _max:
return ZodotResult.constraint_error(field, "Value {value} length is larger than max {max}".format({ "value": value, "max": _max }))
return ZodotResult.good(value)

View file

@ -0,0 +1,41 @@
class_name z_string_name extends Zodot
var _non_empty = false
var _max
var _min
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_STRING_NAME
func non_empty() -> z_string_name:
_non_empty = true
return self
func minimum(m: int) -> z_string_name:
_min = m
return self
func maximum(m: int) -> z_string_name:
_max = m
return self
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
if _non_empty and value == "":
return ZodotResult.constraint_error(field, "Value must not be empty")
if _min != null and len(value) < _min:
return ZodotResult.constraint_error(field, "Value {value} length is smaller than min {min}".format({ "value": value, "min": _min }))
if _max != null and len(value) > _max:
return ZodotResult.constraint_error(field, "Value {value} length is larger than max {max}".format({ "value": value, "max": _max }))
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_transform2d extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_TRANSFORM2D
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_transform3d extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_TRANSFORM3D
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,17 @@
class_name z_union extends Zodot
var _schemas: Array[Zodot] = []
func _init(schemas: Array[Zodot]):
_schemas = schemas
func parse(value: Variant, field: String = "") -> ZodotResult:
if _nullable and value == null:
return ZodotResult.good(value)
for schema in _schemas:
var result = schema.parse(value)
if result.ok():
return result
return ZodotResult.constraint_error(field, "Value does not satisfy any schemas in union")

View file

@ -0,0 +1,16 @@
class_name z_vector2 extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_VECTOR2
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_vector2i extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_VECTOR2I
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_vector3 extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_VECTOR3
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_vector3i extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_VECTOR3I
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_vector4 extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_VECTOR4
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

View file

@ -0,0 +1,16 @@
class_name z_vector4i extends Zodot
func _valid_type(value: Variant) -> bool:
return typeof(value) == TYPE_VECTOR4I
func parse(value: Variant, field: String = "") -> ZodotResult:
if _coerce and typeof(value) == TYPE_STRING:
value = str_to_var(value)
if _nullable and value == null:
return ZodotResult.good(value)
if not _valid_type(value):
return ZodotResult.type_error(field)
return ZodotResult.good(value)

20
addons/zodot/zodot.gd Normal file
View file

@ -0,0 +1,20 @@
class_name Zodot
var _coerce = false
var _nullable = false
func _valid_type(_value: Variant) -> bool:
# Implemented in subclass
return false
func parse(_value: Variant, _field: String = "") -> ZodotResult:
# Implemented in subclass
return null
func coerce() -> Zodot:
_coerce = true
return self
func nullable() -> Zodot:
_nullable = true
return self

View file

@ -0,0 +1,33 @@
class_name ZodotResult
enum Result {
Ok, ## Value is valid
TypeError, ## Value does not match desired type
ConstraintError, ## Value does not satisfy constraint
Unknown ## Not parsed yet
}
var value: Result = Result.Unknown
var error: String = ""
var data: Variant
func ok() -> bool:
return value == Result.Ok
static func good(data: Variant) -> ZodotResult:
var result = ZodotResult.new()
result.value = Result.Ok
result.data = data
return result
static func type_error(field: String) -> ZodotResult:
var result = ZodotResult.new()
result.value = Result.TypeError
result.error = "Field '{field}' does not match desired type".format({ "field": field })
return result
static func constraint_error(field: String, detail: String = "") -> ZodotResult:
var result = ZodotResult.new()
result.value = Result.ConstraintError
result.error = "Field '{field}' does not satisfy constraint. {detail}".format({ "field": field, "detail": detail })
return result

View file

@ -0,0 +1,140 @@
class_name Z
## Dictionary objects with specific properties
##
## Usage:
## [codeblock]
## var MySchema = Z.schema({
## "name": Z.string(),
## "age": Z.integer()
## })
## [/codeblock]
static func schema(dict: Dictionary) -> z_schema:
return z_schema.new(dict)
static func union(schemas: Array[Zodot]) -> z_union:
return z_union.new(schemas)
static func zenum(enum_type: Variant) -> z_enum:
return z_enum.new(enum_type)
static func literal(value: Variant) -> z_literal:
return z_literal.new(value)
static func nil() -> z_nil:
return z_nil.new()
static func boolean(kind: z_boolean.Kind = z_boolean.Kind.BOTH) -> z_boolean:
return z_boolean.new(kind)
static func integer() -> z_integer:
return z_integer.new()
static func float() -> z_float:
return z_float.new()
static func string() -> z_string:
return z_string.new()
static func vector2() -> z_vector2:
return z_vector2.new()
static func vector2i() -> z_vector2i:
return z_vector2i.new()
static func rect2() -> z_rect2:
return z_rect2.new()
static func rect2i() -> z_rect2i:
return z_rect2i.new()
static func vector3() -> z_vector3:
return z_vector3.new()
static func vector3i() -> z_vector3i:
return z_vector3i.new()
static func transform2d() -> z_transform2d:
return z_transform2d.new()
static func vector4() -> z_vector4:
return z_vector4.new()
static func vector4i() -> z_vector4i:
return z_vector4i.new()
static func plane() -> z_plane:
return z_plane.new()
static func quaternion() -> z_quaternion:
return z_quaternion.new()
static func aabb() -> z_aabb:
return z_aabb.new()
static func basis() -> z_basis:
return z_basis.new()
static func transform3d() -> z_transform3d:
return z_transform3d.new()
static func projection() -> z_projection:
return z_projection.new()
static func color() -> z_color:
return z_color.new()
static func string_name() -> z_string_name:
return z_string_name.new()
static func node_path() -> z_node_path:
return z_node_path.new()
static func rid() -> z_rid:
return z_rid.new()
static func object() -> z_object:
return z_object.new()
static func callable() -> z_callable:
return z_callable.new()
# name conflict with signal
static func zignal() -> z_signal:
return z_signal.new()
static func dictionary(schema: Zodot = null) -> z_dictionary:
return z_dictionary.new(schema)
static func array(schema: Zodot = null) -> z_array:
return z_array.new(schema)
static func packed_byte_array() -> z_packed_byte_array:
return z_packed_byte_array.new()
static func packed_int32_array() -> z_packed_int32_array:
return z_packed_int32_array.new()
static func packed_int64_array() -> z_packed_int64_array:
return z_packed_int64_array.new()
static func packed_float32_array() -> z_packed_float32_array:
return z_packed_float32_array.new()
static func packed_float64_array() -> z_packed_float64_array:
return z_packed_float64_array.new()
static func packed_string_array() -> z_packed_string_array:
return z_packed_string_array.new()
static func packed_vector2_array() -> z_packed_vector2_array:
return z_packed_vector2_array.new()
static func packed_vector3_array() -> z_packed_vector3_array:
return z_packed_vector3_array.new()
static func packed_color_array() -> z_packed_color_array:
return z_packed_color_array.new()
static func zmax() -> z_max:
return z_max.new()

View file

@ -10,6 +10,7 @@ class_name DeckHolder
static var decks: Dictionary # Dictionary[String -> id, (Deck|Dictionary[String -> instance_id, Deck])]
static var logger := Logger.new()
static var signals := Signals.new()
## Returns a new empty deck and assigns a new random ID to it.
@ -18,6 +19,7 @@ static func add_empty_deck() -> Deck:
var uuid := UUID.v4()
decks[uuid] = deck
deck.id = uuid
signals.deck_added.emit(uuid)
return deck
@ -34,6 +36,7 @@ static func open_deck_from_file(path: String) -> Deck:
static func open_deck_from_dict(data: Dictionary, path := "") -> Deck:
var deck := Deck.from_dict(data, path)
decks[deck.id] = deck
signals.deck_added.emit(deck.id)
return deck
@ -47,6 +50,7 @@ static func add_group_from_dict(data: Dictionary, deck_id: String, instance_id:
instances[instance_id] = group
decks[deck_id] = instances
connect_group_signals(group)
signals.deck_added.emit(deck_id)
return group
@ -63,6 +67,7 @@ static func add_empty_group() -> Deck:
group.instance_id = UUID.v4()
decks[group.id] = {group.instance_id: group}
connect_group_signals(group)
signals.deck_added.emit(group.id)
return group
@ -125,7 +130,7 @@ static func close_deck(deck_id: String) -> Array:
close_all_group_instances(group)
decks.erase(deck_id)
return groups
signals.deck_closed.emit(deck_id)
return []
@ -222,5 +227,9 @@ static func _on_node_moved(node_id: String, new_position: Dictionary, deck: Deck
instance.emit_group_signals = false
instance.get_node(node_id).position = new_position.duplicate()
instance.emit_group_signals = true
#endregion
class Signals:
signal deck_added(deck_id: String)
signal deck_closed(deck_id: String)

View file

@ -0,0 +1,29 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends DeckNode
func _init() -> void:
name = "Test Any Event"
node_type = name.to_snake_case()
add_input_port(
DeckType.Types.STRING,
"Event name",
"field"
)
add_output_port(
DeckType.Types.DICTIONARY,
"Event",
"",
Port.UsageType.TRIGGER,
)
func _event_received(event_name: StringName, data: Dictionary = {}) -> void:
if event_name != await resolve_input_port_value_async(0):
return
send(0, data)

View file

@ -1,6 +1,10 @@
[gd_scene load_steps=2 format=3 uid="uid://clxtes7sdpe65"]
[gd_scene load_steps=3 format=3 uid="uid://clxtes7sdpe65"]
[ext_resource type="Script" path="res://main.gd" id="1_rxyjw"]
[ext_resource type="Script" path="res://rpc_renderer/rpc_renderer.gd" id="2_m1ypq"]
[node name="Main" type="Node"]
script = ExtResource("1_rxyjw")
[node name="RPCRenderer" type="Node" parent="."]
script = ExtResource("2_m1ypq")

40
rpc_renderer/rpc_frame.gd Normal file
View file

@ -0,0 +1,40 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class_name RPCFrame
## An RPC frame.
##
## A frame is the second smallest unit of data transmittable over RPC, after base types.
## The name of this frame. When a frame is converted to JSON,
## this will be the key in an object, or if this is the top level frame,
## it will be an object with only one key, which is the value of this property.
var frame_name: String
## The props (key names) that will be serialized to JSON before sending to remote clients.
var _props: Array[StringName]
## Wraps this frame's contents into a dictionary with one key: the [member frame_name]. See [member _props].
## If any prop in [member _props] is also an [RPCFrame], it will be serialized
## using [method to_inner_dict].
func to_dict() -> Dictionary:
return {frame_name: to_inner_dict()}
## Converts the [i]contents[/i] of this frame to a dictionary.
func to_inner_dict() -> Dictionary:
var res := {}
for prop in _props:
var value = get(prop)
if value is RPCFrame:
res[prop] = value.to_dict()
elif value is Array and not value.is_empty() and value[0] is RPCFrame:
res[prop] = value.map(
func(e: RPCFrame):
return e.to_dict()
)
else:
res[prop] = value
return res

View file

@ -0,0 +1,119 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends Node
class_name RPCRenderer
## A WebSocket API server.
##
## A renderer that exposes a subset of the core API to remote clients using WebSocket.
const SCOPES_DIR := "res://rpc_renderer/scopes/"
@export var default_port := 6907
var _ws: WebSocketServer = WebSocketServer.new()
var scopes: Array[RPCScope]
var request_schema: Zodot
func load_scopes() -> void:
var d := DirAccess.open(SCOPES_DIR)
d.list_dir_begin()
var current := d.get_next()
while current != "":
if !d.current_is_dir():
var scope = load(SCOPES_DIR.path_join(current)).new() as RPCScope
scopes.append(scope)
current = d.get_next()
for scope in scopes:
scope.event.connect(
func(event: RPCEvent):
send_frame(0, event)
)
scope.response.connect(
func(response: RPCRequestResponse):
send_frame(response.peer_id, response)
if response.event_counterpart != null:
send_frame(-response.peer_id, response.event_counterpart)
)
func build_schema() -> void:
var scope_names = scopes.map(
func(scope: RPCScope):
return scope.name
)
var scopes_schema: Array[Zodot]
scopes_schema.assign(scope_names.map(
func(scope_name: String):
return Z.literal(scope_name)
))
request_schema = Z.schema({
"request": Z.schema({
"id": Z.string(),
"scope": Z.union(scopes_schema),
"operation": RPCOperation.schema(),
"keep": Z.dictionary().nullable(),
})
})
func _ready() -> void:
load_scopes()
build_schema()
add_child(_ws)
_ws.client_connected.connect(_on_ws_client_connected)
_ws.client_disconnected.connect(_on_ws_client_disconnected)
_ws.message_received.connect(_on_ws_message)
listen()
func listen(port := default_port) -> void:
if _ws.listen(port) != OK:
pass
func stop() -> void:
_ws.stop()
func send_frame(peer_id: int, frame: RPCFrame) -> void:
_ws.send(peer_id, JSON.stringify(frame.to_dict(), "", false))
func _on_ws_message(peer_id: int, message: Variant) -> void:
if not message is String:
return
var json := JSON.new()
var err := json.parse(message)
if err != OK:
send_frame(peer_id, RPCError.new(json.get_error_message()))
return
var result = request_schema.parse(json.get_data())
if not result.ok():
send_frame(peer_id, RPCError.new(result.error))
return
var req := RPCRequest.from_dict(result.data, peer_id)
for scope in scopes:
if scope.can_handle_request(req):
scope.handle_request(req)
return
func _on_ws_client_connected(peer_id: int) -> void:
pass
func _on_ws_client_disconnected(peer_id: int) -> void:
pass

89
rpc_renderer/rpc_scope.gd Normal file
View file

@ -0,0 +1,89 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class_name RPCScope
## An object that can respond to requests and send events.
##
## A scope is a handler for requests sent by remote clients, and events from the API. It is generally related to different areas of the program.
## The name of this scope.
var name: String
# Dictionary[String -> RPCOperation.type, Callable]
## The operation types this scope can handle.
## Map of [member RPCOperation.type] to [Callable]. The function will be called
## with one argument: the [RPCRequest] to handle.
var operation_types: Dictionary
## Emitted when a response to a request is ready to be sent.
signal response(response: RPCRequestResponse)
## Emitted when an event is ready to be sent.
signal event(event: RPCEvent)
## Returns [code]true[/code] if this scope can handle the given request.
func can_handle_request(request: RPCRequest) -> bool:
return request.operation.type in operation_types
## Wrapper function to handle a request. See [param operation_types].
func handle_request(request: RPCRequest) -> void:
var c: Callable = operation_types[request.operation.type]
c.call(request)
## Returns an [RPCRequestResponse] that's set up to respond to the given [param request].
## Does not emit [signal response].
func create_response(request: RPCRequest, data: Variant, error: RPCError = null) -> RPCRequestResponse:
var r := RPCRequestResponse.new(request)
r.for_request = request.id
r.scope = name
r.kept = request.keep
r.peer_id = request.peer_id
if data is RPCFrame:
r.data = data.to_dict()
else:
r.data = data
if error:
r.errors.append(error)
return r
func create_error(request: RPCRequest, error_text: String) -> RPCRequestResponse:
var r := RPCRequestResponse.new(request)
r.for_request = request.id
r.scope = name
r.kept = request.keep
r.peer_id = request.peer_id
r.data = {}
r.errors.append(RPCError.new(error_text))
return r
func create_generic_success(request: RPCRequest) -> RPCRequestResponse:
var r := RPCRequestResponse.new(request)
r.for_request = request.id
r.scope = name
r.kept = request.keep
r.peer_id = request.peer_id
r.data = {
"success": true
}
return r
func create_event(type: String, data: Variant, condition := {}) -> RPCEvent:
return RPCEvent.new(type, name, data, condition)
func reconnect(p_signal: Signal, connect_to: Callable, to_call: Callable) -> void:
p_signal.disconnect(connect_to)
to_call.call()
p_signal.connect(connect_to)

View file

@ -0,0 +1,45 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class_name RPCSignalLayer
static var signals := Signals.new()
static func _static_init() -> void:
DeckHolder.signals.deck_added.connect(RPCSignalLayer._on_deck_added)
DeckHolder.signals.deck_closed.connect(
func(deck_id: String):
signals.deck_closed.emit(deck_id)
)
static func _on_deck_added(deck_id: String) -> void:
signals.deck_added.emit(deck_id)
DeckHolder.get_deck(deck_id).node_added.connect(RPCSignalLayer._on_deck_node_added)
static func _on_deck_node_added(node: DeckNode) -> void:
signals.deck_node_added.emit(node._belonging_to.id, node._id)
node.position_updated.connect(RPCSignalLayer._on_node_position_updated.bind(node._belonging_to.id, node._id))
static func _on_node_position_updated(new_position: Dictionary, node_id: String, deck_id: String) -> void:
signals.node_position_updated.emit(deck_id, node_id, new_position)
class Signals:
#region deck holder
signal deck_added(deck_id: String)
signal deck_closed(deck_id: String)
#endregion
#region deck
signal deck_node_added(deck_id: String, node_id: String)
#endregion
#region node
signal node_position_updated(deck_id: String, node_id: String, new_position: Dictionary)
#endregion

View file

@ -0,0 +1,36 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCScope
func _init() -> void:
name = "deck"
operation_types = {
"add_node": add_node,
}
RPCSignalLayer.signals.deck_node_added.connect(_on_deck_node_added)
func add_node(r: RPCRequest) -> void:
reconnect(
RPCSignalLayer.signals.deck_node_added,
_on_deck_node_added,
func():
var deck := DeckHolder.get_deck(r.operation.condition.deck_id)
var node := deck.add_node_type(r.operation.payload.node_type)
var node_partial := RPCNodePartial.new()
node_partial.deck_id = deck.id
node_partial.id = node._id
var resp := create_response(r, node_partial)
resp.create_event_counterpart(node_partial)
response.emit(resp)
)
func _on_deck_node_added(deck_id: String, node_id: String) -> void:
event.emit(create_event("node_added", {"node_id": node_id}, {"deck_id": deck_id}))

View file

@ -0,0 +1,76 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCScope
func _init() -> void:
name = "deck_holder"
operation_types = {
"new_deck": new_deck, # TODO: evaluate later
"get_deck": get_deck,
"send_event": send_event,
"error": error,
}
RPCSignalLayer.signals.deck_added.connect(_on_deck_holder_deck_added)
RPCSignalLayer.signals.deck_closed.connect(_on_deck_holder_deck_closed)
func error(r: RPCRequest) -> void:
response.emit(create_error(r, "random error"))
func new_deck(r: RPCRequest) -> void:
reconnect(
RPCSignalLayer.signals.deck_added,
_on_deck_holder_deck_added,
func():
var deck_partial := RPCDeckPartial.new()
deck_partial.id = DeckHolder.add_empty_deck().id
var resp := create_response(r, deck_partial)
resp.create_event_counterpart(deck_partial)
response.emit(resp)
)
func get_deck(r: RPCRequest) -> void:
if not r.operation.condition.has("id"):
response.emit(create_error(r, "Invalid Condition"))
return
var deck := DeckHolder.get_deck(r.operation.condition.id)
if deck == null:
response.emit(create_error(r, "Deck doesn't exist"))
return
response.emit(create_response(r, deck.to_dict()))
func send_event(r: RPCRequest) -> void:
if not r.operation.payload.has("event_name"):
response.emit(create_error(r, "Event name must be present and not empty."))
return
var event_data: Dictionary
if not r.operation.payload.has("event_data"):
event_data = {}
elif not r.operation.payload.event_data is Dictionary:
#response.emit(create_error(r, "Event data must be an Object"))
var err := RPCError.new("Event data must be an Object")
response.emit(create_response(r, {}, err))
return
else:
event_data = r.operation.payload.event_data
DeckHolder.send_event(r.operation.payload.event_name, event_data)
response.emit(create_generic_success(r))
func _on_deck_holder_deck_added(deck_id: String) -> void:
event.emit(create_event("new_deck", {"deck_id": deck_id}))
func _on_deck_holder_deck_closed(deck_id: String) -> void:
pass

View file

@ -0,0 +1,14 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCScope
func _init() -> void:
name = "node"
RPCSignalLayer.signals.node_position_updated.connect(_on_node_position_updated)
func _on_node_position_updated(deck_id: String, node_id: String, position: Dictionary) -> void:
event.emit(create_event("position_updated", position, {"deck_id": deck_id, "node_id": node_id}))

View file

@ -0,0 +1,12 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCFrame
class_name RPCDeckPartial
var id: String
func _init() -> void:
frame_name = "deck_partial"
_props = [&"id"]

View file

@ -0,0 +1,13 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCFrame
class_name RPCNodePartial
var id: String
var deck_id: String
func _init() -> void:
frame_name = "node_partial"
_props = [&"id", &"deck_id"]

View file

@ -0,0 +1,15 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCFrame
class_name RPCError
## Generic RPC error type.
var text: String
func _init(p_text: String) -> void:
frame_name = "error"
_props = [&"text"]
text = p_text

View file

@ -0,0 +1,35 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCFrame
class_name RPCEvent
## RPC Event type.
##
## Events are sent when something happens that wasn't initiated by a client.
var id: String = UUID.v4()
var type: String
var scope: String
var data: Variant
var condition: Dictionary
func _init(
p_type: String,
p_scope: String,
p_data: Variant,
p_condition: Dictionary = {},
) -> void:
frame_name = "event"
_props = [
&"id",
&"type",
&"scope",
&"data",
&"condition",
]
type = p_type
scope = p_scope
data = p_data
condition = p_condition

View file

@ -0,0 +1,41 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCFrame
class_name RPCOperation
## RPC Operation type.
##
## An operation is a part of a request from a remote client. It describes a request based on the type (what to do), the condition (what to do it to) and the payload (what data to do it with).
var type: String
## A condition is an object usually describing which object the operation will apply to.
var condition: Dictionary
## The payload is additional data that may be required to perform an action.
var payload: Dictionary
func _init(p_type: String, p_condition: Dictionary = {}, p_payload: Dictionary = {}) -> void:
frame_name = "operation"
_props = [&"type", &"condition", &"payload"]
type = p_type
condition = p_condition
payload = p_payload
static func from_dict(d: Dictionary) -> RPCOperation:
var r := RPCOperation.new(
d.type,
d.get("condition", {}),
d.get("payload", {}),
)
return r
static func schema() -> Zodot:
return Z.schema({
"type": Z.string(),
"condition": Z.dictionary().nullable(),
"payload": Z.dictionary().nullable()
})

View file

@ -0,0 +1,34 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class_name RPCRequest
## RPC Request type.
##
## A request is initiated by a remote client that tells the program it wants to do something.
## Provided by the client.
var id: String
## Broadly, which part of the program should handle this request. See [RPCScope].
var scope: String
## The action that the client wants to perform.
var operation: RPCOperation
## Any other data that will be kept and returned back to the client when a response is sent. Optional.
var keep: Dictionary
## Which peer initiated this request.
var peer_id: int
static func from_dict(d: Dictionary, p_peer_id: int) -> RPCRequest:
if not d.has("request"):
return null
var r := RPCRequest.new()
r.id = d.request.id
r.scope = d.request.scope
r.operation = RPCOperation.from_dict(d.request.operation)
r.keep = d.request.get("keep", {})
r.peer_id = p_peer_id
return r

View file

@ -0,0 +1,43 @@
# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
extends RPCFrame
class_name RPCRequestResponse
## RPC Request Response type.
##
## A response to a [RPCRequest]. Initiated by the server as a response. Does not inherently indicate a successful operation.
var id: String = UUID.v4()
## The ID of the request that prompted this response. See [member RPCRequest.id].
var for_request: String
## Broadly, which part of the program this response comes from. See [RPCScope]. The scope will be the same as the [RPCRequest] this is a response for.
var scope: String
## If non-[code]null[/code], the error that this request represents.
var errors: Array[RPCError]
## Additional data associated with the response. Mandatory, but can be empty.
var data: Dictionary
## See [member RPCRequest.keep].
var kept: Dictionary
## The peer ID this response is intended for. See [member RPCRequest.peer_id].
var peer_id: int
var request: RPCRequest
var event_counterpart: RPCEvent
func _init(p_request: RPCRequest) -> void:
request = p_request
frame_name = "request_response"
_props = [
&"id",
&"for_request",
&"scope",
&"errors",
&"data",
&"kept",
]
func create_event_counterpart(data: Variant) -> void:
event_counterpart = RPCEvent.new(request.operation.type, scope, data, request.operation.condition)

View file

@ -0,0 +1,171 @@
#Copyright (c) 2014-present Godot Engine contributors.
#Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur.
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
extends Node
class_name WebSocketServer
signal message_received(peer_id: int, message)
signal client_connected(peer_id: int)
signal client_disconnected(peer_id: int)
@export var handshake_headers := PackedStringArray()
@export var supported_protocols: PackedStringArray
@export var handshake_timout := 3000
@export var use_tls := false
@export var tls_cert: X509Certificate
@export var tls_key: CryptoKey
@export var refuse_new_connections := false:
set(refuse):
if refuse:
pending_peers.clear()
class PendingPeer:
var connect_time: int
var tcp: StreamPeerTCP
var connection: StreamPeer
var ws: WebSocketPeer
func _init(p_tcp: StreamPeerTCP):
tcp = p_tcp
connection = p_tcp
connect_time = Time.get_ticks_msec()
var tcp_server := TCPServer.new()
var pending_peers: Array[PendingPeer] = []
var peers: Dictionary
func listen(port: int) -> int:
assert(not tcp_server.is_listening())
return tcp_server.listen(port)
func stop():
tcp_server.stop()
pending_peers.clear()
peers.clear()
func send(peer_id, message) -> int:
var type = typeof(message)
if peer_id <= 0:
# Send to multiple peers, (zero = brodcast, negative = exclude one)
for id in peers:
if id == -peer_id:
continue
if type == TYPE_STRING:
peers[id].send_text(message)
else:
peers[id].put_packet(message)
return OK
assert(peers.has(peer_id))
var socket = peers[peer_id]
if type == TYPE_STRING:
return socket.send_text(message)
return socket.send(var_to_bytes(message))
func get_message(peer_id) -> Variant:
assert(peers.has(peer_id))
var socket = peers[peer_id]
if socket.get_available_packet_count() < 1:
return null
var pkt = socket.get_packet()
if socket.was_string_packet():
return pkt.get_string_from_utf8()
return bytes_to_var(pkt)
func has_message(peer_id) -> bool:
assert(peers.has(peer_id))
return peers[peer_id].get_available_packet_count() > 0
func _create_peer() -> WebSocketPeer:
var ws = WebSocketPeer.new()
ws.supported_protocols = supported_protocols
ws.handshake_headers = handshake_headers
return ws
func poll() -> void:
if not tcp_server.is_listening():
return
while not refuse_new_connections and tcp_server.is_connection_available():
var conn = tcp_server.take_connection()
assert(conn != null)
pending_peers.append(PendingPeer.new(conn))
var to_remove := []
for p in pending_peers:
if not _connect_pending(p):
if p.connect_time + handshake_timout < Time.get_ticks_msec():
# Timeout
to_remove.append(p)
continue # Still pending
to_remove.append(p)
for r in to_remove:
pending_peers.erase(r)
to_remove.clear()
for id in peers:
var p: WebSocketPeer = peers[id]
var packets = p.get_available_packet_count()
p.poll()
if p.get_ready_state() != WebSocketPeer.STATE_OPEN:
client_disconnected.emit(id)
to_remove.append(id)
continue
while p.get_available_packet_count():
message_received.emit(id, get_message(id))
for r in to_remove:
peers.erase(r)
to_remove.clear()
func _connect_pending(p: PendingPeer) -> bool:
if p.ws != null:
# Poll websocket client if doing handshake
p.ws.poll()
var state = p.ws.get_ready_state()
if state == WebSocketPeer.STATE_OPEN:
var id = randi_range(2, 1 << 30)
peers[id] = p.ws
client_connected.emit(id)
return true # Success.
elif state != WebSocketPeer.STATE_CONNECTING:
return true # Failure.
return false # Still connecting.
elif p.tcp.get_status() != StreamPeerTCP.STATUS_CONNECTED:
return true # TCP disconnected.
elif not use_tls:
# TCP is ready, create WS peer
p.ws = _create_peer()
p.ws.accept_stream(p.tcp)
return false # WebSocketPeer connection is pending.
else:
if p.connection == p.tcp:
assert(tls_key != null and tls_cert != null)
var tls = StreamPeerTLS.new()
tls.accept_stream(p.tcp, TLSOptions.server(tls_key, tls_cert))
p.connection = tls
p.connection.poll()
var status = p.connection.get_status()
if status == StreamPeerTLS.STATUS_CONNECTED:
p.ws = _create_peer()
p.ws.accept_stream(p.connection)
return false # WebSocketPeer connection is pending.
if status != StreamPeerTLS.STATUS_HANDSHAKING:
return true # Failure.
return false
func _process(delta):
poll()