80 lines
3 KiB
PHP
80 lines
3 KiB
PHP
<?php
|
|
|
|
namespace App\Extensions\Webrtc;
|
|
|
|
use JumPHP\Renderer\Renderer;
|
|
use JumPHP\Scene\AbstractScene;
|
|
use JumPHP\WebRtc\DataChannel;
|
|
use JumPHP\WebRtc\WebRtc;
|
|
|
|
/**
|
|
* Sample of jumphp/webrtc: two peers in this game, connected to each other (the signals go straight from one to the other), a data channel
|
|
* between them. Space (or a click) sends a PING from A, B answers PONG. Same code in the browser and on the desktop.
|
|
* JUMPHP_SCENE='App\Extensions\Webrtc\LoopbackSample' bin/jumphp run <game>
|
|
*/
|
|
final class LoopbackSample extends AbstractScene
|
|
{
|
|
public const LABEL = 'Two peers in this game: Space sends a PING through a WebRTC data channel';
|
|
|
|
private ?DataChannel $a = null;
|
|
private string $state = '';
|
|
/** @var list<string> */
|
|
private array $log = [];
|
|
private int $n = 0;
|
|
|
|
public function __construct(private WebRtc $webrtc)
|
|
{
|
|
}
|
|
|
|
public function enter(array $params = []): void
|
|
{
|
|
$this->log = [];
|
|
$this->n = 0;
|
|
$this->state = 'starting (' . $this->webrtc->backendName() . ')';
|
|
$one = $this->webrtc->peer(['stun' => '']); // the same computer: no STUN needed
|
|
$two = $this->webrtc->peer(['stun' => '']);
|
|
$one->on('signal', fn (array $s) => $two->signal($s)); // in a real game: through the relay, a server, a QR code...
|
|
$two->on('signal', fn (array $s) => $one->signal($s));
|
|
$one->on('state', fn (string $s) => $this->state = $s);
|
|
foreach ([$one, $two] as $p) {
|
|
$p->on('error', fn (string $e) => $this->log[] = 'ERROR: ' . $e);
|
|
}
|
|
$this->a = $one->channel('chat');
|
|
$this->a->on('open', fn () => $this->log[] = 'A: channel open');
|
|
$this->a->on('message', fn (string $text) => $this->log[] = 'A got ' . $text);
|
|
$two->on('channel', function (DataChannel $b): void {
|
|
$b->on('message', function (string $text) use ($b): void {
|
|
$this->log[] = 'B got ' . $text;
|
|
$b->send(str_replace('PING', 'PONG', $text));
|
|
});
|
|
});
|
|
$one->offer();
|
|
}
|
|
|
|
public function exit(): void
|
|
{
|
|
$this->webrtc->closeAll();
|
|
}
|
|
|
|
public function update(float $dt): void
|
|
{
|
|
if ($this->actions()->isPressed('back')) {
|
|
$this->scenes()->switchTo((string)$this->engine->config->get('start_scene'));
|
|
return;
|
|
}
|
|
if ($this->actions()->isPressed('send') && $this->a?->isOpen()) {
|
|
$this->a->send('PING ' . ++$this->n);
|
|
}
|
|
$this->log = array_slice($this->log, -9);
|
|
}
|
|
|
|
public function render(Renderer $r): void
|
|
{
|
|
$r->clear([10, 12, 22]);
|
|
$this->font()->draw($r, 'WEBRTC LOOPBACK: ' . strtoupper($this->state), 8, 8, 1, [120, 200, 255]);
|
|
foreach ($this->log as $i => $line) {
|
|
$this->font()->draw($r, strtoupper($line), 8, 26 + $i * 12, 1, [220, 225, 240]);
|
|
}
|
|
$this->font()->draw($r, 'SPACE: SEND A PING ESC: BACK', $this->width() / 2, $this->height() - 14, 1, [140, 140, 170], 'center');
|
|
}
|
|
}
|