Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

example: grid world #159

Merged
merged 23 commits into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions examples/grid/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Topology Protocol Example

This is an example of Topology Protocol usage in a chat system where a user can create or connect to a chat room, send and read the messages sent in the group chat.

## Specifics

Messages are represented as strings in the format (timestamp, content, senderId). Chat is a class which extends TopologyObject and has Gset\<string> as an attribute to store the list of messages.

## How to run locally

After cloning the repository, run the following commands:

```bash
cd ts-topology/examples/chat
yarn
yarn build
yarn dev
```

Debugging is made easier by setting the mode in `webpack.config.js` to "development":

```js
module.exports = {
mode: "development",
...
}
```
27 changes: 27 additions & 0 deletions examples/grid/asconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"entries": ["./src/objects/chat.ts"],
"targets": {
"debug": {
"outFile": "dist/asc/debug.wasm",
"textFile": "dist/asc/debug.wat",
"sourceMap": true,
"debug": true
},
"release": {
"outFile": "dist/asc/release.wasm",
"textFile": "dist/asc/release.wat",
"sourceMap": false,
"optimizeLevel": 3,
"shrinkLevel": 0,
"converge": false,
"noAssert": false
}
},
"options": {
"lib": {
"@topology-foundation/crdt": [
"../node_modules/@topology-foundation/crdt/src/index.asc.ts"
]
}
}
}
37 changes: 37 additions & 0 deletions examples/grid/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Topology - Grid</title>
</head>
<body>
<div>
<h1>Topology Protocol - Grid</h1>
<p>Your peer ID <span id="peerId"></span></p>
<p>Connected to CRO ID: <span id="gridId"></span></p>
<p>Peers: <span id="peers"></span></p>
<p>Discovery_peers: <span id="discoveryPeers"></span></p>
<p>Object_peers: <span id="objectPeers"></span></p>

<input id="gridInput" type="text" placeholder="Grid ID" />
<button id="joinGrid">Connect</button>
<button id="createGrid">Create Grid</button>
</div>

<div
id="grid"
style="
position: relative;
width: 100%;
height: 60vh;
border: 1px solid black;
overflow: hidden;
"
>
<!-- Users will appear here -->
</div>

<script type="module" src="/src/index.ts"></script>
</body>
</html>
37 changes: 37 additions & 0 deletions examples/grid/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "topology-example-chat",
"version": "0.1.1",
"description": "Topology Protocol Chat Exmaple",
"main": "src/index.ts",
"repository": "https://github.com/topology-foundation/ts-topology.git",
"license": "MIT",
"scripts": {
"asbuild": "asc --config asconfig.json --target release",
"build": "vite build",
"clean": "rm -rf dist/ node_modules/",
"dev": "vite serve",
"start": "ts-node ./src/index.ts"
},
"dependencies": {
"@topology-foundation/crdt": "0.1.1",
"@topology-foundation/network": "0.1.1",
"@topology-foundation/node": "0.1.1",
"@topology-foundation/object": "0.1.1",
"assemblyscript": "^0.27.29",
"crypto-browserify": "^3.12.0",
"memfs": "^4.11.1",
"process": "^0.11.10",
"react-spring": "^9.7.4",
"stream-browserify": "^3.0.0",
"ts-node": "^10.9.2",
"uint8arrays": "^5.1.0",
"vm-browserify": "^1.1.2"
},
"devDependencies": {
"@types/node": "^22.5.4",
"ts-loader": "^9.5.1",
"typescript": "^5.5.4",
"vite": "^5.4.3",
"vite-plugin-node-polyfills": "^0.22.0"
}
}
215 changes: 215 additions & 0 deletions examples/grid/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
import { TopologyNode } from "@topology-foundation/node";
import type { TopologyObject } from "@topology-foundation/object";
import { Grid } from "./objects/grid";

const node = new TopologyNode();
let topologyObject: TopologyObject;
let gridCRO: Grid;
let peers: string[] = [];
let discoveryPeers: string[] = [];
let objectPeers: string[] = [];
const userId = Math.random().toString(36).substring(2);
const userColor = `#${Math.floor(Math.random() * 16777215).toString(16)}`;

const render = () => {
if (topologyObject)
(<HTMLButtonElement>document.getElementById("gridId")).innerText =
topologyObject.id;
const element_peerId = <HTMLDivElement>document.getElementById("peerId");
element_peerId.innerHTML = node.networkNode.peerId;

const element_peers = <HTMLDivElement>document.getElementById("peers");
element_peers.innerHTML = `[${peers.join(", ")}]`;

const element_discoveryPeers = <HTMLDivElement>(
document.getElementById("discoveryPeers")
);
element_discoveryPeers.innerHTML = `[${discoveryPeers.join(", ")}]`;

const element_objectPeers = <HTMLDivElement>(
document.getElementById("objectPeers")
);
element_objectPeers.innerHTML = `[${objectPeers.join(", ")}]`;

if (!gridCRO) return;
const users = gridCRO.getUsers();
const element_grid = <HTMLDivElement>document.getElementById("grid");
element_grid.innerHTML = "";

const gridWidth = element_grid.clientWidth;
const gridHeight = element_grid.clientHeight;
const centerX = Math.floor(gridWidth / 2);
const centerY = Math.floor(gridHeight / 2);

// Draw grid lines
const numLinesX = Math.floor(gridWidth / 50);
const numLinesY = Math.floor(gridHeight / 50);

for (let i = -numLinesX; i <= numLinesX; i++) {
const line = document.createElement("div");
line.style.position = "absolute";
line.style.left = `${centerX + i * 50}px`;
line.style.top = "0";
line.style.width = "1px";
line.style.height = "100%";
line.style.backgroundColor = "lightgray";
element_grid.appendChild(line);
}

for (let i = -numLinesY; i <= numLinesY; i++) {
const line = document.createElement("div");
line.style.position = "absolute";
line.style.left = "0";
line.style.top = `${centerY + i * 50}px`;
line.style.width = "100%";
line.style.height = "1px";
line.style.backgroundColor = "lightgray";
element_grid.appendChild(line);
}

for (const userColorString of users) {
const [id, color] = userColorString.split(':');
const position = gridCRO.getUserPosition(userColorString);

if (position) {
const div = document.createElement("div");
div.style.position = "absolute";
div.style.left = `${centerX + position.x * 50 + 5}px`; // Center the circle
div.style.top = `${centerY - position.y * 50 + 5}px`; // Center the circle
div.style.width = "40px";
div.style.height = "40px";
div.style.backgroundColor = color;
div.style.borderRadius = "50%";
div.style.transition = "background-color 1s ease-in-out";
div.style.animation = `glow-${id} 0.5s infinite alternate`;

// Create dynamic keyframes for the glow effect
const style = document.createElement("style");
style.innerHTML = `
@keyframes glow-${id} {
0% {
background-color: ${hexToRgba(color, 0.5)};
}
100% {
background-color: ${hexToRgba(color, 1)};
}
}`;
document.head.appendChild(style);

element_grid.appendChild(div);
}
}
};

// Helper function to convert hex color to rgba
function hexToRgba(hex: string, alpha: number) {
const bigint = parseInt(hex.slice(1), 16);
const r = (bigint >> 16) & 255;
const g = (bigint >> 8) & 255;
const b = bigint & 255;
return `rgba(${r}, ${g}, ${b}, ${alpha})`;
}

async function addUser() {
if (!gridCRO) {
console.error("Grid CRO not initialized");
alert("Please create or join a grid first");
return;
}

gridCRO.addUser(userId, userColor);
render();

// testing
const users = gridCRO.getUsers();
console.log('users', users);
for (const userColorString of users) {
const position = gridCRO.getUserPosition(userColorString);
console.log('userColorString', userColorString, 'position', JSON.stringify(position, null, 2));
}
console.log('----------------------------------');
}

async function moveUser(direction: string) {
if (!gridCRO) {
console.error("Grid CRO not initialized");
alert("Please create or join a grid first");
return;
}

gridCRO.moveUser(userId, direction);
render();

// testing
const users = gridCRO.getUsers();
console.log('users', users);
for (const userColorString of users) {
const position = gridCRO.getUserPosition(userColorString);
console.log('userColorString', userColorString, 'position', JSON.stringify(position, null, 2));
}
console.log('----------------------------------');
}

async function createConnectHandlers() {
node.addCustomGroupMessageHandler(topologyObject.id, (e) => {
if (topologyObject)
objectPeers = node.networkNode.getGroupPeers(topologyObject.id);
render();
});

node.objectStore.subscribe(topologyObject.id, (_, obj) => {
render();
});
}

async function main() {
await node.start();
render();

node.addCustomGroupMessageHandler("", (e) => {
peers = node.networkNode.getAllPeers();
discoveryPeers = node.networkNode.getGroupPeers("topology::discovery");
render();
});

const button_create = <HTMLButtonElement>(
document.getElementById("createGrid")
);
button_create.addEventListener("click", async () => {
topologyObject = await node.createObject(new Grid());
gridCRO = topologyObject.cro as Grid;
createConnectHandlers();
await addUser();
render();
});

const button_connect = <HTMLButtonElement>document.getElementById("joinGrid");
button_connect.addEventListener("click", async () => {
const croId = (<HTMLInputElement>document.getElementById("gridInput"))
.value;
try {
topologyObject = await node.createObject(
new Grid(),
croId,
undefined,
true,
);
gridCRO = topologyObject.cro as Grid;
createConnectHandlers();
await addUser();
render();
console.log("Succeeded in connecting with CRO", croId);
} catch (e) {
console.error("Error while connecting with CRO", croId, e);
}
});

document.addEventListener("keydown", (event) => {
if (event.key === "w") moveUser("U");
if (event.key === "a") moveUser("L");
if (event.key === "s") moveUser("D");
if (event.key === "d") moveUser("R");
});
}

main();
Loading
Loading