Skip to content

Segui le immagini della fotocamera ​

Nel passo 1 ognuno dei dieci fotogrammi al secondo passava da subscribe e ridisegnava tutta la vista. Ora la fotocamera ha un listener suo (onData) che disegna ogni fotogramma separatamente dal resto della vista, conta i fotogrammi e permette alla persona di mettere in pausa la fotocamera.

Perché la fotocamera ha bisogno di un listener suo ​

subscribe chiama il suo listener dopo ogni cambiamento dell'agente (un nuovo fotogramma, un nuovo messaggio o un nuovo stato). Con la fotocamera queste chiamate arrivano dieci volte al secondo e mai più di una volta per animation frame. A questo ritmo ridisegnare un nome e una descrizione non costa niente. I prossimi passi però aggiungono una conversazione, la fotocamera della persona e una casella per i messaggi. Ricostruire tutto questo dieci volte al secondo rallenta la vista e in JavaScript semplice fa perdere anche la posizione di scorrimento e il testo selezionato dalla persona.

agent.onData(name, listener) chiama listener con ogni nuovo valore di un solo nome di data e ignora tutti gli altri cambiamenti. Restituisce una funzione che ferma il listener:

js
const stop = agent.onData('camera', (frame) => {
  picture.src = frame;
  frames += 1;
});

// Later: stop following. The picture stays on the last frame.
stop();

Pausa e riproduzione ​

Pause ferma il listener con la funzione restituita da onData e l'<img> continua a mostrare l'ultimo fotogramma. Per riprendere Play chiama di nuovo onData:

js
function play() {
  stopCamera = agent.onData('camera', (frame) => { picture.src = frame; frames += 1; });
}

function pause() {
  stopCamera();
  stopCamera = null;
}

Conta le immagini ​

Il listener incrementa frames a ogni fotogramma. Una volta al secondo un timer scrive il conteggio nella didascalia ("Live: 10 frames a second") e lo riporta a zero. Da questo conteggio tu e la persona capite se la fotocamera è dal vivo.

In JavaScript semplice tutto il codice della fotocamera è passato nel listener di onData e subscribe ora disegna solo il titolo e la descrizione.

In React ​

In React la fotocamera è un componente (AgentCamera) che registra il suo listener di onData in un effect. Scrivere ogni fotogramma nell'<img> attraverso un ref invece di salvarlo nello state evita un render in più per ogni fotogramma.

jsx
useEffect(() => {
  if (isPaused) return undefined;
  let frames = 0;
  const stop = agent.onData('camera', (frame) => {
    picture.current.src = frame;
    frames += 1;
  });
  const timer = setInterval(() => { setFramesPerSecond(frames); frames = 0; }, 1000);
  return () => {
    stop();
    clearInterval(timer);
  };
}, [isPaused]);
  • L'effect gira di nuovo solo quando cambia isPaused. La cleanup che gira su Pause ferma sia il listener di onData sia il timer.
  • agent manca apposta dalle dipendenze. Dato che useWorld restituisce una nuova copia di agent a ogni cambiamento, elencarlo fermerebbe e riavvierebbe il listener a ogni fotogramma. onData funziona da qualunque copia e basta la prima.

useWorld continua a rifare il render dei tuoi componenti a ogni cambiamento dell'agente e quindi a ogni fotogramma. Qui questi render costano poco perché React aggiorna nel DOM solo quello che è diverso. Restano economici finché ne tieni fuori il lavoro pesante (Prestazioni).

Il codice ​

jsx
import { useEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';

// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
	const x = 170 + 70 * Math.sin(time / 800);
	const y = 120 - Math.abs(25 * Math.sin(time / 300));
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake agent to build with. Its camera sends a new picture every 100 ms.
const feeder = {
	name: 'Feeder',
	profile: { description: 'A camera at a bird feeder, in a garden.' },
	data: { camera: { every: 100, value: frameAt } },
};

// The camera of the agent, apart from the rest, with its picture, a caption and a button to pause it.
function AgentCamera({ agent }) {
	const picture = useRef(null);
	const [isPaused, setIsPaused] = useState(false);
	const [framesPerSecond, setFramesPerSecond] = useState(null);

	useEffect(() => {
		if (isPaused) return undefined;
		let frames = 0;
		// onData calls this with every new picture of `camera`, and for nothing else.
		// The picture goes straight into the <img>, with no state and no new render.
		const stop = agent.onData('camera', (frame) => {
			picture.current.src = frame;
			frames += 1;
		});
		// Once a second, show how many pictures arrived.
		const timer = setInterval(() => {
			setFramesPerSecond(frames);
			frames = 0;
		}, 1000);
		// A pause stops both, and the picture stays on the last frame.
		return () => {
			stop();
			clearInterval(timer);
		};
		// Start again only after a pause, because `onData` works from any copy of `agent`.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isPaused]);

	let caption = `Live: ${framesPerSecond} frames a second`;
	if (isPaused) caption = 'Paused';
	else if (framesPerSecond === null) caption = `Waiting for ${agent.name}'s camera…`;
	return (
		<>
			<img ref={picture} alt={`${agent.name}'s camera`} width="320" height="180" />
			<p>{caption}</p>
			<button onClick={() => setIsPaused(!isPaused)}>{isPaused ? 'Play' : 'Pause'}</button>
		</>
	);
}

export default function App() {
	// While building: the fake agent. In the webapp: useWorld()
	const { world: agent, error } = useWorld({ fake: { agent: feeder } });

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!agent) return <p>Connecting…</p>;
	return (
		<>
			<h1>{agent.name}</h1>
			<p>{agent.profile.description}</p>
			<AgentCamera agent={agent} />
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The camera of the fake agent draws a robin at a bird feeder as an SVG picture.
// Every picture is a little different, because `time` moves the bird.
function frameAt(time) {
	const x = 170 + 70 * Math.sin(time / 800);
	const y = 120 - Math.abs(25 * Math.sin(time / 300));
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="180">
<rect width="320" height="180" fill="#bfe3ff"/><rect y="140" width="320" height="40" fill="#7cc576"/>
<rect x="40" y="70" width="10" height="70" fill="#8b5a2b"/><rect x="18" y="66" width="54" height="8" fill="#8b5a2b"/><polygon points="12,50 78,50 45,30" fill="#a0522d"/>
<circle cx="${x}" cy="${y}" r="14" fill="#d35400"/><circle cx="${x + 12}" cy="${y - 12}" r="8" fill="#6e4b2a"/>
<polygon points="${x + 19},${y - 13} ${x + 28},${y - 10} ${x + 19},${y - 8}" fill="#f1c40f"/>
<text x="310" y="20" font-size="13" font-family="monospace" text-anchor="end">${new Date(time).toLocaleTimeString('en-GB')}</text>
</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake agent to build with. Its camera sends a new picture every 100 ms.
const feeder = {
	name: 'Feeder',
	profile: { description: 'A camera at a bird feeder, in a garden.' },
	data: { camera: { every: 100, value: frameAt } },
};

// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: feeder } });

const title = document.createElement('h1');
const description = document.createElement('p');
document.body.append(title, description);

// Everything but the camera. This listener runs at every change, a new picture included, and must stay light.
agent.subscribe((node) => {
	title.textContent = node.name;
	description.textContent = node.profile.description ?? '';
});

// The camera, apart from the rest, with its picture, a caption and a button to pause it.
const picture = document.createElement('img');
picture.alt = `${agent.name}'s camera`;
picture.width = 320;
picture.height = 180;
const caption = document.createElement('p');
const pauseButton = document.createElement('button');
document.body.append(picture, caption, pauseButton);

let frames = 0; // pictures since the last count
let framesPerSecond = null; // the last count, or null before the first one
let stopCamera = null; // stops following the camera, or null while paused

function drawCaption() {
	if (!stopCamera) caption.textContent = 'Paused';
	else if (framesPerSecond === null) caption.textContent = `Waiting for ${agent.name}'s camera…`;
	else caption.textContent = `Live: ${framesPerSecond} frames a second`;
	pauseButton.textContent = stopCamera ? 'Pause' : 'Play';
}

function play() {
	// onData calls this with every new picture of `camera`, and for nothing else.
	stopCamera = agent.onData('camera', (frame) => {
		picture.src = frame;
		frames += 1;
	});
	drawCaption();
}

function pause() {
	stopCamera(); // the picture stays on the last frame
	stopCamera = null;
	drawCaption();
}

pauseButton.onclick = () => (stopCamera ? pause() : play());
play();

// Once a second, show how many pictures arrived.
setInterval(() => {
	if (stopCamera) framesPerSecond = frames;
	frames = 0;
	drawCaption();
}, 1000);
Live, on a fake world
Open

Pause ferma l'uccello e l'orologio e Play li fa ripartire.

Prossimi passi ​

Feeder risponde anche ai messaggi e il passo 3: Parla con l'agente aggiunge la conversazione alla vista.

La ricetta Segui i dati veloci senza rallentare applica onData a un misuratore di suono che cambia venti volte al secondo.

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.