SDK

Godot

valkyr_bridge.gd, un puente en GDScript puro que se ejecuta en un servidor headless de Godot 4 y se comunica con valkyr-server por HTTP.

bindings/godot/valkyr_bridge.gd es GDScript puro para un servidor dedicado de Godot 4 (una exportación headless). Se comunica por HTTP con un valkyr-server que corre a su lado:

  • los eventos se ponen en cola y se envían en lotes a POST /v1/matches/{match_id}/events;
  • las acciones de sanción se consultan en GET /v1/actions y se emiten como la señal action_received(player, action, reason);
  • end_match() cierra la partida.

Así no hace falta una compilación nativa por plataforma y la detección queda en un proceso separado que un servidor de juego que se cae no puede tumbar.

Sin probar

Godot no estaba disponible donde se escribió el puente, así que el script no se ha ejecutado. Los reportes y correcciones son bienvenidos.

Uso

  1. Ejecuta valkyr-server en la misma máquina con una clave de API que tenga el rol ingest.
  2. Agrega valkyr_bridge.gd a un nodo de la escena del servidor, o como autoload, y configura server_url, api_key y match_id.
  3. Reporta frames y actúa según las acciones:
server.gdGDScript
@onready var valkyr = $ValkyrBridge func _ready():    valkyr.action_received.connect(_on_valkyr_action) func _physics_process(_delta):    for p in players:  # your server side player nodes        valkyr.report_frame(p.peer_id, p.last_input_client_ms, p.global_position,            p.rotation.y, p.camera.rotation.x, p.is_on_floor(), p.jumped_this_tick) func _on_valkyr_action(player: int, action: String, reason: String):    if action == "kick":        multiplayer.multiplayer_peer.disconnect_peer(player)

Coordenadas

Godot usa metros e Y hacia arriba como valkyr, pero un nodo con rotation.y = 0 mira hacia -Z, mientras que el yaw 0 de valkyr mira hacia +Z. El puente hace la conversión: el yaw de valkyr es rad_to_deg(rotation.y) + 180, ajustado al rango de -180 a 180, y el pitch es rad_to_deg(camera.rotation.x). Las posiciones se pasan sin cambios.

El puente

valkyr_bridge.gdGDScript
# valkyr_bridge.gd - Godot 4 bridge from a headless (dedicated) Godot# server to a local valkyr-server over HTTP.## Untested example (Godot was not available where this was written).## Add this script to a Node in the server scene (or register it as an# autoload), set server_url, api_key (a key with the "ingest" role) and# match_id, then call the report_* functions from your server side game# code. Events are sent in batches; enforcement actions (kick and above)# are polled from /v1/actions and emitted as the action_received signal.## Coordinates: Godot is meters and Y up like valkyr, but a Godot node looks# along -Z with rotation.y = 0, while valkyr yaw 0 looks along +Z and 90# along +X. So valkyr yaw = rad_to_deg(rotation.y) + 180 (wrapped) and# valkyr pitch = rad_to_deg(camera rotation.x) (both positive up).extends Node signal action_received(player: int, action: String, reason: String) @export var server_url := "http://127.0.0.1:7420"@export var api_key := ""@export var match_id := "match-1"@export var batch_interval_sec := 0.25@export var poll_interval_sec := 1.0@export var max_batch := 2000 var _queue: Array = []var _sending := falsevar _polling := falsevar _cursor := 0var _send_timer := 0.0var _poll_timer := 0.0var _seq := {}var _events_http: HTTPRequestvar _actions_http: HTTPRequest  func _ready() -> void:	_events_http = HTTPRequest.new()	_actions_http = HTTPRequest.new()	add_child(_events_http)	add_child(_actions_http)	_events_http.request_completed.connect(_on_events_done)	_actions_http.request_completed.connect(_on_actions_done)  func _process(delta: float) -> void:	_send_timer += delta	_poll_timer += delta	if _send_timer >= batch_interval_sec:		_send_timer = 0.0		_flush()	if _poll_timer >= poll_interval_sec:		_poll_timer = 0.0		_poll()  static func now_ms() -> int:	return Time.get_ticks_msec()  static func valkyr_yaw(godot_rotation_y: float) -> float:	return wrapf(rad_to_deg(godot_rotation_y) + 180.0, -180.0, 180.0)  static func valkyr_pitch(godot_camera_rotation_x: float) -> float:	return rad_to_deg(godot_camera_rotation_x)  static func _vec(v: Vector3) -> Dictionary:	return {"x": v.x, "y": v.y, "z": v.z}  ## Per tick state of a player as the server sees it.## client_time_ms: the timestamp the client sent with its input.func report_frame(player: int, client_time_ms: int, feet: Vector3, body_rotation_y: float,		camera_rotation_x: float, on_ground: bool, jump: bool) -> void:	var seq: int = _seq.get(player, 0) + 1	_seq[player] = seq	_queue.append({		"type": "frame", "player": player, "seq": seq,		"client_time_ms": client_time_ms, "server_time_ms": now_ms(),		"position": _vec(feet), "yaw": valkyr_yaw(body_rotation_y),		"pitch": valkyr_pitch(camera_rotation_x),		"on_ground": on_ground, "jump": jump,	})  ## A shot the server accepted. target is -1 when nothing was hit; bone is## "head", "body", "limb" or "".func report_shot(player: int, client_time_ms: int, weapon: int, body_rotation_y: float,		camera_rotation_x: float, target: int = -1, bone: String = "", latency_ms: int = 0) -> void:	var ev := {		"type": "shot", "player": player, "client_time_ms": client_time_ms,		"server_time_ms": now_ms(), "weapon": weapon,		"yaw": valkyr_yaw(body_rotation_y), "pitch": valkyr_pitch(camera_rotation_x),		"latency_ms": latency_ms,	}	if target >= 0:		ev["target"] = target	if bone != "":		ev["bone"] = bone	_queue.append(ev)  ## Spawn or server authorized teleport (resets movement history).func report_spawn(player: int, feet: Vector3, team: int) -> void:	_queue.append({		"type": "spawn", "player": player, "server_time_ms": now_ms(),		"position": _vec(feet), "team": team,	})  func _headers() -> PackedStringArray:	return PackedStringArray([		"Content-Type: application/json",		"Authorization: Bearer %s" % api_key,	])  func _flush() -> void:	if _sending or _queue.is_empty():		return	var n := mini(_queue.size(), max_batch)	var batch := _queue.slice(0, n)	_queue = _queue.slice(n)	var url := "%s/v1/matches/%s/events" % [server_url, match_id.uri_encode()]	var body := JSON.stringify({"events": batch})	if _events_http.request(url, _headers(), HTTPClient.METHOD_POST, body) == OK:		_sending = true	else:		push_warning("valkyr: could not send %d events" % n)  func _on_events_done(result: int, code: int, _headers_in: PackedStringArray, body: PackedByteArray) -> void:	_sending = false	if result != HTTPRequest.RESULT_SUCCESS or code != 200:		push_warning("valkyr: events rejected (%d, %d): %s" % [result, code, body.get_string_from_utf8()])  func _poll() -> void:	if _polling:		return	var url := "%s/v1/actions?since=%d&limit=100" % [server_url, _cursor]	if _actions_http.request(url, _headers(), HTTPClient.METHOD_GET) == OK:		_polling = true  func _on_actions_done(result: int, code: int, _headers_in: PackedStringArray, body: PackedByteArray) -> void:	_polling = false	if result != HTTPRequest.RESULT_SUCCESS or code != 200:		return	var data = JSON.parse_string(body.get_string_from_utf8())	if typeof(data) != TYPE_DICTIONARY:		return	for a in data.get("actions", []):		# The queue is shared by every match on the valkyr server.		if str(a.get("match_id", match_id)) != match_id:			continue		action_received.emit(int(a.get("player", 0)), str(a.get("action", "")), str(a.get("reason", "")))	_cursor = int(data.get("cursor", _cursor))  ## Ends the match on the server. Call it after the last report and once the## queue is empty (the end request is not ordered with a batch in flight).func end_match() -> void:	var http := HTTPRequest.new()	add_child(http)	http.request_completed.connect(func(_r, _c, _h, _b): http.queue_free())	http.request("%s/v1/matches/%s/end" % [server_url, match_id.uri_encode()], _headers(),		HTTPClient.METHOD_POST, "{}")

Editar esta página en GitHub