From 739390d7f5b8c1c7fa820a0753afc7bb611ca48c Mon Sep 17 00:00:00 2001 From: ari melody Date: Fri, 14 Mar 2025 00:33:59 +0000 Subject: [PATCH 1/5] funny cursor teehee --- public/script/cursor.js | 273 ++++++++++++++++++++++++++++++++++++++++ public/script/main.js | 1 + public/style/cursor.css | 43 +++++++ public/style/main.css | 1 + 4 files changed, 318 insertions(+) create mode 100644 public/script/cursor.js create mode 100644 public/style/cursor.css diff --git a/public/script/cursor.js b/public/script/cursor.js new file mode 100644 index 0000000..94f1a8e --- /dev/null +++ b/public/script/cursor.js @@ -0,0 +1,273 @@ +const CURSOR_TICK_RATE = 1000/30; +const CURSOR_LERP_RATE = 1/100; +const CURSOR_CHAR_MAX_LIFE = 5000; +const CURSOR_MAX_CHARS = 50; +/** @type HTMLElement */ +let cursorContainer; +/** @type Cursor */ +let myCursor; +/** @type Map */ +let cursors = new Map(); +/** @type Array */ +let chars = new Array(); + +let lastCursorUpdateTime = 0; +let lastCharUpdateTime = 0; + +class Cursor { + /** @type number */ id; + + // real coordinates (canonical) + /** @type number */ x; + /** @type number */ y; + + // update coordinates (interpolated) + /** @type number */ rx; + /** @type number */ ry; + + /** @type HTMLElement */ + #element; + /** @type HTMLElement */ + #char; + + /** + * @param {number} id + * @param {number} x + * @param {number} y + */ + constructor(id, x, y) { + this.id = id; + this.x = x; + this.y = y; + this.rx = x; + this.ry = y; + + const element = document.createElement("i"); + element.classList.add("cursor"); + element.id = "cursor" + id; + const colour = randomColour(); + element.style.borderColor = colour; + element.style.color = colour; + element.innerText = "0x" + navigator.userAgent.hashCode(); + + const char = document.createElement("p"); + char.className = "char"; + element.appendChild(char); + + this.#element = element; + this.#char = char; + cursorContainer.appendChild(this.#element); + } + + destroy() { + this.#element.remove(); + } + + /** + * @param {number} x + * @param {number} y + */ + move(x, y) { + this.x = x; + this.y = y; + } + + /** + * @param {number} deltaTime + */ + update(deltaTime) { + this.rx += (this.x - this.rx) * CURSOR_LERP_RATE * deltaTime; + this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime; + this.#element.style.left = this.rx + "px"; + this.#element.style.top = this.ry + "px"; + } + + /** + * @param {string} text + */ + print(text) { + if (text.length > 1) return; + this.#char.innerText = text; + } +} + +class FunChar { + /** @type number */ x; y; + /** @type number */ xa; ya; + /** @type number */ r; ra; + /** @type HTMLElement */ element; + /** @type number */ life; + + /** + * @param {number} x + * @param {number} y + * @param {number} xa + * @param {number} ya + * @param {string} text + */ + constructor(x, y, xa, ya, text) { + this.x = x; + this.y = y; + this.xa = xa + Math.random() * .2 - .1; + this.ya = ya + Math.random() * -.25; + this.r = this.xa * 100; + this.ra = this.r * 0.01; + this.life = 0; + + const char = document.createElement("i"); + char.className = "funchar"; + char.innerText = text; + char.style.left = x + "px"; + char.style.top = y + "px"; + char.style.transform = `rotate(${this.r}deg)`; + this.element = char; + cursorContainer.appendChild(this.element); + } + + /** + * @param {number} deltaTime + */ + update(deltaTime) { + this.life += deltaTime; + if (this.life > CURSOR_CHAR_MAX_LIFE || + this.y > window.outerHeight || + this.x < 0 || + this.x > window.outerWidth + ) { + this.destroy(); + return; + } + + this.x += this.xa * deltaTime; + this.y += this.ya * deltaTime; + this.r += this.ra * deltaTime; + this.ya = Math.min(this.ya + 0.0005 * deltaTime, 10); + + this.element.style.left = this.x + "px"; + this.element.style.top = this.y + "px"; + this.element.style.transform = `rotate(${this.r}deg)`; + } + + destroy() { + chars = chars.filter(char => char !== this); + this.element.remove(); + } +} + +String.prototype.hashCode = function() { + var hash = 0; + if (this.length === 0) return hash; + for (let i = 0; i < this.length; i++) { + const chr = this.charCodeAt(i); + hash = ((hash << 5) - hash) + chr; + hash |= 0; // convert to 32-bit integer + } + return Math.round(Math.abs(hash)).toString(16).slice(0, 8).padStart(8, '0'); +}; + +/** + * @returns string + */ +function randomColour() { + const min = 128; + const range = 100; + const red = Math.round((min + Math.random() * range)).toString(16); + const green = Math.round((min + Math.random() * range)).toString(16); + const blue = Math.round((min + Math.random() * range)).toString(16); + + return "#" + red + green + blue; +} + +/** + * @param {MouseEvent} event + */ +function handleMouseMove(event) { + if (!myCursor) return; + myCursor.move(event.x, event.y); +} + +/** + * @param {KeyboardEvent} event + */ +function handleKeyDown(event) { + if (event.key.length > 1) return; + if (event.metaKey || event.ctrlKey) return; + if (window.cursorFunMode === true) { + const yOffset = -20; + const accelMultiplier = 0.002; + if (chars.length < CURSOR_MAX_CHARS) + chars.push(new FunChar( + myCursor.x, myCursor.y + yOffset, + (myCursor.x - myCursor.rx) * accelMultiplier, (myCursor.y - myCursor.ry) * accelMultiplier, + event.key)); + } else { + myCursor.print(event.key); + } +} + +function handleKeyUp() { + if (!window.cursorFunMode) { + myCursor.print(""); + } +} + +/** + * @param {number} time + */ +function updateCursors(time) { + const deltaTime = time - lastCursorUpdateTime; + + cursors.forEach(cursor => { + cursor.update(deltaTime); + }); + + lastCursorUpdateTime = time; + requestAnimationFrame(updateCursors); +} + +/** + * @param {number} time + */ +function updateChars(time) { + const deltaTime = time - lastCharUpdateTime; + + chars.forEach(char => { + char.update(deltaTime); + }); + + lastCharUpdateTime = time; + requestAnimationFrame(updateChars); +} + +function cursorSetup() { + window.cursorFunMode = false; + cursorContainer = document.createElement("div"); + cursorContainer.id = "cursors"; + document.body.appendChild(cursorContainer); + myCursor = new Cursor(0, window.innerWidth / 2, window.innerHeight / 2); + cursors.set(0, myCursor); + document.addEventListener("mousemove", handleMouseMove); + document.addEventListener("keydown", handleKeyDown); + document.addEventListener("keyup", handleKeyUp); + requestAnimationFrame(updateCursors); + requestAnimationFrame(updateChars); + console.debug(`Cursor tracking @ ${window.location.pathname}`); +} + +function cursorDestroy() { + document.removeEventListener("mousemove", handleMouseMove); + document.removeEventListener("keydown", handleKeyDown); + document.removeEventListener("keyup", handleKeyUp); + cursors.forEach(cursor => { + cursor.destroy(); + }); + cursors.clear(); + chars.forEach(cursor => { + cursor.destroy(); + }); + chars = new Array(); + myCursor = null; + console.debug(`Cursor no longer tracking.`); +} + +cursorSetup(); diff --git a/public/script/main.js b/public/script/main.js index 95023e5..c1d5101 100644 --- a/public/script/main.js +++ b/public/script/main.js @@ -1,5 +1,6 @@ import "./header.js"; import "./config.js"; +import "./cursor.js"; function type_out(e) { const text = e.innerText; diff --git a/public/style/cursor.css b/public/style/cursor.css new file mode 100644 index 0000000..477e525 --- /dev/null +++ b/public/style/cursor.css @@ -0,0 +1,43 @@ +#cursors i.cursor { + position: fixed; + padding: 4px; + + display: block; + z-index: 1000; + + background: #0008; + border: 2px solid #808080; + border-radius: 2px; + + font-style: normal; + font-size: 10px; + font-weight: bold; + white-space: nowrap; + + user-select: none; + pointer-events: none; +} + +#cursors i.cursor .char { + position: absolute; + transform: translateY(-44px); + margin: 0; + font-size: 20px; + color: var(--on-background); +} + +#cursors .funchar { + position: fixed; + margin: 0; + + display: block; + z-index: 1000; + + font-style: normal; + font-size: 20px; + font-weight: bold; + color: var(--on-background); + + user-select: none; + pointer-events: none; +} diff --git a/public/style/main.css b/public/style/main.css index f7f2131..4e9e113 100644 --- a/public/style/main.css +++ b/public/style/main.css @@ -2,6 +2,7 @@ @import url("/style/header.css"); @import url("/style/footer.css"); @import url("/style/prideflag.css"); +@import url("/style/cursor.css"); @font-face { font-family: "Monaspace Argon"; From a797e82a6814fb285cd6ad5ca71cfdee9807032d Mon Sep 17 00:00:00 2001 From: ari melody Date: Fri, 14 Mar 2025 16:26:30 +0000 Subject: [PATCH 2/5] waow i really like doing config overhauls don't i + cursor improvements --- public/script/config.js | 122 ++++++++++++++++++++++++++++++++-------- public/script/cursor.js | 122 ++++++++++++++++++++++++++++------------ public/style/cursor.css | 26 ++++++++- 3 files changed, 208 insertions(+), 62 deletions(-) diff --git a/public/script/config.js b/public/script/config.js index 2bb33a6..1ab8b5a 100644 --- a/public/script/config.js +++ b/public/script/config.js @@ -1,33 +1,107 @@ -const DEFAULT_CONFIG = { - crt: false -}; -const config = (() => { - let saved = localStorage.getItem("config"); - if (saved) { - const config = JSON.parse(saved); - setCRT(config.crt || DEFAULT_CONFIG.crt); - return config; +const ARIMELODY_CONFIG_NAME = "arimelody.me-config"; + +class Config { + _crt = false; + _cursor = false; + _cursorFunMode = false; + + /** @type Map> */ + #listeners = new Map(); + + constructor(values) { + function thisOrElse(values, name, defaultValue) { + if (values === null) return defaultValue; + if (values[name] === undefined) return defaultValue; + return values[name]; + } + + this.#listeners.set('crt', new Array()); + this.crt = thisOrElse(values, 'crt', false); + this.#listeners.set('cursor', new Array()); + this.cursor = thisOrElse(values, 'cursor', false); + this.#listeners.set('cursorFunMode', new Array()); + this.cursorFunMode = thisOrElse(values, 'cursorFunMode', false); + this.save(); } - localStorage.setItem("config", JSON.stringify(DEFAULT_CONFIG)); - return DEFAULT_CONFIG; -})(); + /** + * Appends a listener function to be called when the config value of `name` + * is changed. + */ + addListener(name, callback) { + const callbacks = this.#listeners.get(name); + if (!callbacks) return; + callbacks.push(callback); + } -function saveConfig() { - localStorage.setItem("config", JSON.stringify(config)); + /** + * Removes the listener function `callback` from the list of callbacks when + * the config value of `name` is changed. + */ + removeListener(name, callback) { + const callbacks = this.#listeners.get(name); + if (!callbacks) return; + callbacks.set(name, callbacks.filter(c => c !== callback)); + } + + save() { + localStorage.setItem(ARIMELODY_CONFIG_NAME, JSON.stringify({ + crt: this.crt, + cursor: this.cursor, + cursorFunMode: this.cursorFunMode + })); + } + + get crt() { return this._crt } + set crt(/** @type boolean */ enabled) { + this._crt = enabled; + + if (enabled) { + document.body.classList.add("crt"); + } else { + document.body.classList.remove("crt"); + } + document.getElementById('toggle-crt').className = enabled ? "" : "disabled"; + + this.#listeners.get('crt').forEach(callback => { + callback(this._crt); + }) + + this.save(); + } + + get cursor() { return this._cursor } + set cursor(/** @type boolean */ value) { + this._cursor = value; + this.#listeners.get('cursor').forEach(callback => { + callback(this._cursor); + }) + this.save(); + } + + get cursorFunMode() { return this._cursorFunMode } + set cursorFunMode(/** @type boolean */ value) { + this._cursorFunMode = value; + this.#listeners.get('cursorFunMode').forEach(callback => { + callback(this._cursorFunMode); + }) + this.save(); + } } +const config = (() => { + let values = null; + + const saved = localStorage.getItem(ARIMELODY_CONFIG_NAME); + if (saved) + values = JSON.parse(saved); + + return new Config(values); +})(); + document.getElementById("toggle-crt").addEventListener("click", () => { config.crt = !config.crt; - setCRT(config.crt); - saveConfig(); }); -function setCRT(/** @type boolean */ enabled) { - if (enabled) { - document.body.classList.add("crt"); - } else { - document.body.classList.remove("crt"); - } - document.getElementById('toggle-crt').className = enabled ? "" : "disabled"; -} +window.config = config; +export default config; diff --git a/public/script/cursor.js b/public/script/cursor.js index 94f1a8e..a1df6bb 100644 --- a/public/script/cursor.js +++ b/public/script/cursor.js @@ -1,7 +1,10 @@ +import config from './config.js'; + const CURSOR_TICK_RATE = 1000/30; const CURSOR_LERP_RATE = 1/100; const CURSOR_CHAR_MAX_LIFE = 5000; const CURSOR_MAX_CHARS = 50; + /** @type HTMLElement */ let cursorContainer; /** @type Cursor */ @@ -11,6 +14,7 @@ let cursors = new Map(); /** @type Array */ let chars = new Array(); +let running = false; let lastCursorUpdateTime = 0; let lastCharUpdateTime = 0; @@ -42,16 +46,16 @@ class Cursor { this.rx = x; this.ry = y; - const element = document.createElement("i"); - element.classList.add("cursor"); - element.id = "cursor" + id; + const element = document.createElement('i'); + element.classList.add('cursor'); + element.id = 'cursor' + id; const colour = randomColour(); element.style.borderColor = colour; element.style.color = colour; - element.innerText = "0x" + navigator.userAgent.hashCode(); + element.innerText = '0x' + navigator.userAgent.hashCode(); - const char = document.createElement("p"); - char.className = "char"; + const char = document.createElement('p'); + char.className = 'char'; element.appendChild(char); this.#element = element; @@ -61,6 +65,7 @@ class Cursor { destroy() { this.#element.remove(); + this.#char.remove(); } /** @@ -78,8 +83,8 @@ class Cursor { update(deltaTime) { this.rx += (this.x - this.rx) * CURSOR_LERP_RATE * deltaTime; this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime; - this.#element.style.left = this.rx + "px"; - this.#element.style.top = this.ry + "px"; + this.#element.style.left = this.rx + 'px'; + this.#element.style.top = this.ry + 'px'; } /** @@ -89,6 +94,16 @@ class Cursor { if (text.length > 1) return; this.#char.innerText = text; } + + /** + * @param {boolean} active + */ + click(active) { + if (active) + this.#element.classList.add('click'); + else + this.#element.classList.remove('click'); + } } class FunChar { @@ -114,11 +129,11 @@ class FunChar { this.ra = this.r * 0.01; this.life = 0; - const char = document.createElement("i"); - char.className = "funchar"; + const char = document.createElement('i'); + char.className = 'funchar'; char.innerText = text; - char.style.left = x + "px"; - char.style.top = y + "px"; + char.style.left = x + 'px'; + char.style.top = y + 'px'; char.style.transform = `rotate(${this.r}deg)`; this.element = char; cursorContainer.appendChild(this.element); @@ -130,9 +145,9 @@ class FunChar { update(deltaTime) { this.life += deltaTime; if (this.life > CURSOR_CHAR_MAX_LIFE || - this.y > window.outerHeight || + this.y > document.body.clientHeight || this.x < 0 || - this.x > window.outerWidth + this.x > document.body.clientWidth ) { this.destroy(); return; @@ -143,8 +158,8 @@ class FunChar { this.r += this.ra * deltaTime; this.ya = Math.min(this.ya + 0.0005 * deltaTime, 10); - this.element.style.left = this.x + "px"; - this.element.style.top = this.y + "px"; + this.element.style.left = (this.x - window.scrollX) + 'px'; + this.element.style.top = (this.y - window.scrollY) + 'px'; this.element.style.transform = `rotate(${this.r}deg)`; } @@ -175,7 +190,7 @@ function randomColour() { const green = Math.round((min + Math.random() * range)).toString(16); const blue = Math.round((min + Math.random() * range)).toString(16); - return "#" + red + green + blue; + return '#' + red + green + blue; } /** @@ -186,18 +201,25 @@ function handleMouseMove(event) { myCursor.move(event.x, event.y); } +function handleMouseDown() { + myCursor.click(true); +} +function handleMouseUp() { + myCursor.click(false); +} + /** * @param {KeyboardEvent} event */ function handleKeyDown(event) { if (event.key.length > 1) return; if (event.metaKey || event.ctrlKey) return; - if (window.cursorFunMode === true) { + if (config.cursorFunMode === true) { const yOffset = -20; const accelMultiplier = 0.002; if (chars.length < CURSOR_MAX_CHARS) chars.push(new FunChar( - myCursor.x, myCursor.y + yOffset, + myCursor.x + window.scrollX, myCursor.y + window.scrollY + yOffset, (myCursor.x - myCursor.rx) * accelMultiplier, (myCursor.y - myCursor.ry) * accelMultiplier, event.key)); } else { @@ -206,8 +228,8 @@ function handleKeyDown(event) { } function handleKeyUp() { - if (!window.cursorFunMode) { - myCursor.print(""); + if (!config.cursorFunMode) { + myCursor.print(''); } } @@ -215,6 +237,8 @@ function handleKeyUp() { * @param {number} time */ function updateCursors(time) { + if (!running) return; + const deltaTime = time - lastCursorUpdateTime; cursors.forEach(cursor => { @@ -229,6 +253,8 @@ function updateCursors(time) { * @param {number} time */ function updateChars(time) { + if (!running) return; + const deltaTime = time - lastCharUpdateTime; chars.forEach(char => { @@ -240,34 +266,60 @@ function updateChars(time) { } function cursorSetup() { - window.cursorFunMode = false; - cursorContainer = document.createElement("div"); - cursorContainer.id = "cursors"; + if (running) throw new Error('Only one instance of Cursor can run at a time.'); + running = true; + + cursorContainer = document.createElement('div'); + cursorContainer.id = 'cursors'; document.body.appendChild(cursorContainer); + myCursor = new Cursor(0, window.innerWidth / 2, window.innerHeight / 2); cursors.set(0, myCursor); - document.addEventListener("mousemove", handleMouseMove); - document.addEventListener("keydown", handleKeyDown); - document.addEventListener("keyup", handleKeyUp); + + document.addEventListener('mousemove', handleMouseMove); + document.addEventListener('mousedown', handleMouseDown); + document.addEventListener('mouseup', handleMouseUp); + document.addEventListener('keydown', handleKeyDown); + document.addEventListener('keyup', handleKeyUp); + requestAnimationFrame(updateCursors); requestAnimationFrame(updateChars); + console.debug(`Cursor tracking @ ${window.location.pathname}`); } function cursorDestroy() { - document.removeEventListener("mousemove", handleMouseMove); - document.removeEventListener("keydown", handleKeyDown); - document.removeEventListener("keyup", handleKeyUp); + if (!running) return; + + document.removeEventListener('mousemove', handleMouseMove); + document.removeEventListener('mousedown', handleMouseDown); + document.removeEventListener('mouseup', handleMouseUp); + document.removeEventListener('keydown', handleKeyDown); + document.removeEventListener('keyup', handleKeyUp); + + chars.forEach(char => { + char.destroy(); + }); + chars = new Array(); cursors.forEach(cursor => { cursor.destroy(); }); cursors.clear(); - chars.forEach(cursor => { - cursor.destroy(); - }); - chars = new Array(); myCursor = null; + + cursorContainer.remove(); + console.debug(`Cursor no longer tracking.`); + running = false; } -cursorSetup(); +if (config.cursor === true) { + cursorSetup(); +} + +config.addListener('cursor', enabled => { + if (enabled === true) + cursorSetup(); + else + cursorDestroy(); +}); diff --git a/public/style/cursor.css b/public/style/cursor.css index 477e525..e53cee5 100644 --- a/public/style/cursor.css +++ b/public/style/cursor.css @@ -13,9 +13,11 @@ font-size: 10px; font-weight: bold; white-space: nowrap; +} - user-select: none; - pointer-events: none; +#cursors i.cursor.click { + color: var(--on-background) !important; + border-color: var(--on-background) !important; } #cursors i.cursor .char { @@ -27,7 +29,7 @@ } #cursors .funchar { - position: fixed; + position: absolute; margin: 0; display: block; @@ -37,7 +39,25 @@ font-size: 20px; font-weight: bold; color: var(--on-background); +} + +#cursors { + width: 100vw; + height: 100vh; + position: fixed; + top: 0; + left: 0; + + z-index: 1000; + overflow: clip; user-select: none; pointer-events: none; } + +@media (prefers-color-scheme: light) { + #cursors i.cursor { + filter: saturate(5) brightness(0.8); + background: #fff8; + } +} From 4b3c8f94497c6a5d5e5e5e73e128326736cefd1d Mon Sep 17 00:00:00 2001 From: ari melody Date: Fri, 14 Mar 2025 20:42:44 +0000 Subject: [PATCH 3/5] lol cursor is multiplayer now --- cursor/cursor.go | 189 ++++++++++++++++++++++++++++++ go.mod | 1 + go.sum | 2 + log/log.go | 1 + main.go | 16 ++- public/script/cursor.js | 253 ++++++++++++++++++++++++---------------- public/style/cursor.css | 7 +- 7 files changed, 362 insertions(+), 107 deletions(-) create mode 100644 cursor/cursor.go diff --git a/cursor/cursor.go b/cursor/cursor.go new file mode 100644 index 0000000..a74c998 --- /dev/null +++ b/cursor/cursor.go @@ -0,0 +1,189 @@ +package cursor + +import ( + "arimelody-web/model" + "fmt" + "math/rand" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/gorilla/websocket" +) + +type CursorClient struct { + ID int32 + Conn *websocket.Conn + Route string + X int16 + Y int16 + Disconnected bool +} + +type CursorMessage struct { + Data []byte + Route string + Exclude []*CursorClient +} + +func (client *CursorClient) Send(data []byte) { + err := client.Conn.WriteMessage(websocket.TextMessage, data) + if err != nil { + client.Disconnect() + } +} + +func (client *CursorClient) Disconnect() { + client.Disconnected = true + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("leave:%d", client.ID)), + client.Route, + []*CursorClient{}, + } +} + +var clients = make(map[int32]*CursorClient) +var broadcast = make(chan CursorMessage) +var mutex = &sync.Mutex{} + +func StartCursor(app *model.AppState) { + var includes = func (clients []*CursorClient, client *CursorClient) bool { + for _, c := range clients { + if c.ID == client.ID { return true } + } + return false + } + + log("Cursor message handler ready!") + + for { + message := <-broadcast + mutex.Lock() + for _, client := range clients { + if client.Route != message.Route { continue } + if includes(message.Exclude, client) { continue } + client.Send(message.Data) + } + mutex.Unlock() + } +} + +func handleClient(client *CursorClient) { + msgType, message, err := client.Conn.ReadMessage() + if err != nil { + client.Disconnect() + return + } + if msgType != websocket.TextMessage { return } + + args := strings.Split(string(message), ":") + if len(args) == 0 { return } + switch args[0] { + case "loc": + if len(args) < 2 { return } + + client.Route = args[1] + + mutex.Lock() + for _, otherClient := range clients { + if otherClient.ID == client.ID { continue } + if otherClient.Route != client.Route { continue } + client.Send([]byte(fmt.Sprintf("join:%d", otherClient.ID))) + client.Send([]byte(fmt.Sprintf("pos:%d:%d:%d", otherClient.ID, otherClient.X, otherClient.Y))) + } + mutex.Unlock() + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("join:%d", client.ID)), + client.Route, + []*CursorClient{ client }, + } + case "char": + if len(args) < 2 { return } + // haha, turns out using ':' as a separator means you can't type ':'s + // i should really be writing byte packets, not this nonsense + msg := byte(':') + if len(args[1]) > 0 { + msg = args[1][0] + } + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("char:%d:%c", client.ID, msg)), + client.Route, + []*CursorClient{ client }, + } + case "nochar": + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("nochar:%d", client.ID)), + client.Route, + []*CursorClient{ client }, + } + case "pos": + if len(args) < 3 { return } + x, err := strconv.ParseInt(args[1], 10, 32) + y, err := strconv.ParseInt(args[2], 10, 32) + if err != nil { return } + client.X = int16(x) + client.Y = int16(y) + broadcast <- CursorMessage{ + []byte(fmt.Sprintf("pos:%d:%d:%d", client.ID, client.X, client.Y)), + client.Route, + []*CursorClient{ client }, + } + } +} + +func Handler(app *model.AppState) http.HandlerFunc { + var upgrader = websocket.Upgrader{ + CheckOrigin: func (r *http.Request) bool { + origin := r.Header.Get("Origin") + return origin == app.Config.BaseUrl + }, + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := upgrader.Upgrade(w, r, nil) + if err != nil { + log("Failed to upgrade to WebSocket connection: %v\n", err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } + defer conn.Close() + + client := CursorClient{ + ID: rand.Int31(), + Conn: conn, + X: 0.0, + Y: 0.0, + Disconnected: false, + } + + err = client.Conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("id:%d", client.ID))) + if err != nil { + client.Conn.Close() + return + } + + mutex.Lock() + clients[client.ID] = &client + mutex.Unlock() + + // log("Client connected: %s (%s)", fmt.Sprintf("0x%08x", client.ID), client.Conn.RemoteAddr().String()) + + for { + if client.Disconnected { + mutex.Lock() + delete(clients, client.ID) + client.Conn.Close() + mutex.Unlock() + return + } + handleClient(&client) + } + }) +} + +func log(format string, args ...any) { + logString := fmt.Sprintf(format, args...) + fmt.Printf("[%s] [CURSOR] %s\n", time.Now().Format(time.UnixDate), logString) +} diff --git a/go.mod b/go.mod index f8717a2..a1c6c76 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ require ( require golang.org/x/crypto v0.27.0 // indirect require ( + github.com/gorilla/websocket v1.5.3 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect ) diff --git a/go.sum b/go.sum index 15259a1..f2ec7e7 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= diff --git a/log/log.go b/log/log.go index 3d023ab..2d1c0c2 100644 --- a/log/log.go +++ b/log/log.go @@ -30,6 +30,7 @@ const ( TYPE_ARTWORK string = "artwork" TYPE_FILES string = "files" TYPE_MISC string = "misc" + TYPE_CURSOR string = "cursor" ) type LogLevel int diff --git a/main.go b/main.go index 03e9d77..2252622 100644 --- a/main.go +++ b/main.go @@ -1,11 +1,13 @@ package main import ( + "bufio" "errors" "fmt" stdLog "log" "math" "math/rand" + "net" "net/http" "os" "path/filepath" @@ -17,9 +19,10 @@ import ( "arimelody-web/api" "arimelody-web/colour" "arimelody-web/controller" + "arimelody-web/cursor" + "arimelody-web/log" "arimelody-web/model" "arimelody-web/templates" - "arimelody-web/log" "arimelody-web/view" "github.com/jmoiron/sqlx" @@ -428,6 +431,8 @@ func main() { os.Exit(1) } + go cursor.StartCursor(&app) + // start the web server! mux := createServeMux(&app) fmt.Printf("Now serving at http://%s:%d\n", app.Config.Host, app.Config.Port) @@ -444,6 +449,7 @@ func createServeMux(app *model.AppState) *http.ServeMux { mux.Handle("/api/", http.StripPrefix("/api", api.Handler(app))) mux.Handle("/music/", http.StripPrefix("/music", view.MusicHandler(app))) mux.Handle("/uploads/", http.StripPrefix("/uploads", staticHandler(filepath.Join(app.Config.DataDirectory, "uploads")))) + mux.Handle("/cursor-ws", cursor.Handler(app)) mux.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodHead { w.WriteHeader(http.StatusOK) @@ -536,6 +542,14 @@ type LoggingResponseWriter struct { Status int } +func (lrw *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + hijack, ok := lrw.ResponseWriter.(http.Hijacker) + if !ok { + return nil, nil, errors.New("Server does not support hijacking\n") + } + return hijack.Hijack() +} + func (lrw *LoggingResponseWriter) WriteHeader(status int) { lrw.Status = status lrw.ResponseWriter.WriteHeader(status) diff --git a/public/script/cursor.js b/public/script/cursor.js index a1df6bb..059a2bd 100644 --- a/public/script/cursor.js +++ b/public/script/cursor.js @@ -2,8 +2,9 @@ import config from './config.js'; const CURSOR_TICK_RATE = 1000/30; const CURSOR_LERP_RATE = 1/100; +const CURSOR_FUNCHAR_RATE = 20; const CURSOR_CHAR_MAX_LIFE = 5000; -const CURSOR_MAX_CHARS = 50; +const CURSOR_MAX_CHARS = 64; /** @type HTMLElement */ let cursorContainer; @@ -11,61 +12,57 @@ let cursorContainer; let myCursor; /** @type Map */ let cursors = new Map(); -/** @type Array */ -let chars = new Array(); + +/** @type WebSocket */ +let ws; let running = false; -let lastCursorUpdateTime = 0; -let lastCharUpdateTime = 0; +let lastUpdate = 0; class Cursor { - /** @type number */ id; - - // real coordinates (canonical) - /** @type number */ x; - /** @type number */ y; - - // update coordinates (interpolated) - /** @type number */ rx; - /** @type number */ ry; - /** @type HTMLElement */ #element; /** @type HTMLElement */ - #char; + #charElement; + #funCharCooldown = CURSOR_FUNCHAR_RATE; /** - * @param {number} id + * @param {string} id * @param {number} x * @param {number} y */ constructor(id, x, y) { - this.id = id; + // real coordinates (canonical) this.x = x; this.y = y; + // render coordinates (interpolated) this.rx = x; this.ry = y; + this.msg = ''; + this.funChars = new Array(); const element = document.createElement('i'); element.classList.add('cursor'); - element.id = 'cursor' + id; const colour = randomColour(); element.style.borderColor = colour; element.style.color = colour; - element.innerText = '0x' + navigator.userAgent.hashCode(); - - const char = document.createElement('p'); - char.className = 'char'; - element.appendChild(char); - + cursorContainer.appendChild(element); this.#element = element; - this.#char = char; - cursorContainer.appendChild(this.#element); + + const char = document.createElement('i'); + char.className = 'char'; + cursorContainer.appendChild(char); + this.#charElement = char; + + this.setID(id); } destroy() { this.#element.remove(); - this.#char.remove(); + this.#charElement.remove(); + this.funChars.forEach(char => { + char.destroy(); + }); } /** @@ -85,14 +82,52 @@ class Cursor { this.ry += (this.y - this.ry) * CURSOR_LERP_RATE * deltaTime; this.#element.style.left = this.rx + 'px'; this.#element.style.top = this.ry + 'px'; + this.#charElement.style.left = this.rx + 'px'; + this.#charElement.style.top = (this.ry - 24) + 'px'; + + if (this.#funCharCooldown > 0) + this.#funCharCooldown -= deltaTime; + + if (this.msg.length > 0) { + if (config.cursorFunMode === true) { + if (this.#funCharCooldown <= 0) { + this.#funCharCooldown = CURSOR_FUNCHAR_RATE; + if (this.funChars.length >= CURSOR_MAX_CHARS) { + const char = this.funChars.shift(); + char.destroy(); + } + const yOffset = -20; + const accelMultiplier = 0.002; + this.funChars.push(new FunChar( + this.x + window.scrollX, this.y + window.scrollY + yOffset, + (this.x - this.rx) * accelMultiplier, (this.y - this.ry) * accelMultiplier, + this.msg)); + } + } else { + this.#charElement.innerText = this.msg; + } + } else { + this.#charElement.innerText = ''; + } + + this.funChars.forEach(char => { + if (char.life > CURSOR_CHAR_MAX_LIFE || + char.y > document.body.clientHeight || + char.x < 0 || + char.x > document.body.clientWidth + ) { + this.funChars = this.funChars.filter(c => c !== this); + char.destroy(); + return; + } + char.update(deltaTime); + }); } - /** - * @param {string} text - */ - print(text) { - if (text.length > 1) return; - this.#char.innerText = text; + setID(id) { + this.id = id; + this.#element.id = 'cursor' + id; + this.#element.innerText = '0x' + id.toString(16).slice(0, 8).padStart(8, '0'); } /** @@ -107,12 +142,6 @@ class Cursor { } class FunChar { - /** @type number */ x; y; - /** @type number */ xa; ya; - /** @type number */ r; ra; - /** @type HTMLElement */ element; - /** @type number */ life; - /** * @param {number} x * @param {number} y @@ -144,14 +173,6 @@ class FunChar { */ update(deltaTime) { this.life += deltaTime; - if (this.life > CURSOR_CHAR_MAX_LIFE || - this.y > document.body.clientHeight || - this.x < 0 || - this.x > document.body.clientWidth - ) { - this.destroy(); - return; - } this.x += this.xa * deltaTime; this.y += this.ya * deltaTime; @@ -164,22 +185,10 @@ class FunChar { } destroy() { - chars = chars.filter(char => char !== this); this.element.remove(); } } -String.prototype.hashCode = function() { - var hash = 0; - if (this.length === 0) return hash; - for (let i = 0; i < this.length; i++) { - const chr = this.charCodeAt(i); - hash = ((hash << 5) - hash) + chr; - hash |= 0; // convert to 32-bit integer - } - return Math.round(Math.abs(hash)).toString(16).slice(0, 8).padStart(8, '0'); -}; - /** * @returns string */ @@ -198,6 +207,8 @@ function randomColour() { */ function handleMouseMove(event) { if (!myCursor) return; + if (ws && ws.readyState == WebSocket.OPEN) + ws.send(`pos:${event.x}:${event.y}`); myCursor.move(event.x, event.y); } @@ -211,26 +222,19 @@ function handleMouseUp() { /** * @param {KeyboardEvent} event */ -function handleKeyDown(event) { +function handleKeyPress(event) { if (event.key.length > 1) return; if (event.metaKey || event.ctrlKey) return; - if (config.cursorFunMode === true) { - const yOffset = -20; - const accelMultiplier = 0.002; - if (chars.length < CURSOR_MAX_CHARS) - chars.push(new FunChar( - myCursor.x + window.scrollX, myCursor.y + window.scrollY + yOffset, - (myCursor.x - myCursor.rx) * accelMultiplier, (myCursor.y - myCursor.ry) * accelMultiplier, - event.key)); - } else { - myCursor.print(event.key); - } + if (myCursor.msg === event.key) return; + if (ws && ws.readyState == WebSocket.OPEN) + ws.send(`char:${event.key}`); + myCursor.msg = event.key; } function handleKeyUp() { - if (!config.cursorFunMode) { - myCursor.print(''); - } + if (ws && ws.readyState == WebSocket.OPEN) + ws.send(`nochar`); + myCursor.msg = ''; } /** @@ -239,32 +243,16 @@ function handleKeyUp() { function updateCursors(time) { if (!running) return; - const deltaTime = time - lastCursorUpdateTime; + const deltaTime = time - lastUpdate; cursors.forEach(cursor => { cursor.update(deltaTime); }); - lastCursorUpdateTime = time; + lastUpdate = time; requestAnimationFrame(updateCursors); } -/** - * @param {number} time - */ -function updateChars(time) { - if (!running) return; - - const deltaTime = time - lastCharUpdateTime; - - chars.forEach(char => { - char.update(deltaTime); - }); - - lastCharUpdateTime = time; - requestAnimationFrame(updateChars); -} - function cursorSetup() { if (running) throw new Error('Only one instance of Cursor can run at a time.'); running = true; @@ -273,19 +261,82 @@ function cursorSetup() { cursorContainer.id = 'cursors'; document.body.appendChild(cursorContainer); - myCursor = new Cursor(0, window.innerWidth / 2, window.innerHeight / 2); + myCursor = new Cursor("You!", window.innerWidth / 2, window.innerHeight / 2); cursors.set(0, myCursor); document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mousedown', handleMouseDown); document.addEventListener('mouseup', handleMouseUp); - document.addEventListener('keydown', handleKeyDown); + document.addEventListener('keypress', handleKeyPress); document.addEventListener('keyup', handleKeyUp); requestAnimationFrame(updateCursors); - requestAnimationFrame(updateChars); - console.debug(`Cursor tracking @ ${window.location.pathname}`); + ws = new WebSocket("/cursor-ws"); + + ws.addEventListener("open", () => { + console.log("Cursor connected to server successfully."); + + ws.send(`loc:${window.location.pathname}`); + }); + ws.addEventListener("error", error => { + console.error("Cursor WebSocket error:", error); + }); + ws.addEventListener("close", () => { + console.log("Cursor connection closed."); + }); + + ws.addEventListener("message", event => { + const args = String(event.data).split(":"); + if (args.length == 0) return; + + let id = 0; + /** @type Cursor */ + let cursor; + if (args.length > 1) { + id = Number(args[1]); + cursor = cursors.get(id); + } + + switch (args[0]) { + case 'id': { + myCursor.setID(Number(args[1])); + break; + } + case 'join': { + if (id === myCursor.id) break; + cursors.set(id, new Cursor(id, 0, 0)); + break; + } + case 'leave': { + if (!cursor || cursor === myCursor) break; + cursors.get(id).destroy(); + cursors.delete(id); + break; + } + case 'char': { + if (!cursor || cursor === myCursor) break; + cursor.msg = args[2]; + break; + } + case 'nochar': { + if (!cursor || cursor === myCursor) break; + cursor.msg = ''; + break; + } + case 'pos': { + if (!cursor || cursor === myCursor) break; + cursor.move(Number(args[2]), Number(args[3])); + break; + } + default: { + console.warn("Cursor: Unknown command received from server:", args[0]); + break; + } + } + }); + + console.log(`Cursor tracking @ ${window.location.pathname}`); } function cursorDestroy() { @@ -294,13 +345,9 @@ function cursorDestroy() { document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mousedown', handleMouseDown); document.removeEventListener('mouseup', handleMouseUp); - document.removeEventListener('keydown', handleKeyDown); + document.removeEventListener('keypress', handleKeyPress); document.removeEventListener('keyup', handleKeyUp); - chars.forEach(char => { - char.destroy(); - }); - chars = new Array(); cursors.forEach(cursor => { cursor.destroy(); }); @@ -309,7 +356,7 @@ function cursorDestroy() { cursorContainer.remove(); - console.debug(`Cursor no longer tracking.`); + console.log(`Cursor no longer tracking.`); running = false; } diff --git a/public/style/cursor.css b/public/style/cursor.css index e53cee5..8561716 100644 --- a/public/style/cursor.css +++ b/public/style/cursor.css @@ -20,15 +20,16 @@ border-color: var(--on-background) !important; } -#cursors i.cursor .char { +#cursors i.char { position: absolute; - transform: translateY(-44px); margin: 0; + font-style: normal; font-size: 20px; + font-weight: bold; color: var(--on-background); } -#cursors .funchar { +#cursors i.funchar { position: absolute; margin: 0; From 7eac4765586e4cdc5f228777519c287e4f353e10 Mon Sep 17 00:00:00 2001 From: ari melody Date: Fri, 14 Mar 2025 20:47:58 +0000 Subject: [PATCH 4/5] random scripts are silly. MAKEFILES are where it's at --- .gitignore | 1 + Makefile | 12 ++++++++++++ bundle.sh | 9 --------- 3 files changed, 13 insertions(+), 9 deletions(-) create mode 100644 Makefile delete mode 100755 bundle.sh diff --git a/.gitignore b/.gitignore index 9bdf788..2e63958 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ docker-compose*.yml !docker-compose.example.yml config*.toml arimelody-web +arimelody-web.tar.gz diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f9784d5 --- /dev/null +++ b/Makefile @@ -0,0 +1,12 @@ +EXEC = arimelody-web + +.PHONY: all + +all: + go build -o $(EXEC) + +bundle: $(EXEC) + tar czf $(EXEC).tar.gz $(EXEC) admin/components/ admin/views/ admin/static/ views/ public/ schema-migration/ + +clean: + rm $(EXEC) $(EXEC).tar.gz diff --git a/bundle.sh b/bundle.sh deleted file mode 100755 index 277bb9c..0000000 --- a/bundle.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/bin/bash -# simple script to pack up arimelody.me for production distribution - -if [ ! -f arimelody-web ]; then - echo "[FATAL] ./arimelody-web not found! please run \`go build -o arimelody-web\` first." - exit 1 -fi - -tar czf arimelody-web.tar.gz arimelody-web admin/components/ admin/views/ admin/static/ views/ public/ schema-migration/ From 3f3164bc153a70df2bd6352fb514a62646f7cc1c Mon Sep 17 00:00:00 2001 From: ari melody Date: Fri, 14 Mar 2025 20:55:09 +0000 Subject: [PATCH 5/5] and the goddess spoke: don't make this silly mistake again --- Makefile | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index f9784d5..11e565a 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,9 @@ EXEC = arimelody-web -.PHONY: all +.PHONY: $(EXEC) -all: - go build -o $(EXEC) +$(EXEC): + GOOS=linux GOARCH=amd64 go build -o $(EXEC) bundle: $(EXEC) tar czf $(EXEC).tar.gz $(EXEC) admin/components/ admin/views/ admin/static/ views/ public/ schema-migration/