// ==UserScript== // @name OE2 VITAL — Vessel Integrity Tracking & Assessment Layer // @namespace https://game.dev.outerempires.net/ // @version 3.1 // @description Real-time ship maintenance grade — A-F rating, component list, and details (WebSocket-driven ShipPartsUpdate) // @match https://game.dev.outerempires.net/* // @grant none // @run-at document-start // ==/UserScript== (function () { 'use strict'; var POS_KEY = 'oe2_vital_pos'; var SLOTS = { Weapons: { label: 'WPN' }, Turrets: { label: 'TRT' }, Engines: { label: 'ENG' }, Core: { label: 'CORE' }, Shields: { label: 'SHD' }, Ammo: { label: 'AMMO' } }; var API_BASE = localStorage.getItem('_oe2_api_base') || ''; var API_AUTH = localStorage.getItem('_oe2_api_auth') || ''; var API_CHAR_ID = localStorage.getItem('_oe2_api_char_id') || ''; var _snapshotFetched = false; console.log('[VITAL] v3.0 loaded' + (API_BASE ? ' (cached creds)' : ' (awaiting creds)')); var overlayEl = null; var reopenBtn = null; var vtgBtn = null; var isDragging = false; var dragOffX = 0, dragOffY = 0; var isExpanded = false; var isVisible = false; var isUserHidden = false; var components = {}; var shipName = ''; var shipId = ''; var shieldData = null; var powerData = null; var lastBuzzZeroTime = 0; var lastBuzzBelow10Time = 0; var lastBuzzBelow25Time = 0; // Credential capture from game traffic + localStorage persistence (shared with other OE2 scripts) (function () { var origFetch = window.fetch; window.fetch = function (input, init) { var r = origFetch.apply(this, arguments); r.then(function (resp) { try { var url = typeof input === 'string' ? input : input ? input.url : ''; if (!url || url.indexOf('twitch') !== -1) return; if (url.indexOf('oe2') === -1 && url.indexOf('outerempires') === -1) return; var changed = false; if (!API_BASE) { var m = url.match(/^(https:\/\/[^/]+)/); if (m) { API_BASE = m[1]; localStorage.setItem('_oe2_api_base', API_BASE); changed = true; } } var cm = url.match(/characterId=(\d+)/); if (cm) { API_CHAR_ID = cm[1]; localStorage.setItem('_oe2_api_char_id', API_CHAR_ID); changed = true; } var headers = init ? init.headers : (input ? input.headers : {}); if (typeof headers === 'object' && !Array.isArray(headers)) { var auth = headers.Authorization || headers.authorization || ''; if (auth && (!API_AUTH || auth !== API_AUTH)) { var prevAuth = API_AUTH; API_AUTH = auth; localStorage.setItem('_oe2_api_auth', API_AUTH); changed = true; // If auth token changed (renewed), allow snapshot retry if (prevAuth && auth !== prevAuth) _snapshotFetched = false; } } if (changed) console.log('[VITAL] Credentials ready' + (API_CHAR_ID ? ' char=' + API_CHAR_ID : '')); if (changed) fetchInitialSnapshot(); // Detect repair API calls and refresh snapshot if (resp && resp.ok && url.indexOf('repair') !== -1) { console.log('[VITAL] Repair detected, refreshing snapshot'); refreshSnapshot(); } } catch (e) {} }); return r; }; // Also capture from XHR (game may use this for some calls) var _open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function (method, url) { this._vitalUrl = url; return _open.apply(this, arguments); }; var _setH = XMLHttpRequest.prototype.setRequestHeader; XMLHttpRequest.prototype.setRequestHeader = function (k, v) { var u = this._vitalUrl || ''; if (u.indexOf('oe2') !== -1 || u.indexOf('outerempires') !== -1) { if (u.indexOf('twitch') === -1 && k.toLowerCase() === 'authorization' && (!API_AUTH || v !== API_AUTH)) { if (API_AUTH && v !== API_AUTH) _snapshotFetched = false; API_AUTH = v; localStorage.setItem('_oe2_api_auth', API_AUTH); console.log('[VITAL] Credentials ready (XHR)'); fetchInitialSnapshot(); } if (!API_BASE) { var m = u.match(/^(https:\/\/[^/]+)/); if (m) { API_BASE = m[1]; localStorage.setItem('_oe2_api_base', API_BASE); } } var cm = u.match(/characterId=(\d+)/); if (cm) { API_CHAR_ID = cm[1]; localStorage.setItem('_oe2_api_char_id', API_CHAR_ID); } } return _setH.apply(this, arguments); }; var _send = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function () { var xhr = this; var u = xhr._vitalUrl || ''; if (u.indexOf('repair') !== -1 && (u.indexOf('oe2') !== -1 || u.indexOf('outerempires') !== -1)) { xhr.addEventListener('load', function () { if (xhr.status >= 200 && xhr.status < 300) { console.log('[VITAL] Repair detected (XHR), refreshing snapshot'); refreshSnapshot(); } }); } return _send.apply(this, arguments); }; })(); // WebSocket interceptor — catches GameUpdate/ShipPartsUpdate messages (function () { console.log('[VITAL] WS interceptor installing at document-start'); var _origAdd = EventTarget.prototype.addEventListener; EventTarget.prototype.addEventListener = function (type, listener, options) { if (type === 'message' && this instanceof WebSocket) { var self = this; var wrapped = function (e) { if (typeof e.data === 'string') tryProcess(e.data); if (typeof listener === 'function') return listener.apply(self, arguments); else if (listener && typeof listener.handleEvent === 'function') return listener.handleEvent(e); }; return _origAdd.call(this, type, wrapped, options); } return _origAdd.apply(this, arguments); }; if (window.WebSocket) { var _origWS = window.WebSocket; window.WebSocket = function (url, protocols) { var ws = new _origWS(url, protocols); Object.defineProperty(ws, 'onmessage', { configurable: true, enumerable: true, get: function () { return this.__vital_om; }, set: function (fn) { this.__vital_om = fn; _origAdd.call(ws, 'message', function (e) { if (typeof e.data === 'string') tryProcess(e.data); if (this.__vital_om) this.__vital_om.call(this, e); }); } }); return ws; }; window.WebSocket.prototype = _origWS.prototype; window.WebSocket.CONNECTING = 0; window.WebSocket.OPEN = 1; window.WebSocket.CLOSING = 2; window.WebSocket.CLOSED = 3; } function tryProcess(text) { try { var p = JSON.parse(text); } catch (e) { return; } var msgs = Array.isArray(p) ? p : [p]; for (var i = 0; i < msgs.length; i++) { var m = msgs[i]; if (m.message_type === 'GameUpdate' && m.message) { handleGameUpdate(m.message); } } } })(); function handleGameUpdate(msg) { var action = msg.action; var payload = msg.payload; if (!action || !payload) return; if (action === 'ShipPartsUpdate') { applyPartUpdates(payload); } else if (action === 'CombinedUpdate' && Array.isArray(payload)) { for (var i = 0; i < payload.length; i++) { if (payload[i].action === 'ShipPartsUpdate') { applyPartUpdates(payload[i].payload); } } } else if (action === 'Update' && Array.isArray(payload) && payload.length > 0) { for (var ui = 0; ui < payload.length; ui++) { var sd = payload[ui]; // Track player's own ship var cid = sd.char_id !== undefined && sd.char_id !== null ? '' + sd.char_id : ''; if (cid && cid === API_CHAR_ID) { if (sd.ship_id !== undefined) shipId = sd.ship_id; if (sd.name) shipName = sd.name; if (sd.shield) shieldData = sd.shield; if (sd.power) powerData = sd.power; // Check for component-like data in any field for (var key in sd) { if (Array.isArray(sd[key]) && sd[key].length > 0 && sd[key][0].healthPercentage !== undefined) { applyPartUpdates(sd[key]); } } // Re-render if we got new data (even just shield/power update) renderFromState(); } } } } function applyPartUpdates(parts) { if (!Array.isArray(parts) || !parts.length) return; var changed = false; for (var i = 0; i < parts.length; i++) { var c = parts[i]; var id = c.Id !== undefined && c.Id !== null ? '' + c.Id : c.id !== undefined && c.id !== null ? '' + c.id : null; if (!id) continue; // Dedup: remove any synthetic 'c_' entry that matches this component name var staleKeys = Object.keys(components).filter(function (k) { return k.indexOf('c_') === 0 && components[k].name === c.name; }); for (var si = 0; si < staleKeys.length; si++) { delete components[staleKeys[si]]; changed = true; } if (!components[id]) { components[id] = JSON.parse(JSON.stringify(c)); if (i === 0) console.log('[VITAL] New component via WS:', id, c.name, Object.keys(c).join(',')); } else { var oldHP = components[id].healthPercentage; for (var k in c) { if (c.hasOwnProperty(k)) components[id][k] = c[k]; } var newHP = components[id].healthPercentage; if (oldHP !== undefined && newHP !== undefined && newHP < oldHP) { components[id]._damageFlash = Date.now(); components[id]._lastDamagedAt = Date.now(); } } changed = true; } if (changed) renderFromState(); } function fetchInitialSnapshot() { if (!API_BASE || !API_AUTH) { console.log('[VITAL] Waiting for credentials...'); setTimeout(fetchInitialSnapshot, 3000); return; } _snapshotFetched = true; console.log('[VITAL] Fetching initial ship snapshot...'); fetch(API_BASE + '/v1/character/' + API_CHAR_ID + '/availableShips', { headers: { 'Authorization': API_AUTH } }).then(function (resp) { if (!resp.ok) { console.log('[VITAL] Snapshot fetch failed:', resp.status); return null; } return resp.json(); }).then(function (body) { if (!body || !body.success) { console.log('[VITAL] Snapshot response invalid'); return; } var ships = body.data; if (!Array.isArray(ships) || !ships.length) { console.log('[VITAL] No ships in snapshot'); return; } // Try to find current ship by shipId from WS, fallback to first var ship = null; if (shipId) { for (var si = 0; si < ships.length; si++) { if (ships[si].ship_id && '' + ships[si].ship_id === '' + shipId) { ship = ships[si]; break; } if (ships[si].id && '' + ships[si].id === '' + shipId) { ship = ships[si]; break; } } } if (!ship) ship = ships[0]; shipName = ship.summary ? (ship.summary.shipName || ship.summary.shipType || '') : (ship.name || ''); console.log('[VITAL] Snapshot loaded: ' + shipName + (ship.components ? ' (' + ship.components.length + ' components)' : ' (no components)')); if (ship.components) { for (var j = 0; j < ship.components.length; j++) { var c = ship.components[j]; var id = c.Id !== undefined && c.Id !== null ? '' + c.Id : c.id !== undefined && c.id !== null ? '' + c.id : null; if (id) { components[id] = c; } else { console.log('[VITAL] Component missing id:', c.name || '?'); } } } renderFromState(); }).catch(function () { console.log('[VITAL] Snapshot fetch error'); }); } function refreshSnapshot() { if (!API_BASE || !API_AUTH || !API_CHAR_ID) { console.log('[VITAL] refreshSnapshot: no creds'); return; } console.log('[VITAL] Refreshing snapshot...'); var prevDamage = {}; for (var id in components) { if (components[id]._lastDamagedAt) prevDamage[id] = components[id]._lastDamagedAt; } fetch(API_BASE + '/v1/character/' + API_CHAR_ID + '/availableShips', { headers: { 'Authorization': API_AUTH } }).then(function (resp) { if (!resp.ok) { console.log('[VITAL] Refresh failed:', resp.status); return null; } return resp.json(); }).then(function (body) { if (!body || !body.success) return; var ships = body.data; if (!Array.isArray(ships) || !ships.length) return; // Try to find current ship by shipId from WS, fallback to first var ship = null; if (shipId) { for (var si = 0; si < ships.length; si++) { if (ships[si].ship_id && '' + ships[si].ship_id === '' + shipId) { ship = ships[si]; break; } if (ships[si].id && '' + ships[si].id === '' + shipId) { ship = ships[si]; break; } } } if (!ship) ship = ships[0]; shipName = ship.summary ? (ship.summary.shipName || ship.summary.shipType || '') : (ship.name || ''); components = {}; if (ship.components) { for (var j = 0; j < ship.components.length; j++) { var c = ship.components[j]; var id = c.Id !== undefined && c.Id !== null ? '' + c.Id : c.id !== undefined && c.id !== null ? '' + c.id : null; if (!id) continue; components[id] = JSON.parse(JSON.stringify(c)); if (prevDamage[id]) components[id]._lastDamagedAt = prevDamage[id]; } } renderFromState(); console.log('[VITAL] Snapshot refreshed'); }).catch(function () { console.log('[VITAL] Refresh error'); }); } function renderFromState() { var compList = []; var now = Date.now(); for (var id in components) { if (components[id]._damageFlash && now - components[id]._damageFlash > 1000) { delete components[id]._damageFlash; } if (components[id]._lastDamagedAt && now - components[id]._lastDamagedAt > 30000) { delete components[id]._lastDamagedAt; } compList.push(components[id]); } var total = 0, count = 0, damaged = false; for (var i = 0; i < compList.length; i++) { var hp = compList[i].healthPercentage; if (hp !== null && hp !== undefined) { total += hp; count++; } if (hp !== null && hp !== undefined && hp < 90) damaged = true; } // Include shield/power data from WS if available var wsInfo = {}; if (shieldData) wsInfo.shield = shieldData; if (powerData) wsInfo.power = powerData; render({ summary: { shipName: shipName, shipType: shipName, overallIntegrity: count > 0 ? total / count : null, isDamaged: damaged }, components: compList, wsInfo: wsInfo }); } function healthColor(pct) { if (pct === null || pct === undefined) return '#888'; if (pct > 80) return '#4dd0e1'; if (pct > 60) return '#00eda2'; if (pct > 40) return '#ff9800'; if (pct > 20) return '#ffc107'; return '#ff6b6b'; } function maintenanceGrade(pct) { if (pct === null || pct === undefined) return { grade: '\u2014\u2014', color: '#3a6ea8' }; if (pct >= 95) return { grade: 'A', color: '#00eda2' }; if (pct >= 85) return { grade: 'B', color: '#8bc34a' }; if (pct >= 70) return { grade: 'C', color: '#ffc107' }; if (pct >= 50) return { grade: 'D', color: '#ff9800' }; return { grade: 'F', color: '#ff6b6b' }; } function dotColor(pct) { if (pct === null || pct === undefined) return '#888'; if (pct > 80) return '#4dd0e1'; if (pct > 60) return '#00eda2'; if (pct > 40) return '#ff9800'; if (pct > 20) return '#ffc107'; return '#ff6b6b'; } function getSlot(name, blue) { name = (name || '').toLowerCase(); blue = (blue || '').toLowerCase(); if (blue === 'weapon' || blue === 'weapons' || name.match(/laser|missile|rail|cannon|launcher|turret|beam|blaster/)) return name.includes('turret') ? 'Turrets' : 'Weapons'; if (blue === 'engine' || blue === 'engines' || name.match(/engine|drive|thruster|propul|warp/)) return 'Engines'; if (blue === 'core' || name.match(/reactor|core|power|cpu|processor/)) return 'Core'; if (blue === 'shield' || blue === 'shields' || name.match(/shield|deflector|armor|plat/)) return 'Shields'; if (blue === 'ammo' || name.match(/ammo|charge|battery|cell/)) return 'Ammo'; if (blue === 'turret' || name.includes('turret')) return 'Turrets'; return 'Core'; } function scrapeDOMComponents() { // DOM scraping disabled — all component data comes from WebSocket ShipPartsUpdate. // Old CSS classes (#ShipInformation, .CargoItem, .CargoType, .MiniPie) no longer exist. return 0; } function createOverlay() { isUserHidden = false; if (overlayEl) { overlayEl.style.display = ''; if (vtgBtn) vtgBtn.style.display = ''; isVisible = true; fetchInitialSnapshot(); return; } console.log('[VITAL] Creating overlay'); if (reopenBtn) reopenBtn.style.display = 'none'; overlayEl = document.createElement('div'); overlayEl.id = 'oe2-vital-overlay'; overlayEl.style.cssText = [ 'position:fixed', 'z-index:280', 'bottom:20px', 'right:16px', 'background:rgba(6,12,22,0.3)', 'padding:4px 0', 'font-family:Rajdhani,"Segoe UI",sans-serif', 'color:#e0e8f0', 'font-size:15px', 'width:260px', 'pointer-events:auto', 'cursor:move', 'user-select:none', 'text-shadow:0 0 8px #000,0 1px 4px #000', ].join(';') + ';'; var saved = localStorage.getItem(POS_KEY); if (saved) { try { var p = JSON.parse(saved); overlayEl.style.left = p.x + 'px'; overlayEl.style.bottom = p.y + 'px'; overlayEl.style.right = ''; } catch (e) {} } overlayEl.innerHTML = '