'use strict'; /* ============================================================ أوسفالت 3D — سباق النيترو A complete 3D arcade racing game (Three.js) ============================================================ */ // ---------------- utils ---------------- const clamp = (v, a, b) => Math.max(a, Math.min(b, v)); /** Start-line crossing detector. Returns +1 if the position wrapped forward past the * start line, -1 if it wrapped backward, 0 for normal (sub-half-lap) motion. * Relies on the invariant that a car moves less than N/2 samples per frame, which * holds by a wide margin (max ~3 samples/frame). */ function crossStart(sTo, sFrom, N) { const d = sTo - sFrom; // raw, NOT wrapped — the wrap is what we detect if (d < -N / 2) return 1; // went from ~N-1 to ~0 (forward crossing) if (d > N / 2) return -1; // went from ~0 to ~N-1 (backward crossing) return 0; } const lerp = (a, b, t) => a + (b - a) * t; function lerpAngle(a, b, t) { let d = (b - a) % (Math.PI * 2); if (d > Math.PI) d -= Math.PI * 2; if (d < -Math.PI) d += Math.PI * 2; return a + d * t; } function fmtTime(t) { if (!isFinite(t) || t < 0) t = 0; const m = Math.floor(t / 60), s = Math.floor(t % 60), ms = Math.floor((t % 1) * 1000); return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}.${String(ms).padStart(3, '0')}`; } // ---------------- car catalogue ---------------- const CAR_TYPES = [ { name: 'فينكس GT', color: 0xd7263d, accel: 15.5, top: 63, grip: 2.3, nitro: 0.30, stats: { 'السرعة': 72, 'التسارع': 60, 'الانحناء': 58, 'النيترو': 80 } }, { name: 'صقر رياضي', color: 0x1d6ff2, accel: 17.5, top: 58.5, grip: 2.6, nitro: 0.24, stats: { 'السرعة': 60, 'التسارع': 76, 'الانحناء': 72, 'النيترو': 58 } }, { name: 'العاصفة', color: 0xf2a11d, accel: 19.5, top: 55, grip: 2.9, nitro: 0.34, stats: { 'السرعة': 54, 'التسارع': 88, 'الانحناء': 84, 'النيترو': 92 } }, ]; const LAPS = 3; let RACE_TIME_LIMIT = 180; // seconds — DNF cap: no race can hang forever (F-004) // ---------------- persistence (F-007 / F-008 / F-009) ---------------- // Namespaced localStorage; every access is wrapped so private mode / // unavailable storage degrades to defaults instead of crashing. const Store = { PREFIX: 'asphalt3d.', get(key, dflt) { try { const v = localStorage.getItem(this.PREFIX + key); return v === null ? dflt : JSON.parse(v); } catch { return dflt; } }, set(key, value) { try { localStorage.setItem(this.PREFIX + key, JSON.stringify(value)); } catch { /* storage unavailable — play without persistence */ } }, }; // Difficulty: multiplies every AI top speed (F-009). Rubber-banding is kept. const DIFFS = { easy: { label: 'سهل', mult: 0.88 }, normal: { label: 'عادي', mult: 1.0 }, hard: { label: 'صعب', mult: 1.08 } }; let diffKey = Store.get('diff', 'normal'); if (!DIFFS[diffKey]) diffKey = 'normal'; // ---------------- track definition ---------------- const HALF = 9; // half road width const TRACK_PTS = [ [0, -150], [95, -140], [160, -95], [170, -20], [125, 45], [155, 115], [80, 155], [-20, 148], [-65, 95], [-130, 125], [-185, 60], [-165, -25], [-190, -90], [-105, -125] ]; let N, SEG_LEN, samplesX, samplesZ, tanX, tanZ, sideX, sideZ, arcLen, curv, limits; let trackMinX, trackMaxX, trackMinZ, trackMaxZ; // Closed uniform Catmull-Rom (tension 0.5) — mathematically identical to // THREE.CatmullRomCurve3(pts, true, 'catmullrom', 0.5). Used only in Node unit // tests where THREE is absent, so track logic stays testable without a browser. function catmullRomFallback(pts2d) { const n = pts2d.length; const co = (a, b, c, d, t) => 0.5 * (2 * b + (c - a) * t + (2 * a - 5 * b + 4 * c - d) * t * t + (3 * b - a - 3 * c + d) * t * t * t); const evalAt = (u) => { const f = u * n, seg = Math.floor(f) % n, t = f - Math.floor(f); const p0 = pts2d[(seg - 1 + n) % n], p1 = pts2d[seg], p2 = pts2d[(seg + 1) % n], p3 = pts2d[(seg + 2) % n]; return { x: co(p0[0], p1[0], p2[0], p3[0], t), z: co(p0[1], p1[1], p2[1], p3[1], t) }; }; const M = 4000, lut = [0]; let prev = evalAt(0), total = 0; for (let i = 1; i <= M; i++) { const pt = evalAt(i / M); total += Math.hypot(pt.x - prev.x, pt.z - prev.z); lut.push(total); prev = pt; } return { getSpacedPoints(divisions) { const out = []; for (let i = 0; i <= divisions; i++) { const target = (i / divisions) * total; let lo = 1, hi = M; while (lo < hi) { const mid = (lo + hi) >> 1; if (lut[mid] < target) lo = mid + 1; else hi = mid; } const u = ((lo - 1) + (target - lut[lo - 1]) / Math.max(lut[lo] - lut[lo - 1], 1e-9)) / M; out.push(evalAt(u)); } return out; } }; } function buildTrackData() { const curve = (typeof THREE !== 'undefined' && THREE.CatmullRomCurve3) ? new THREE.CatmullRomCurve3( TRACK_PTS.map(p => new THREE.Vector3(p[0], 0, p[1])), true, 'catmullrom', 0.5) : catmullRomFallback(TRACK_PTS); const pts = curve.getSpacedPoints(1000); N = pts.length - 1; // last == first samplesX = new Float32Array(N); samplesZ = new Float32Array(N); let len = 0; for (let i = 0; i < N; i++) { samplesX[i] = pts[i].x; samplesZ[i] = pts[i].z; } for (let i = 0; i < N; i++) { const a = pts[i], b = pts[(i + 1) % N]; len += Math.hypot(b.x - a.x, b.z - a.z); } SEG_LEN = len / N; // tangents / sides / arcs tanX = new Float32Array(N); tanZ = new Float32Array(N); sideX = new Float32Array(N); sideZ = new Float32Array(N); arcLen = new Float32Array(N); curv = new Float32Array(N); let acc = 0; for (let i = 0; i < N; i++) { const p0 = pts[(i - 1 + N) % N], p1 = pts[(i + 1) % N]; let tx = p1.x - p0.x, tz = p1.z - p0.z; const tl = Math.hypot(tx, tz) || 1; tx /= tl; tz /= tl; tanX[i] = tx; tanZ[i] = tz; sideX[i] = tz; sideZ[i] = -tx; if (i > 0) acc += SEG_LEN; arcLen[i] = acc; } // curvature (angle change over a small window / distance) for (let i = 0; i < N; i++) { const a0 = pts[(i - 2 + N) % N], a1 = pts[i], a2 = pts[(i + 4) % N]; let t0x = a1.x - a0.x, t0z = a1.z - a0.z, l0 = Math.hypot(t0x, t0z) || 1; let t1x = a2.x - a1.x, t1z = a2.z - a1.z, l1 = Math.hypot(t1x, t1z) || 1; t0x /= l0; t0z /= l0; t1x /= l1; t1z /= l1; const ang = Math.acos(clamp(t0x * t1x + t0z * t1z, -1, 1)); curv[i] = ang / Math.max(l0 + l1, 0.01); } // AI speed limits per sample (min over a look-ahead window) const raw = new Float32Array(N); for (let i = 0; i < N; i++) raw[i] = Math.min(66, Math.sqrt(12.5 / Math.max(curv[i], 0.0004))); limits = new Float32Array(N); for (let i = 0; i < N; i++) { let m = Infinity; for (let o = 0; o < 45; o++) m = Math.min(m, raw[(i + o) % N]); limits[i] = m; } // bounds trackMinX = Infinity; trackMaxX = -Infinity; trackMinZ = Infinity; trackMaxZ = -Infinity; for (let i = 0; i < N; i++) { trackMinX = Math.min(trackMinX, samplesX[i]); trackMaxX = Math.max(trackMaxX, samplesX[i]); trackMinZ = Math.min(trackMinZ, samplesZ[i]); trackMaxZ = Math.max(trackMaxZ, samplesZ[i]); } } function distToTrack(x, z, step) { let bd = Infinity; for (let i = 0; i < N; i += (step || 4)) { const dx = x - samplesX[i], dz = z - samplesZ[i]; const d = dx * dx + dz * dz; if (d < bd) bd = d; } return Math.sqrt(bd); } function nearestSample(x, z, hint) { let best = hint % N, bd = Infinity; for (let o = -40; o <= 40; o++) { const i = (hint + o + N) % N; const dx = x - samplesX[i], dz = z - samplesZ[i]; const d = dx * dx + dz * dz; if (d < bd) { bd = d; best = i; } } return best; } // ---------------- three.js scene ---------------- let scene, camera, renderer, clock; let sun; function makeSky() { const geo = new THREE.SphereGeometry(2000, 24, 12); const mat = new THREE.ShaderMaterial({ side: THREE.BackSide, depthWrite: false, uniforms: { top: { value: new THREE.Color(0x1e4f9c) }, mid: { value: new THREE.Color(0x6fa8e0) }, bot: { value: new THREE.Color(0xd8ecff) } }, vertexShader: `varying vec3 vP; void main(){ vP=position; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`, fragmentShader: `varying vec3 vP; uniform vec3 top; uniform vec3 mid; uniform vec3 bot; void main(){ float h=normalize(vP).y; vec3 c = h>0.25 ? mix(mid,top,smoothstep(0.25,0.9,h)) : mix(bot,mid,smoothstep(-0.05,0.25,h)); gl_FragColor=vec4(c,1.); }` }); return new THREE.Mesh(geo, mat); } function makeAsphaltTexture() { const c = document.createElement('canvas'); c.width = 256; c.height = 256; const g = c.getContext('2d'); g.fillStyle = '#34363c'; g.fillRect(0, 0, 256, 256); for (let i = 0; i < 2600; i++) { g.fillStyle = Math.random() < 0.5 ? 'rgba(255,255,255,0.05)' : 'rgba(0,0,0,0.12)'; g.fillRect(Math.random() * 256, Math.random() * 256, 2, 2); } // curbs (red/white) at both edges for (let y = 0; y < 256; y += 32) { const on = (y / 32) % 2 === 0; g.fillStyle = on ? '#d43a2f' : '#e8e8e8'; g.fillRect(0, y, 16, 32); g.fillRect(240, y, 16, 32); } // edge lines g.fillStyle = '#f2f2f2'; g.fillRect(24, 0, 5, 256); g.fillRect(227, 0, 5, 256); // center dashes g.fillStyle = '#e8b93c'; for (let y = 0; y < 256; y += 64) g.fillRect(125, y, 6, 40); const tex = new THREE.CanvasTexture(c); tex.wrapS = THREE.RepeatWrapping; tex.wrapT = THREE.RepeatWrapping; tex.anisotropy = 8; return tex; } function makeCheckerTexture() { const c = document.createElement('canvas'); c.width = 64; c.height = 32; const g = c.getContext('2d'); for (let y = 0; y < 2; y++) for (let x = 0; x < 8; x++) { g.fillStyle = (x + y) % 2 ? '#111' : '#fff'; g.fillRect(x * 8, y * 16, 8, 16); } return new THREE.CanvasTexture(c); } function makeBannerTexture(text) { const c = document.createElement('canvas'); c.width = 512; c.height = 96; const g = c.getContext('2d'); g.fillStyle = '#0d1b3a'; g.fillRect(0, 0, 512, 96); g.strokeStyle = '#ffd23f'; g.lineWidth = 6; g.strokeRect(6, 6, 500, 84); g.fillStyle = '#ffd23f'; g.font = '900 52px Cairo, Arial'; g.textAlign = 'center'; g.fillText(text, 256, 68); return new THREE.CanvasTexture(c); } function smokeTexture() { const c = document.createElement('canvas'); c.width = 64; c.height = 64; const g = c.getContext('2d'); const gr = g.createRadialGradient(32, 32, 2, 32, 32, 30); gr.addColorStop(0, 'rgba(255,255,255,0.9)'); gr.addColorStop(1, 'rgba(255,255,255,0)'); g.fillStyle = gr; g.fillRect(0, 0, 64, 64); return new THREE.CanvasTexture(c); } function initScene() { const canvas = document.getElementById('game'); renderer = new THREE.WebGLRenderer({ canvas, antialias: true }); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setSize(innerWidth, innerHeight); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; renderer.outputColorSpace = THREE.SRGBColorSpace; scene = new THREE.Scene(); scene.fog = new THREE.Fog(0xbcd8f0, 250, 1500); camera = new THREE.PerspectiveCamera(72, innerWidth / innerHeight, 0.1, 4000); clock = new THREE.Clock(); scene.add(makeSky()); scene.add(new THREE.HemisphereLight(0xbdd9ff, 0x4a5a3a, 0.85)); sun = new THREE.DirectionalLight(0xfff2d8, 1.6); sun.position.set(180, 260, -120); sun.castShadow = true; sun.shadow.mapSize.set(2048, 2048); sun.shadow.camera.left = -280; sun.shadow.camera.right = 280; sun.shadow.camera.top = 280; sun.shadow.camera.bottom = -280; sun.shadow.camera.far = 900; sun.shadow.bias = -0.0005; scene.add(sun); // ground const ground = new THREE.Mesh( new THREE.PlaneGeometry(2400, 2400), new THREE.MeshStandardMaterial({ color: 0x5f9c48, roughness: 1 })); ground.rotation.x = -Math.PI / 2; ground.position.y = -0.05; ground.receiveShadow = true; scene.add(ground); buildRoad(); buildEnvironment(); window.addEventListener('resize', () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight); }); } function buildRoad() { const tex = makeAsphaltTexture(); const totalLen = SEG_LEN * N; tex.repeat.set(1, totalLen / 16); const pos = new Float32Array(N * 2 * 3), uv = new Float32Array(N * 2 * 2); for (let i = 0; i < N; i++) { const cx = samplesX[i], cz = samplesZ[i], sx = sideX[i], sz = sideZ[i]; pos[i * 6 + 0] = cx + sx * HALF; pos[i * 6 + 1] = 0.02; pos[i * 6 + 2] = cz + sz * HALF; pos[i * 6 + 3] = cx - sx * HALF; pos[i * 6 + 4] = 0.02; pos[i * 6 + 5] = cz - sz * HALF; uv[i * 4 + 0] = 0; uv[i * 4 + 1] = arcLen[i] / 16; uv[i * 4 + 2] = 1; uv[i * 4 + 3] = arcLen[i] / 16; } const idx = []; for (let i = 0; i < N; i++) { const j = (i + 1) % N; idx.push(i * 2, j * 2, i * 2 + 1, j * 2, j * 2 + 1, i * 2 + 1); } const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(pos, 3)); geo.setAttribute('uv', new THREE.BufferAttribute(uv, 2)); geo.setIndex(idx); geo.computeVertexNormals(); const road = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ map: tex, roughness: 0.92 })); road.receiveShadow = true; scene.add(road); // start / finish line const sl = new THREE.Mesh( new THREE.PlaneGeometry(HALF * 2, 2.4), new THREE.MeshBasicMaterial({ map: makeCheckerTexture() })); sl.rotation.x = -Math.PI / 2; sl.position.set(samplesX[0], 0.045, samplesZ[0]); sl.rotation.z = Math.atan2(tanX[0], tanZ[0]); scene.add(sl); // start gantry const gx = sideX[0], gz = sideZ[0]; const pillarMat = new THREE.MeshStandardMaterial({ color: 0x2b3340, roughness: 0.6 }); for (const sgn of [1, -1]) { const p = new THREE.Mesh(new THREE.BoxGeometry(0.8, 7, 0.8), pillarMat); p.position.set(samplesX[0] + gx * (HALF + 2) * sgn, 3.5, samplesZ[0] + gz * (HALF + 2) * sgn); p.castShadow = true; scene.add(p); } const bar = new THREE.Mesh(new THREE.BoxGeometry(HALF * 2 + 6, 0.7, 0.7), pillarMat); bar.position.set(samplesX[0], 7, samplesZ[0]); bar.rotation.y = Math.atan2(gx, gz); scene.add(bar); const banner = new THREE.Mesh( new THREE.PlaneGeometry(HALF * 2 + 4, 2.6), new THREE.MeshBasicMaterial({ map: makeBannerTexture('START • انطلاقة') })); banner.position.set(samplesX[0], 5.7, samplesZ[0]); banner.rotation.y = Math.atan2(gx, gz) + Math.PI; scene.add(banner); // guard-rail posts (both sides) const postGeo = new THREE.BoxGeometry(0.35, 0.7, 0.35); const postMat = new THREE.MeshStandardMaterial({ color: 0x8fa3bd, metalness: 0.6, roughness: 0.4 }); const count = Math.floor(N / 3) * 2; const posts = new THREE.InstancedMesh(postGeo, postMat, count); const m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), eul = new THREE.Euler(), sc = new THREE.Vector3(1, 1, 1); let pi = 0; for (let i = 0; i < N; i += 3) { for (const sgn of [1, -1]) { eul.set(0, Math.atan2(sideX[i], sideZ[i]), 0); q.setFromEuler(eul); m4.compose( new THREE.Vector3(samplesX[i] + sideX[i] * (HALF + 1.5) * sgn, 0.35, samplesZ[i] + sideZ[i] * (HALF + 1.5) * sgn), q, sc); posts.setMatrixAt(pi++, m4); } } posts.instanceMatrix.needsUpdate = true; scene.add(posts); } function buildEnvironment() { const rand = (() => { let s = 12345; return () => (s = (s * 16807) % 2147483647) / 2147483647; })(); const pad = 60; const x0 = trackMinX - pad, x1 = trackMaxX + pad, z0 = trackMinZ - pad, z1 = trackMaxZ + pad; // ---- buildings ---- const bGeo = new THREE.BoxGeometry(1, 1, 1); bGeo.translate(0, 0.5, 0); const bMat = new THREE.MeshStandardMaterial({ roughness: 0.85, metalness: 0.15 }); const bColors = [0x9aa7ba, 0x7d8ba1, 0xb8c4d4, 0x69788f, 0xa89f92]; const NB = 120; const bld = new THREE.InstancedMesh(bGeo, bMat, NB); const m4 = new THREE.Matrix4(), sc = new THREE.Vector3(), qid = new THREE.Quaternion(), pv = new THREE.Vector3(); let placed = 0, tries = 0; while (placed < NB && tries < 4000) { tries++; const x = x0 + rand() * (x1 - x0), z = z0 + rand() * (z1 - z0); if (distToTrack(x, z, 4) < HALF + 22) continue; const h = 12 + rand() * rand() * 90; const w = 14 + rand() * 26, d = 14 + rand() * 26; pv.set(x, 0, z); sc.set(w, h, d); qid.setFromEuler(new THREE.Euler(0, rand() * Math.PI, 0)); m4.compose(pv, qid, sc); bld.setMatrixAt(placed, m4); bld.setColorAt(placed, new THREE.Color(bColors[placed % bColors.length]).multiplyScalar(0.7 + rand() * 0.5)); placed++; } bld.instanceMatrix.needsUpdate = true; if (bld.instanceColor) bld.instanceColor.needsUpdate = true; scene.add(bld); // ---- trees (trunk + canopy) ---- const NT = 170; const trunkGeo = new THREE.CylinderGeometry(0.35, 0.5, 4, 6); trunkGeo.translate(0, 2, 0); const leafGeo = new THREE.ConeGeometry(3.2, 7, 7); leafGeo.translate(0, 7, 0); const trunks = new THREE.InstancedMesh(trunkGeo, new THREE.MeshStandardMaterial({ color: 0x7a5230, roughness: 1 }), NT); const leaves = new THREE.InstancedMesh(leafGeo, new THREE.MeshStandardMaterial({ color: 0x2e7d32, roughness: 1 }), NT); placed = 0; tries = 0; while (placed < NT && tries < 4000) { tries++; const x = x0 + rand() * (x1 - x0), z = z0 + rand() * (z1 - z0); const dtr = distToTrack(x, z, 4); if (dtr < HALF + 5 || dtr > HALF + 30) continue; const s = 0.8 + rand() * 0.8; pv.set(x, 0, z); sc.set(s, s, s); qid.setFromEuler(new THREE.Euler(0, rand() * Math.PI * 2, 0)); m4.compose(pv, qid, sc); trunks.setMatrixAt(placed, m4); leaves.setMatrixAt(placed, m4); placed++; } trunks.instanceMatrix.needsUpdate = true; leaves.instanceMatrix.needsUpdate = true; scene.add(trunks); scene.add(leaves); // ---- street lamps ---- const NL = Math.floor(N / 12); const poleGeo = new THREE.CylinderGeometry(0.14, 0.2, 6, 6); poleGeo.translate(0, 3, 0); const poles = new THREE.InstancedMesh(poleGeo, new THREE.MeshStandardMaterial({ color: 0x39424e, roughness: 0.6 }), NL); const headGeo = new THREE.SphereGeometry(0.45, 8, 6); const heads = new THREE.InstancedMesh(headGeo, new THREE.MeshStandardMaterial({ color: 0xfff3c0, emissive: 0xffe9a0, emissiveIntensity: 1.2 }), NL); for (let k = 0; k < NL; k++) { const i = Math.floor(k * N / NL); const sgn = (k % 2 ? 1 : -1); const px = samplesX[i] + sideX[i] * (HALF + 2.2) * sgn, pz = samplesZ[i] + sideZ[i] * (HALF + 2.2) * sgn; pv.set(px, 0, pz); sc.set(1, 1, 1); qid.identity(); m4.compose(pv, qid, sc); poles.setMatrixAt(k, m4); pv.set(px, 6.1, pz); m4.compose(pv, qid, sc); heads.setMatrixAt(k, m4); } poles.instanceMatrix.needsUpdate = true; heads.instanceMatrix.needsUpdate = true; scene.add(poles); scene.add(heads); // ---- clouds ---- const cTex = smokeTexture(); for (let i = 0; i < 10; i++) { const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: cTex, color: 0xffffff, transparent: true, opacity: 0.75, depthWrite: false })); sp.position.set(x0 + rand() * (x1 - x0), 160 + rand() * 80, z0 + rand() * (z1 - z0)); sp.scale.setScalar(70 + rand() * 90); scene.add(sp); } } // ---------------- car model ---------------- const sharedMats = {}; function getMats() { if (sharedMats.body) return sharedMats; sharedMats.tire = new THREE.MeshStandardMaterial({ color: 0x101216, roughness: 0.9 }); sharedMats.rim = new THREE.MeshStandardMaterial({ color: 0x9aa5b5, metalness: 0.85, roughness: 0.3 }); sharedMats.glass = new THREE.MeshStandardMaterial({ color: 0x0d1a28, metalness: 0.9, roughness: 0.12 }); sharedMats.dark = new THREE.MeshStandardMaterial({ color: 0x15181e, roughness: 0.7 }); sharedMats.head = new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: 0xcfe8ff, emissiveIntensity: 1.4 }); sharedMats.tail = new THREE.MeshStandardMaterial({ color: 0xff2222, emissive: 0xff2020, emissiveIntensity: 1.2 }); return sharedMats; } function buildCar(colorHex) { const M = getMats(); const bodyMat = new THREE.MeshStandardMaterial({ color: colorHex, metalness: 0.65, roughness: 0.3 }); const g = new THREE.Group(); const body = new THREE.Mesh(new THREE.BoxGeometry(1.9, 0.5, 4.5), bodyMat); body.position.y = 0.5; body.castShadow = true; g.add(body); const nose = new THREE.Mesh(new THREE.BoxGeometry(1.7, 0.28, 0.7), bodyMat); nose.position.set(0, 0.42, 2.5); g.add(nose); const cabin = new THREE.Mesh(new THREE.BoxGeometry(1.55, 0.52, 2.2), M.glass); cabin.position.set(0, 1.0, -0.25); cabin.castShadow = true; g.add(cabin); const spoiler = new THREE.Mesh(new THREE.BoxGeometry(1.9, 0.09, 0.55), M.dark); spoiler.position.set(0, 1.18, -2.15); g.add(spoiler); for (const sx of [-0.7, 0.7]) { const strut = new THREE.Mesh(new THREE.BoxGeometry(0.1, 0.35, 0.12), M.dark); strut.position.set(sx, 0.98, -2.1); g.add(strut); } // lights for (const sx of [-0.6, 0.6]) { const h = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.16, 0.08), M.head); h.position.set(sx, 0.5, 2.51); g.add(h); const t = new THREE.Mesh(new THREE.BoxGeometry(0.55, 0.14, 0.08), M.tail); t.position.set(sx, 0.55, -2.26); g.add(t); } // wheels const wheelGeo = new THREE.CylinderGeometry(0.42, 0.42, 0.34, 14); wheelGeo.rotateZ(Math.PI / 2); const wheels = [], steerPivots = []; const wpos = [[-0.95, 1.55, 1], [0.95, 1.55, 1], [-0.95, -1.55, 0], [0.95, -1.55, 0]]; for (const [wx, wz, steer] of wpos) { const pivot = new THREE.Group(); pivot.position.set(wx, 0.42, wz); const w = new THREE.Mesh(wheelGeo, M.tire); const rim = new THREE.Mesh(new THREE.CylinderGeometry(0.24, 0.24, 0.36, 8).rotateZ(Math.PI / 2), M.rim); pivot.add(w); pivot.add(rim); g.add(pivot); wheels.push(w); steerPivots.push(pivot); } // nitro flames const flameGeo = new THREE.ConeGeometry(0.22, 1.1, 8); flameGeo.rotateX(-Math.PI / 2); const flameMat = new THREE.MeshBasicMaterial({ color: 0x40b4ff, transparent: true, opacity: 0.9, blending: THREE.AdditiveBlending, depthWrite: false }); const flames = []; for (const sx of [-0.5, 0.5]) { const f = new THREE.Mesh(flameGeo, flameMat); f.position.set(sx, 0.42, -2.9); f.visible = false; g.add(f); flames.push(f); } return { group: g, wheels, steerPivots, flames }; } // ---------------- particles ---------------- const Particles = (() => { const max = 90, arr = []; let idx = 0; function emit(x, y, z, vx, vy, vz, life, size, color) { if (!scene) return; // Node unit tests: physics runs without a 3D scene let p = arr[idx]; if (!p) { const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: smokeTexture(), color: 0xffffff, transparent: true, opacity: 0.5, depthWrite: false })); s.visible = false; scene.add(s); p = { s, vx: 0, vy: 0, vz: 0, life: 0, max: 1, size: 1 }; arr[idx] = p; } idx = (idx + 1) % max; p.s.visible = true; p.s.position.set(x, y, z); p.vx = vx; p.vy = vy; p.vz = vz; p.life = p.max = life; p.size = size; p.s.material.color.setHex(color); p.s.material.opacity = 0.55; } function update(dt) { for (const p of arr) { if (!p || !p.s.visible) continue; p.life -= dt; if (p.life <= 0) { p.s.visible = false; continue; } p.s.position.x += p.vx * dt; p.s.position.y += p.vy * dt; p.s.position.z += p.vz * dt; p.vx *= 0.94; p.vz *= 0.94; const t = p.life / p.max; p.s.scale.setScalar(p.size * (1.7 - t * 0.7)); p.s.material.opacity = 0.5 * t; } } return { emit, update }; })(); // ---------------- audio ---------------- const AudioSys = { ctx: null, muted: Store.get('sound', 1) === 0, // persisted preference (F-008) init() { if (this.ctx) return; try { const AC = window.AudioContext || window.webkitAudioContext; const ctx = this.ctx = new AC(); const master = this.master = ctx.createGain(); master.gain.value = this.muted ? 0 : 0.9; master.connect(ctx.destination); // engine this.engGain = ctx.createGain(); this.engGain.gain.value = 0; const lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 900; this.engOsc1 = ctx.createOscillator(); this.engOsc1.type = 'sawtooth'; this.engOsc1.frequency.value = 60; this.engOsc2 = ctx.createOscillator(); this.engOsc2.type = 'square'; this.engOsc2.frequency.value = 30; const g2 = ctx.createGain(); g2.gain.value = 0.4; this.engOsc1.connect(lp); this.engOsc2.connect(g2); g2.connect(lp); lp.connect(this.engGain); this.engGain.connect(master); this.engOsc1.start(); this.engOsc2.start(); // noise buffer (skid / nitro / crash) const nb = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate); const d = nb.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1; this.noiseBuf = nb; // skid this.skidSrc = ctx.createBufferSource(); this.skidSrc.buffer = nb; this.skidSrc.loop = true; const bp = ctx.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 700; bp.Q.value = 0.7; this.skidGain = ctx.createGain(); this.skidGain.gain.value = 0; this.skidSrc.connect(bp); bp.connect(this.skidGain); this.skidGain.connect(master); this.skidSrc.start(); // nitro this.nitroSrc = ctx.createBufferSource(); this.nitroSrc.buffer = nb; this.nitroSrc.loop = true; const hp = ctx.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 1400; this.nitroGain = ctx.createGain(); this.nitroGain.gain.value = 0; this.nitroSrc.connect(hp); hp.connect(this.nitroGain); this.nitroGain.connect(master); this.nitroSrc.start(); } catch (e) { this.ctx = null; } }, engine(speedNorm, throttle, boost, drifting) { if (!this.ctx) return; const t = this.ctx.currentTime; const f = 55 + speedNorm * 240 + (boost ? 110 : 0) + throttle * 25; this.engOsc1.frequency.setTargetAtTime(f, t, 0.06); this.engOsc2.frequency.setTargetAtTime(f * 0.5, t, 0.06); this.engGain.gain.setTargetAtTime(0.035 + speedNorm * 0.05 + throttle * 0.02 + (boost ? 0.03 : 0), t, 0.08); this.skidGain.gain.setTargetAtTime(drifting && speedNorm > 0.15 ? 0.16 : 0, t, 0.05); this.nitroGain.gain.setTargetAtTime(boost ? 0.22 : 0, t, 0.06); }, skid(on) { if (!this.ctx) return; this.skidOn = on; }, beep(freq, dur, vol, type) { if (!this.ctx) return; const t = this.ctx.currentTime; const o = this.ctx.createOscillator(), g = this.ctx.createGain(); o.type = type || 'square'; o.frequency.value = freq; g.gain.setValueAtTime(vol || 0.25, t); g.gain.exponentialRampToValueAtTime(0.001, t + dur); o.connect(g); g.connect(this.master); o.start(t); o.stop(t + dur + 0.05); }, crash(power) { if (!this.ctx) return; const t = this.ctx.currentTime; const s = this.ctx.createBufferSource(); s.buffer = this.noiseBuf; const f = this.ctx.createBiquadFilter(); f.type = 'lowpass'; f.frequency.value = 500; const g = this.ctx.createGain(); g.gain.setValueAtTime(clamp(power, 0.1, 1) * 0.7, t); g.gain.exponentialRampToValueAtTime(0.001, t + 0.35); s.connect(f); f.connect(g); g.connect(this.master); s.start(t); s.stop(t + 0.4); this.beep(70, 0.25, 0.3, 'triangle'); }, fanfare() { [523, 659, 784, 1046].forEach((f, i) => setTimeout(() => this.beep(f, 0.3, 0.25, 'triangle'), i * 160)); }, mute(m) { if (this.master) this.master.gain.value = m ? 0 : 0.9; } }; // ---------------- game state ---------------- const G = { state: 'menu', // menu | countdown | race | paused | finished carType: CAR_TYPES[0], player: null, cars: [], // all cars (player + AI) with meshes raceTime: 0, cd: 0, shake: 0, finishDelay: 0, camFov: 72, }; function resetRace() { // clear old car meshes for (const c of G.cars) scene.remove(c.model.group); G.cars.length = 0; const type = G.carType; // player const pm = buildCar(type.color); scene.add(pm.group); const player = { isPlayer: true, name: type.name + ' (أنت)', color: type.color, type, model: pm, lap: 0, prevS: 0, s: 0, mid: false, lapStart: 0, best: Infinity, finished: false, finishTime: 0, nitro: 0.6, boosting: false, drifting: false, offroad: false, steer: 0, i: N - 23, }; const p = spawnPos(N - 23, 0); player.x = p.x; player.z = p.z; player.heading = Math.atan2(tanX[N - 23], tanZ[N - 23]); player.vx = 0; player.vz = 0; player.prevS = (N - 23) % N; G.player = player; G.cars.push(player); // AI rivals const aiDefs = [ { name: 'ريماس', color: 0x2ecc71, top: 61.5, sOff: N - 3, lane: -4.5 }, { name: 'خالد', color: 0x9b59b6, top: 59.5, sOff: N - 3, lane: 4.5 }, { name: 'سارة', color: 0xe67e22, top: 58, sOff: N - 13, lane: -4.5 }, { name: 'مازن', color: 0x16a5a5, top: 56.5, sOff: N - 13, lane: 4.5 }, ]; for (const a of aiDefs) { const m = buildCar(a.color); scene.add(m.group); const ai = { isPlayer: false, name: a.name, color: a.color, model: m, top: a.top * DIFFS[diffKey].mult, v: 0, s: a.sOff % N, baseLane: a.lane, lane: a.lane, phase: Math.random() * 10, lap: 0, mid: false, finished: false, finishTime: 0, i: Math.floor(a.sOff) % N, vx2: 0, vz2: 0, // V-001: defined from the first frame (was undefined → NaN in collision) }; const p2 = spawnPos(Math.floor(ai.s), ai.lane); ai.x = p2.x; ai.z = p2.z; ai.heading = Math.atan2(tanX[Math.floor(ai.s)], tanZ[Math.floor(ai.s)]); G.cars.push(ai); } G.raceTime = 0; G.shake = 0; G.finishDelay = 0; } function spawnPos(s, lane) { const i = ((Math.round(s) % N) + N) % N; return { x: samplesX[i] + sideX[i] * lane, z: samplesZ[i] + sideZ[i] * lane }; } // ---------------- input ---------------- const keys = {}; const touch = { left: 0, right: 0, gas: 0, brake: 0, nitro: 0, drift: 0 }; let isTouchDevice = false; function readInput() { return { left: (keys.ArrowLeft || keys.KeyA || touch.left) ? 1 : 0, right: (keys.ArrowRight || keys.KeyD || touch.right) ? 1 : 0, gas: (keys.ArrowUp || keys.KeyW || touch.gas) ? 1 : 0, brake: (keys.ArrowDown || keys.KeyS || touch.brake) ? 1 : 0, nitro: (keys.ShiftLeft || keys.ShiftRight || touch.nitro) ? 1 : 0, drift: (keys.Space || touch.drift) ? 1 : 0, }; } // ---------------- player physics ---------------- function updatePlayer(dt, inp) { const p = G.player, t = p.type; const fx = Math.sin(p.heading), fz = Math.cos(p.heading); // forward const rx = fz, rz = -fx; // right let vf = p.vx * fx + p.vz * fz; let vl = p.vx * rx + p.vz * rz; const speed = Math.hypot(p.vx, p.vz); // nitro const wantNitro = inp.nitro && inp.gas && p.nitro > 0.02 && vf > 2; p.boosting = wantNitro; if (wantNitro) p.nitro = Math.max(0, p.nitro - dt * 0.33); else { p.nitro += dt * 0.045; // slow passive refill if (p.drifting && speed > 10) p.nitro += dt * 0.16; // drift reward (F-006) p.nitro = Math.min(1, p.nitro); } const maxSp = p.boosting ? t.top * (1 + t.nitro) : t.top; const acc = t.accel * (p.boosting ? 1.7 : 1); if (inp.gas && G.state === 'race') vf += acc * dt; if (inp.brake) { if (vf > 0.5) vf = Math.max(0, vf - 32 * dt); else vf = Math.max(-9, vf - 10 * dt); } // drag (balances acc at maxSp) + rolling vf -= (acc / (maxSp * maxSp)) * vf * Math.abs(vf) * dt; vf -= vf * 0.15 * dt; // drift & grip const wasDrifting = p.drifting; p.drifting = inp.drift && speed > 10 && Math.abs(inp.right - inp.left) > 0.2; p.offroad = Math.abs(p.d) > HALF - 0.4; const grip = t.grip * (p.drifting ? 0.42 : 1) * (p.offroad ? 0.45 : 1); vl -= vl * clamp(grip * 7 * dt, 0, 1); if (p.offroad) vf -= vf * clamp(0.9 * dt, 0, 0.5); // steering const steerT = (inp.left - inp.right); p.steer = lerp(p.steer, clamp(steerT, -1, 1), clamp(10 * dt, 0, 1)); const sf = (2.6 / (1 + speed * 0.055)) * (p.drifting ? 1.3 : 1); p.heading += p.steer * sf * dt * (vf < -0.5 ? -1 : 1) * clamp(Math.abs(vf) / 6, 0, 1); // recompose velocity const nfx = Math.sin(p.heading), nfz = Math.cos(p.heading); const nrx = nfz, nrz = -nfx; p.vx = nfx * vf + nrx * vl; p.vz = nfz * vf + nrz * vl; p.x += p.vx * dt; p.z += p.vz * dt; // track position / walls p.i = nearestSample(p.x, p.z, p.i); const cx = samplesX[p.i], cz = samplesZ[p.i], nx = sideX[p.i], nz = sideZ[p.i]; p.d = (p.x - cx) * nx + (p.z - cz) * nz; const W = HALF + 1.2; if (Math.abs(p.d) > W) { const sgn = Math.sign(p.d); p.x = cx + nx * W * sgn; p.z = cz + nz * W * sgn; const vn = p.vx * nx + p.vz * nz; if (vn * sgn > 0) { p.vx -= nx * vn * 1.55; p.vz -= nz * vn * 1.55; if (Math.abs(vn) > 5) { G.shake = Math.min(1, G.shake + Math.abs(vn) / 30); AudioSys.crash(Math.abs(vn) / 18); Particles.emit(p.x, 0.6, p.z, (Math.random() - 0.5) * 6, 2, (Math.random() - 0.5) * 6, 0.5, 0.8, 0xffcc55); } } // wall-slide assist: gently align velocity with the track direction so the // car slides along the barrier instead of getting pinned against it const sp2 = Math.hypot(p.vx, p.vz); if (sp2 > 2) { const k = clamp(3 * dt, 0, 0.3); p.vx += (tanX[p.i] * sp2 - p.vx) * k; p.vz += (tanZ[p.i] * sp2 - p.vz) * k; } } // progress & laps const tx = tanX[p.i], tz = tanZ[p.i]; const along = ((p.x - cx) * tx + (p.z - cz) * tz) / SEG_LEN; let sF = (p.i + clamp(along, -0.5, 0.5)) % N; if (sF < 0) sF += N; const cross = crossStart(sF, p.prevS, N); if (cross === 1) { // crossed the start line forward if (p.mid && !p.finished) { p.lap++; const lt = G.raceTime - p.lapStart; p.lapStart = G.raceTime; if (lt < p.best) p.best = lt; if (p.lap >= LAPS) { p.finished = true; p.finishTime = G.raceTime; } else onPlayerLap(lt); } p.mid = false; } else if (cross === -1) { p.lap = Math.max(0, p.lap - 1); // crossed backwards } const frac = sF / N; if (frac > 0.45 && frac < 0.6) p.mid = true; p.s = sF; p.prevS = sF; // visuals const cg = p.model.group; cg.position.set(p.x, 0, p.z); cg.rotation.y = p.heading; cg.rotation.z = clamp(p.steer * vf * 0.004, -0.09, 0.09); // body roll const spin = vf * dt * 2.4; for (const w of p.model.wheels) w.rotation.x += spin; for (const sp of p.model.steerPivots) sp.rotation.y = p.steer * 0.45; // nitro flames const fl = p.model.flames; for (const f of fl) { f.visible = p.boosting; if (p.boosting) { const s = 0.7 + Math.random() * 0.8; f.scale.set(1, 1, s * (1 + p.nitro)); f.material.color.setHex(Math.random() < 0.5 ? 0x40b4ff : 0x9fe0ff); } } // drift smoke if ((p.drifting || (wasDrifting && p.drifting)) && G.state === 'race' && speed > 10) { const bx = -Math.sin(p.heading), bz = -Math.cos(p.heading); for (const sx of [-0.95, 0.95]) { Particles.emit( p.x + bx * 1.5 - Math.cos(p.heading) * sx, 0.3, p.z + bz * 1.5 + Math.sin(p.heading) * sx, (Math.random() - 0.5) * 2, 1.5, (Math.random() - 0.5) * 2, 0.9, 1.6, 0xd8d8d8); } } if (p.offroad && speed > 12 && Math.random() < 0.5) { Particles.emit(p.x - Math.sin(p.heading) * 2, 0.3, p.z - Math.cos(p.heading) * 2, 0, 1.2, 0, 0.7, 1.4, 0x9c8a5a); } // collision with AI cars for (const a of G.cars) { if (a === p) continue; const dx = p.x - a.x, dz = p.z - a.z; const d = Math.hypot(dx, dz); if (d < 2.4 && d > 0.001) { const nx2 = dx / d, nz2 = dz / d; const push = (2.4 - d); p.x += nx2 * push; p.z += nz2 * push; const rv = (p.vx - a.vx2) * nx2 + (p.vz - a.vz2) * nz2; if (rv < 0) { p.vx -= nx2 * rv * 0.8; p.vz -= nz2 * rv * 0.8; if (Math.abs(rv) > 4) { G.shake = Math.min(1, G.shake + 0.25); AudioSys.crash(Math.abs(rv) / 16); } } } } // audio AudioSys.engine(clamp(speed / 75, 0, 1), inp.gas ? 1 : 0, p.boosting, p.drifting); } function onPlayerLap(lt) { if (G.player.lap === LAPS - 1) showMsg('الجولة الأخيرة! 🏁', 'gold', 1.8); else showMsg('جولة ' + G.player.lap + '/' + LAPS + ' • ' + fmtTime(lt), 'cyan', 1.5); } // ---------------- AI ---------------- function updateAI(dt) { const p = G.player; for (const a of G.cars) { if (a.isPlayer) continue; const i = Math.floor(a.s) % N; let target = Math.min(a.top, limits[(i + 20) % N]); // rubber band const progP = p.lap * N + p.s; const progA = a.lap * N + a.s; const diff = progP - progA; if (diff > 250) target *= 1.12; else if (diff < -250) target *= 0.90; else target *= (1 + clamp(diff / 1200, -0.04, 0.04)); // avoid player ahead in similar lane let dP = p.s - a.s; if (dP < -N / 2) dP += N; if (dP > N / 2) dP -= N; if (dP > 0 && dP < 16 && Math.abs((p.d || 0) - a.lane) < 2.8) target *= 0.62; // avoid other AI ahead for (const b of G.cars) { if (b === a || b.isPlayer) continue; let dB = b.s - a.s; if (dB < -N / 2) dB += N; if (dB > N / 2) dB -= N; if (dB > 0 && dB < 10 && Math.abs(b.lane - a.lane) < 2.6) target = Math.min(target, a.v * 0.9); } if (a.finished) target = Math.min(target, 20); a.v += clamp(target - a.v, -16 * dt, 9 * dt); a.v = Math.max(0, a.v); const prevS = a.s; a.s = (a.s + a.v * dt / SEG_LEN) % N; a.lane = a.baseLane + Math.sin(G.raceTime * 0.35 + a.phase) * 1.4; // laps (forward wrap = crossed the line) const cross = crossStart(a.s, prevS, N); if (cross === 1) { if (a.mid && !a.finished) { a.lap++; a.mid = false; if (a.lap >= LAPS) { a.finished = true; a.finishTime = G.raceTime; } } } else if (cross === -1) a.lap = Math.max(0, a.lap - 1); const frac = a.s / N; if (frac > 0.45 && frac < 0.6) a.mid = true; // smooth position const i2 = Math.floor(a.s) % N, i3 = (i2 + 1) % N, f = a.s - Math.floor(a.s); a.x = lerp(samplesX[i2], samplesX[i3], f) + sideX[i2] * a.lane; a.z = lerp(samplesZ[i2], samplesZ[i3], f) + sideZ[i2] * a.lane; a.heading = lerpAngle(a.heading, Math.atan2(tanX[i2], tanZ[i2]), clamp(6 * dt, 0, 1)); const cg = a.model.group; cg.position.set(a.x, 0, a.z); cg.rotation.y = a.heading; const spin = a.v * dt * 2.4; for (const w of a.model.wheels) w.rotation.x += spin; a.vx2 = Math.sin(a.heading) * a.v; a.vz2 = Math.cos(a.heading) * a.v; } } // ---------------- camera ---------------- let camPos = null; // lazy: created on first camera update (keeps game.js require-able in Node) let camReady = false; function updateCamera(dt) { if (!camPos) camPos = new THREE.Vector3(); const p = G.player; const fx = Math.sin(p.heading), fz = Math.cos(p.heading); const speed = Math.hypot(p.vx, p.vz); const dist = 9.2 + speed * 0.022; const tx = p.x - fx * dist, ty = 3.4 + speed * 0.008, tz = p.z - fz * dist; if (!camReady) { camPos.set(tx, ty, tz); camReady = true; } // (camPos guaranteed non-null) const k = clamp(4.5 * dt, 0, 1); camPos.x = lerp(camPos.x, tx, k); camPos.y = lerp(camPos.y, ty, k); camPos.z = lerp(camPos.z, tz, k); G.shake = Math.max(0, G.shake - dt * 2.2); const sh = G.shake * G.shake; camera.position.set( camPos.x + (Math.random() - 0.5) * sh, camPos.y + (Math.random() - 0.5) * sh * 0.6, camPos.z + (Math.random() - 0.5) * sh); camera.lookAt(p.x + fx * 5, 1.2, p.z + fz * 5); // FOV with nitro const targetFov = p.boosting ? 84 : 72; G.camFov = lerp(G.camFov, targetFov, clamp(5 * dt, 0, 1)); if (Math.abs(camera.fov - G.camFov) > 0.05) { camera.fov = G.camFov; camera.updateProjectionMatrix(); } } // ---------------- HUD & minimap ---------------- const $ = id => document.getElementById(id); let msgTimer = 0; function showMsg(text, cls, dur) { if (typeof document === 'undefined') return; // Node unit tests const m = $('msg'); m.textContent = text; m.className = 'show ' + (cls || ''); msgTimer = dur || 1.2; } function updateHUD() { const p = G.player; const speed = Math.hypot(p.vx, p.vz) * 3.6; $('speed').textContent = Math.round(speed); $('lapNow').textContent = Math.min(p.lap + 1, LAPS); $('time').textContent = fmtTime(G.raceTime); $('nitroFill').style.width = (p.nitro * 100) + '%'; $('nitroLabel').classList.toggle('charge', p.drifting && speed > 36); // 36 km/h = 10 m/s const rank = getRank(); $('rank').innerHTML = rank + '/' + G.cars.length + ''; drawMinimap(); } /** Single source of truth for race progress (F-010): finished cars sort by * finish time (earlier = higher); unfinished cars by total distance driven. */ function carProgress(c) { return c.finished ? 1e9 - (LAPS + 1) * N + (1000 - c.finishTime) : c.lap * N + c.s; } function getRank() { const sorted = G.cars.slice().sort((a, b) => carProgress(b) - carProgress(a)); return sorted.indexOf(G.player) + 1; } let mmPts = null, mmScale = 1, mmOX = 0, mmOZ = 0; function buildMinimap() { const c = $('minimap'), g = c.getContext('2d'); const pad = 16; const w = trackMaxX - trackMinX, h = trackMaxZ - trackMinZ; mmScale = Math.min((150 - pad * 2) / w, (150 - pad * 2) / h); mmOX = (150 - w * mmScale) / 2 - trackMinX * mmScale; mmOZ = (150 - h * mmScale) / 2 - trackMinZ * mmScale; mmPts = []; for (let i = 0; i < N; i += 6) mmPts.push([samplesX[i] * mmScale + mmOX, samplesZ[i] * mmScale + mmOZ]); } function drawMinimap() { const c = $('minimap'), g = c.getContext('2d'); g.clearRect(0, 0, 150, 150); if (!mmPts) return; g.strokeStyle = 'rgba(255,255,255,0.85)'; g.lineWidth = 4; g.lineJoin = 'round'; g.beginPath(); g.moveTo(mmPts[0][0], mmPts[0][1]); for (const pt of mmPts) g.lineTo(pt[0], pt[1]); g.closePath(); g.stroke(); // start dot g.fillStyle = '#ffd23f'; g.beginPath(); g.arc(mmPts[0][0], mmPts[0][1], 3.4, 0, 7); g.fill(); // cars for (const car of G.cars) { g.fillStyle = car.isPlayer ? '#ffffff' : '#' + car.color.toString(16).padStart(6, '0'); g.beginPath(); g.arc(car.x * mmScale + mmOX, car.z * mmScale + mmOZ, car.isPlayer ? 4 : 3, 0, 7); g.fill(); if (car.isPlayer) { g.strokeStyle = '#ffd23f'; g.lineWidth = 1.5; g.stroke(); } } } // ---------------- UI flow ---------------- function buildMenu() { const list = $('carList'); list.innerHTML = ''; const savedCar = clamp(Store.get('car', 0) | 0, 0, CAR_TYPES.length - 1); const records = Store.get('bestLap', {}); G.carType = CAR_TYPES[savedCar]; // restore last choice (F-007) CAR_TYPES.forEach((ct, i) => { const hex = '#' + ct.color.toString(16).padStart(6, '0'); const card = document.createElement('div'); card.className = 'car-card' + (i === savedCar ? ' sel' : ''); let statsHtml = ''; for (const [k, v] of Object.entries(ct.stats)) statsHtml += `
${k}
`; const best = records[ct.name]; const bestHtml = best != null && best < Infinity ? `
🏅 أفضل جولة: ${fmtTime(best)}
` : ''; card.innerHTML = `
${ct.name}
${bestHtml}${statsHtml}`; card.onclick = () => { document.querySelectorAll('.car-card').forEach(c => c.classList.remove('sel')); card.classList.add('sel'); G.carType = ct; Store.set('car', i); AudioSys.beep(600, 0.07, 0.12); }; list.appendChild(card); }); } function setMuted(m) { // F-008 AudioSys.muted = m; Store.set('sound', m ? 0 : 1); if (AudioSys.master) AudioSys.master.gain.value = m ? 0 : 0.9; syncSoundBtn(); } function syncSoundBtn() { const b = $('soundBtn'); if (b) b.textContent = AudioSys.muted ? '🔇' : '🔊'; } function bindDifficulty() { // F-009 const btns = document.querySelectorAll('.diff-btn'); const sel = () => btns.forEach(b => b.classList.toggle('sel', b.dataset.diff === diffKey)); btns.forEach(b => { b.onclick = () => { diffKey = b.dataset.diff; Store.set('diff', diffKey); sel(); AudioSys.beep(520, 0.06, 0.1); }; }); sel(); } function showFatal(msg) { // F-002 const el = document.getElementById('fatal'); const m = document.getElementById('fatalMsg'); if (el && m) { m.textContent = msg; el.classList.add('show'); } } function startRace() { AudioSys.init(); if (AudioSys.ctx && AudioSys.ctx.state === 'suspended') AudioSys.ctx.resume(); resetRace(); $('menu').classList.remove('show'); $('results').classList.remove('show'); $('hud').classList.add('show'); $('pauseBtn').classList.add('show'); if (isTouchDevice) $('touch').classList.add('show'); G.state = 'countdown'; G.cd = 3.6; lastCountInt = 4; // V-002: fresh countdown — never skip the "3" beep camReady = false; G.player.model.group.position.set(G.player.x, 0, G.player.z); G.player.model.group.rotation.y = G.player.heading; } function backToMenu() { G.state = 'menu'; buildMenu(); // refresh cards (records, saved selection) $('pause').classList.remove('show'); $('results').classList.remove('show'); $('hud').classList.remove('show'); $('pauseBtn').classList.remove('show'); $('touch').classList.remove('show'); $('menu').classList.add('show'); AudioSys.engine(0, 0, false); } function togglePause() { if (G.state === 'race' || G.state === 'countdown') { G.state = 'paused'; $('pause').classList.add('show'); AudioSys.engine(0, 0, false); } else if (G.state === 'paused') { $('pause').classList.remove('show'); G.state = G.raceTime > 0 ? 'race' : 'countdown'; } } function showResults() { G.state = 'finished'; const sorted = G.cars.slice().sort((a, b) => carProgress(b) - carProgress(a)); const rank = sorted.indexOf(G.player) + 1; // personal best lap, per car (F-007) let newRecord = false; if (G.player.finished && G.player.best < Infinity) { const records = Store.get('bestLap', {}); const carName = G.carType.name; if (records[carName] == null || G.player.best < records[carName]) { records[carName] = G.player.best; Store.set('bestLap', records); newRecord = true; } } $('resTitle').textContent = rank === 1 ? '🏆 المركز الأول!' : rank <= 3 ? `🥉 المركز ${rank}` : `المركز ${rank}`; $('resSub').textContent = 'الزمن الإجمالي: ' + fmtTime(G.player.finishTime) + (G.player.best < Infinity ? ' • أفضل جولة: ' + fmtTime(G.player.best) : '') + (newRecord ? ' • 🏅 رقم قياسي جديد!' : ''); const listEl = $('resList'); listEl.innerHTML = ''; sorted.forEach((c, i) => { const row = document.createElement('div'); row.className = 'res-row' + (c.isPlayer ? ' me' : ''); row.innerHTML = `
${i + 1}
${c.name}
${c.finished ? fmtTime(c.finishTime) : 'لم يكمل'}
`; listEl.appendChild(row); }); $('results').classList.add('show'); if (rank === 1) AudioSys.fanfare(); } // ---------------- main loop ---------------- let lastCountInt = 4; function loop() { requestAnimationFrame(loop); const dt = Math.min(clock.getDelta(), 0.05); if (G.state === 'countdown') { G.cd -= dt; const cInt = Math.ceil(G.cd - 0.6); if (cInt !== lastCountInt) { lastCountInt = cInt; if (cInt > 0) { showMsg(String(cInt), 'gold', 0.9); AudioSys.beep(440, 0.18, 0.3); } else if (cInt === 0) { showMsg('انطلق! 🚦', 'cyan', 1); AudioSys.beep(880, 0.5, 0.35); G.state = 'race'; } } if (G.cd < -0.5) G.state = 'race'; Particles.update(dt); updateCamera(dt); } else if (G.state === 'race') { G.raceTime += dt; const inp = readInput(); updatePlayer(dt, inp); updateAI(dt); Particles.update(dt); updateCamera(dt); // finish if (G.player.finished) { G.finishDelay += dt; if (G.finishDelay > 1.6) { showResults(); $('msg').className = ''; } } // DNF safety (F-004): a race can never hang forever else if (G.raceTime >= RACE_TIME_LIMIT) { showResults(); $('msg').className = ''; } } else if (G.state === 'menu') { // slow cinematic orbit around the track const t = clock.elapsedTime * 0.15; camera.position.set( samplesX[0] + Math.cos(t) * 260, 130, samplesZ[0] + Math.sin(t) * 260); camera.lookAt(0, 0, 0); Particles.update(dt); } else if (G.state === 'finished') { // keep world alive behind the results screen const inp = { left: 0, right: 0, gas: 0, brake: 0, nitro: 0, drift: 0 }; updatePlayer(dt, inp); updateAI(dt); Particles.update(dt); updateCamera(dt); } // paused: static // HUD if (G.state === 'race' || G.state === 'countdown' || G.state === 'finished') updateHUD(); if (msgTimer > 0) { msgTimer -= dt; if (msgTimer <= 0) $('msg').className = ''; } renderer.render(scene, camera); } // ---------------- events & boot ---------------- function bindKeyboard() { window.addEventListener('keydown', e => { if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Space'].includes(e.code)) e.preventDefault(); keys[e.code] = true; if (e.code === 'Escape') togglePause(); if (e.code === 'KeyM') setMuted(!AudioSys.muted); if (e.code === 'Enter' && G.state === 'menu') startRace(); }); window.addEventListener('keyup', e => { keys[e.code] = false; }); window.addEventListener('blur', () => { for (const k in keys) keys[k] = false; }); // F-003: auto-pause when the tab is hidden, so a race is never missed document.addEventListener('visibilitychange', () => { if (document.hidden && (G.state === 'race' || G.state === 'countdown')) togglePause(); }); } function bindTouch(id, prop) { const el = $(id); const on = e => { e.preventDefault(); touch[prop] = 1; el.classList.add('on'); }; const off = e => { e.preventDefault(); touch[prop] = 0; el.classList.remove('on'); }; el.addEventListener('pointerdown', on); el.addEventListener('pointerup', off); el.addEventListener('pointercancel', off); el.addEventListener('pointerleave', off); } function boot() { // F-002: friendly Arabic failure instead of a blank page if (typeof THREE === 'undefined') { showFatal('تعذر تحميل مكتبة Three.js من الإنترنت.\nتحقق من اتصالك ثم أعد تحميل الصفحة.'); return; } try { buildTrackData(); initScene(); } catch (err) { console.error('WebGL init failed:', err); showFatal('تعذر تشغيل الرسوميات ثلاثية الأبعاد (WebGL).\nجرّب متصفحاً حديثاً أو فعّل تسريع العتاد في إعدادات المتصفح.'); return; } buildMinimap(); buildMenu(); resetRace(); // show the grid behind the menu bindKeyboard(); camReady = false; $('btnStart').onclick = startRace; $('btnAgain').onclick = startRace; $('btnMenu2').onclick = backToMenu; $('btnResume').onclick = togglePause; $('btnQuit').onclick = backToMenu; $('pauseBtn').onclick = e => { e.stopPropagation(); togglePause(); }; // sound toggle (F-008) + difficulty selector (F-009) $('soundBtn').onclick = () => setMuted(!AudioSys.muted); syncSoundBtn(); bindDifficulty(); isTouchDevice = ('ontouchstart' in window) || navigator.maxTouchPoints > 0; if (isTouchDevice) { bindTouch('tLeft', 'left'); bindTouch('tRight', 'right'); bindTouch('tGas', 'gas'); bindTouch('tBrake', 'brake'); bindTouch('tNitro', 'nitro'); bindTouch('tDrift', 'drift'); } loop(); } // ---------------- boot / test export ---------------- // Browser: auto-boot. Node (unit tests): importing must not start the game. if (typeof window !== 'undefined' && window.document) boot(); if (typeof module !== 'undefined' && module.exports) { module.exports = { G, CAR_TYPES, LAPS, HALF, TRACK_PTS, clamp, lerp, lerpAngle, fmtTime, crossStart, buildTrackData, distToTrack, nearestSample, spawnPos, resetRace, startRace, backToMenu, togglePause, showResults, getRank, updatePlayer, updateAI, carProgress, setMuted, Store, DIFFS, diff: () => diffKey, raceLimit: () => RACE_TIME_LIMIT, track: () => ({ N, SEG_LEN, samplesX, samplesZ, tanX, tanZ, sideX, sideZ, arcLen, curv, limits, trackMinX, trackMaxX, trackMinZ, trackMaxZ }), }; }