[READ-ONLY] Mirror of https://github.com/flo-bit/threlte-vr-code-editor. proof of concept for a live 3d code editor in vr
code-editor threejs threlte vr
0

Configure Feed

Select the types of activity you want to include in your feed.

1.9 kB 68 lines
1import Peer from 'peerjs'; 2import type { DataConnection } from 'peerjs'; 3import { writable, type Writable } from 'svelte/store'; 4 5export const peerIdPrefix = 'peer-threlte-vr-editor-'; 6 7export function randomId(len = 4) { 8 // 6 random lowercase letters 9 return Array.from({ length: len }, () => 10 Math.floor(Math.random() * 36) 11 .toString(36) 12 .toUpperCase() 13 ).join(''); 14} 15 16export const stream: Writable<MediaStream | null> = writable(null); 17 18export function setupEditorConnection(peerId: string, callback: (data: unknown) => void) { 19 const id = `${peerIdPrefix}${peerId}`; 20 console.log('Peer ID:', id); 21 const peer = new Peer(id); 22 peer.on('open', (id) => { 23 console.log('Connected as', id); 24 peer.on('connection', (conn) => { 25 console.log('Connected to', conn.peer); 26 conn.on('data', (data) => { 27 callback(data); 28 }); 29 }); 30 31 peer.on('call', (call) => { 32 console.log('Incoming call from', call.peer); 33 call.answer(); 34 call.on('stream', (remoteStream) => { 35 console.log('Receiving remote stream'); 36 stream.set(remoteStream); 37 }); 38 }); 39 }); 40 return peer; 41} 42 43export const editor: Writable<DataConnection | null> = writable(null); 44 45export function connectToPeer(remotePeerId: string, stream?: MediaStream) { 46 console.log('Connecting to', remotePeerId); 47 const peerId = randomId(); 48 const id = `${peerIdPrefix}${peerId}`; 49 console.log('Peer ID:', id); 50 const peer = new Peer(id); 51 peer.on('open', (id) => { 52 console.log('Connected as', id); 53 54 if (stream) { 55 console.log('sharing screen with', `${peerIdPrefix}${remotePeerId}`); 56 peer.call(`${peerIdPrefix}${remotePeerId}`, stream); 57 } 58 59 console.log('opening data connection to', `${peerIdPrefix}${remotePeerId}`); 60 const conn = peer.connect(`${peerIdPrefix}${remotePeerId}`); 61 62 conn.on('open', () => { 63 console.log('Connected to', conn.peer); 64 editor.set(conn); 65 }); 66 return conn; 67 }); 68}