vice city online: the bare online core

This commit is contained in:
CRTkafa 2026-11-17 14:27:34 +07:00
commit 2f98475c19
256 changed files with 144219 additions and 0 deletions

393
src/core/CdStreamWeb.cpp Normal file
View file

@ -0,0 +1,393 @@
#ifdef __EMSCRIPTEN__
// Streaming for the browser build: image files (models/gta3.img) are not in the
// in-memory file system, every read is an HTTP range request to the data host.
// Reads stay asynchronous like on the PC; CdStreamSync yields to the browser
// (ASYNCIFY) until the request is done.
#include "common.h"
#include "CdStream.h"
#include <emscripten.h>
#include <emscripten/fetch.h>
#include <string>
#include <vector>
#define CDTRACE(f, ...) printf("%s: " f "\n", "cdvd_stream", ## __VA_ARGS__)
static const int MAX_RETRIES = 3;
struct CdReadInfo
{
uint32 nSectorOffset;
uint32 nSectorsToRead;
void *pBuffer;
int32 nImage;
int32 nStatus;
int32 nRetries;
bool bReading;
bool bBlockFetch;
};
static char gCdImageNames[MAX_CDIMAGES+1][64];
static std::string gImgUrls[MAX_CDIMAGES];
static std::string gImgKeys[MAX_CDIMAGES]; // lower-case path, the key of Module.vcImages
static uint32 gImgSizes[MAX_CDIMAGES];
static int32 gNumImages;
static int32 gNumChannels;
static CdReadInfo *gpReadInfo;
static int32 lastPosnRead;
#ifdef FLUSHABLE_STREAMING
// A request in flight cannot be cancelled, so a flush just waits for it in CdStreamSync.
bool flushStream[MAX_CDCHANNELS];
#endif
// "MODELS\\GTA3.IMG" -> "<data url>/models/gta3.img"
static std::string
ImageUrl(const char *path)
{
char *base = (char*)EM_ASM_PTR({ return stringToNewUTF8(Module.vcDataUrl || "data"); });
std::string url = base;
free(base);
url += '/';
for(const char *p = path; *p; p++)
url += *p == '\\' ? '/' : (char)tolower(*p);
return url;
}
// Reads are small and scattered, and every request costs a round trip to the data host.
// The image is therefore fetched in aligned blocks, and the latest blocks are kept: models
// that sit next to each other in the image (the same area) come out of memory.
static const uint32 BLOCK_SIZE = 2 * 1024 * 1024;
static const int NUM_BLOCKS = 48;
struct Block
{
int32 image;
uint32 index;
uint32 lastUse;
std::vector<uint8> data;
};
static Block gBlocks[NUM_BLOCKS];
static uint32 gBlockClock;
static Block *
FindBlock(int32 image, uint32 index)
{
for(int i = 0; i < NUM_BLOCKS; i++)
if(gBlocks[i].image == image && gBlocks[i].index == index && !gBlocks[i].data.empty())
return &gBlocks[i];
return nil;
}
static Block *
ClaimBlock(int32 image, uint32 index)
{
Block *victim = &gBlocks[0];
for(int i = 0; i < NUM_BLOCKS; i++){
if(gBlocks[i].data.empty()){ victim = &gBlocks[i]; break; }
if(gBlocks[i].lastUse < victim->lastUse) victim = &gBlocks[i];
}
victim->image = image;
victim->index = index;
victim->lastUse = ++gBlockClock;
victim->data.clear();
return victim;
}
// Copies [from, from+size) out of a block, if the whole range lies inside it.
static bool
CopyFromBlock(int32 image, uint64 from, uint32 size, void *dst)
{
uint32 index = (uint32)(from / BLOCK_SIZE);
Block *b = FindBlock(image, index);
uint64 start = from - (uint64)index * BLOCK_SIZE;
if(!b || start + size > b->data.size()) return false;
memcpy(dst, &b->data[start], size);
b->lastUse = ++gBlockClock;
return true;
}
static void StartFetch(int32 channel);
static void
OnFetchDone(emscripten_fetch_t *fetch)
{
int32 channel = (int32)(intptr_t)fetch->userData;
CdReadInfo *ch = &gpReadInfo[channel];
uint32 want = ch->nSectorsToRead * CDSTREAM_SECTOR_SIZE;
bool ok = fetch->status == 206 || fetch->status == 200;
if(ok){
uint64 from = (uint64)ch->nSectorOffset * CDSTREAM_SECTOR_SIZE;
uint64 blockStart = from / BLOCK_SIZE * BLOCK_SIZE;
bool blockFetch = ch->bBlockFetch;
if(blockFetch){
Block *b = ClaimBlock(ch->nImage, (uint32)(from / BLOCK_SIZE));
b->data.assign((const uint8*)fetch->data, (const uint8*)fetch->data + fetch->numBytes);
uint64 start = from - blockStart;
uint64 n = start >= b->data.size() ? 0 : Min((uint64)want, b->data.size() - start);
if(n) memcpy(ch->pBuffer, &b->data[start], n);
if(n < want) memset((uint8*)ch->pBuffer + n, 0, want - n);
}else{
uint64 n = fetch->numBytes < want ? fetch->numBytes : want;
memcpy(ch->pBuffer, fetch->data, n);
if(n < want)
memset((uint8*)ch->pBuffer + n, 0, want - n);
}
}
emscripten_fetch_close(fetch);
EM_ASM({ if(Module.vcBusy) Module.vcBusy($0); }, -1);
if(!ok && ch->nRetries++ < MAX_RETRIES){
CDTRACE("read failed (HTTP %d), retrying", fetch->status);
StartFetch(channel);
return;
}
ch->nStatus = ok ? STREAM_NONE : STREAM_ERROR;
ch->nSectorsToRead = 0;
ch->bReading = false;
}
static void
StartFetch(int32 channel)
{
CdReadInfo *ch = &gpReadInfo[channel];
uint64 from = (uint64)ch->nSectorOffset * CDSTREAM_SECTOR_SIZE;
uint64 to = from + (uint64)ch->nSectorsToRead * CDSTREAM_SECTOR_SIZE - 1;
static char range[64];
// Ask for the whole aligned block when the request lies inside one; a request that
// crosses a block border is fetched as it is.
ch->bBlockFetch = from / BLOCK_SIZE == to / BLOCK_SIZE;
if(ch->bBlockFetch){
uint64 blockStart = from / BLOCK_SIZE * BLOCK_SIZE;
uint64 blockEnd = Min(blockStart + BLOCK_SIZE, (uint64)gImgSizes[ch->nImage]) - 1;
snprintf(range, sizeof(range), "bytes=%llu-%llu", (unsigned long long)blockStart, (unsigned long long)blockEnd);
}else
snprintf(range, sizeof(range), "bytes=%llu-%llu", (unsigned long long)from, (unsigned long long)to);
const char *headers[] = { "Range", range, nil };
// An image the page already holds in memory (Module.vcImages) is copied, no request needed.
if(EM_ASM_INT({
const key = UTF8ToString($0);
if(Module.vcReadLog) Module.vcReadLog.push($1 + ":" + $2);
const img = Module.vcImages && Module.vcImages[key];
if(!img){
// Pieces of the image that have already arrived are used at once. A piece the game
// asks for and does not have yet moves to the front of the download.
const part = Module.vcPart;
if(part && part.key === key){
const first = Math.floor($1 / part.size);
const last = Math.floor(($1 + $2 - 1) / part.size);
let all = true;
for(let i = last; i >= first; i--){
if(!part.done[i]){
all = false;
part.want.push(i);
}
}
if(all){
const n = Math.max(0, Math.min($2, part.buf.length - $1));
HEAPU8.set(part.buf.subarray($1, $1 + n), $3);
HEAPU8.fill(0, $3 + n, $3 + $2);
return 1;
}
}
// The start pack: what the game reads at the spawn point, ahead of the whole image.
const pack = Module.vcStart;
if(!pack || pack.key !== key) return 0;
let lo = 0;
let hi = pack.ranges.length - 1;
while(lo <= hi){
const mid = (lo + hi) >> 1;
const r = pack.ranges[mid];
if($1 < r.at) hi = mid - 1;
else if($1 >= r.at + r.size) lo = mid + 1;
else{
if($1 + $2 > r.at + r.size) return 0;
const from = r.pos + $1 - r.at;
HEAPU8.set(pack.data.subarray(from, from + $2), $3);
return 1;
}
}
return 0;
}
const n = Math.max(0, Math.min($2, img.length - $1));
HEAPU8.set(img.subarray($1, $1 + n), $3);
HEAPU8.fill(0, $3 + n, $3 + $2);
return 1;
}, gImgKeys[ch->nImage].c_str(), (double)from, (double)(to - from + 1), ch->pBuffer)){
ch->nStatus = STREAM_NONE;
ch->nSectorsToRead = 0;
ch->bReading = false;
return;
}
if(CopyFromBlock(ch->nImage, from, (uint32)(to - from + 1), ch->pBuffer)){
ch->nStatus = STREAM_NONE;
ch->nSectorsToRead = 0;
ch->bReading = false;
return;
}
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
attr.requestHeaders = headers;
attr.userData = (void*)(intptr_t)channel;
attr.onsuccess = OnFetchDone;
attr.onerror = OnFetchDone;
ch->bReading = true;
EM_ASM({ if(Module.vcBusy) Module.vcBusy($0); }, 1);
emscripten_fetch(&attr, gImgUrls[ch->nImage].c_str());
}
void
CdStreamInitThread(void)
{
}
void
CdStreamInit(int32 numChannels)
{
gNumImages = 0;
gNumChannels = numChannels;
gpReadInfo = (CdReadInfo*)calloc(numChannels, sizeof(CdReadInfo));
}
uint32
GetGTA3ImgSize(void)
{
return gImgSizes[0];
}
void
CdStreamShutdown(void)
{
free(gpReadInfo);
gpReadInfo = nil;
}
int32
CdStreamRead(int32 channel, void *buffer, uint32 offset, uint32 size)
{
ASSERT(channel < gNumChannels);
lastPosnRead = size + offset;
int32 image = _GET_INDEX(offset);
if(image >= gNumImages)
return STREAM_NONE;
CdReadInfo *ch = &gpReadInfo[channel];
if(ch->nSectorsToRead != 0 || ch->bReading){
if(ch->nImage == image && ch->nSectorOffset == _GET_OFFSET(offset) && ch->nSectorsToRead >= size)
return STREAM_SUCCESS;
return STREAM_NONE;
}
ch->nImage = image;
ch->nStatus = STREAM_NONE;
ch->nSectorOffset = _GET_OFFSET(offset);
ch->nSectorsToRead = size;
ch->pBuffer = buffer;
ch->nRetries = 0;
StartFetch(channel);
return STREAM_SUCCESS;
}
int32
CdStreamGetStatus(int32 channel)
{
CdReadInfo *ch = &gpReadInfo[channel];
if(ch->bReading)
return STREAM_READING;
if(ch->nSectorsToRead != 0)
return STREAM_WAITING;
int32 status = ch->nStatus;
ch->nStatus = STREAM_NONE;
return status;
}
int32
CdStreamGetLastPosn(void)
{
return lastPosnRead;
}
int32
CdStreamSync(int32 channel)
{
CdReadInfo *ch = &gpReadInfo[channel];
while(ch->bReading)
emscripten_sleep(1);
#ifdef FLUSHABLE_STREAMING
if(flushStream[channel]){
flushStream[channel] = false;
ch->nStatus = STREAM_NONE;
}
#endif
return ch->nStatus;
}
void
AddToQueue(Queue *queue, int32 item)
{
queue->items[queue->tail] = item;
queue->tail = (queue->tail + 1) % queue->size;
}
int32
GetFirstInQueue(Queue *queue)
{
return queue->head == queue->tail ? -1 : queue->items[queue->head];
}
void
RemoveFirstInQueue(Queue *queue)
{
if(queue->head != queue->tail)
queue->head = (queue->head + 1) % queue->size;
}
// Image sizes come from the data host's manifest.json ("ranged" list), which the
// page loads before start-up.
bool
CdStreamAddImage(char const *path)
{
ASSERT(gNumImages < MAX_CDIMAGES);
std::string url = ImageUrl(path);
double size = EM_ASM_DOUBLE({
const rel = UTF8ToString($0);
const hit = (Module.vcRanged || []).find(f => rel.endsWith("/" + f.path));
return hit ? hit.size : -1;
}, url.c_str());
if(size < 0){
CDTRACE("%s is not in the manifest", url.c_str());
return false;
}
gImgUrls[gNumImages] = url;
std::string key;
for(const char *p = path; *p; p++)
key += *p == '\\' ? '/' : (char)tolower(*p);
gImgKeys[gNumImages] = key;
gImgSizes[gNumImages] = (uint32)size;
strncpy(gCdImageNames[gNumImages], path, 63);
gNumImages++;
return true;
}
char *
CdStreamGetImageName(int32 cd)
{
return cd < gNumImages ? gCdImageNames[cd] : nil;
}
void
CdStreamRemoveImages(void)
{
for(int32 i = 0; i < gNumChannels; i++)
CdStreamSync(i);
gNumImages = 0;
}
int32
CdStreamGetNumImages(void)
{
return gNumImages;
}
#endif

455
src/core/WebFile.cpp Normal file
View file

@ -0,0 +1,455 @@
#include "common.h"
#include "crossplatform.h"
#include "WebFile.h"
#ifndef __EMSCRIPTEN__
FILE *
WebFileOpen(const char *path, const char *mode)
{
return fcaseopen(path, mode);
}
bool
WebStreamsReady(void)
{
return true;
}
bool
WebFilePrefetch(const char *path, double fraction)
{
return true;
}
#else
#include <emscripten.h>
#include <emscripten/fetch.h>
#include <string>
#include <vector>
#define WEBFILE_TRACE(f, ...) printf("webfile: " f "\n", ## __VA_ARGS__)
static const int64 CHUNK_SIZE = 256 * 1024; // one HTTP request
static const int MAX_CHUNKS = 24; // cached per file (6 MB)
static const int MAX_RETRIES = 3;
struct WebChunk
{
int64 index;
std::vector<uint8> data;
uint32 lastUse;
bool loading;
bool failed;
};
struct WebFileState
{
std::string url;
std::string rel;
bool closing; // closed by the game, deleted when its last fetch lands
int64 size;
int64 pos;
WebChunk chunks[MAX_CHUNKS];
uint32 useCounter;
bool samples; // sfx.raw: a missing part may play as silence
};
static std::vector<WebFileState*> openFiles;
// Chunks fetched ahead of a radio switch.
struct PrefetchChunk
{
std::string rel;
int64 index;
std::vector<uint8> data;
uint32 lastUse;
bool loading;
bool failed;
};
static const size_t MAX_PREFETCH = 16;
static std::vector<PrefetchChunk*> prefetched;
static uint32 prefetchCounter;
static PrefetchChunk *
FindPrefetched(const std::string &rel, int64 index)
{
for(PrefetchChunk *p : prefetched)
if(p->index == index && p->rel == rel)
return p;
return nil;
}
static bool
GamePlaying(void)
{
return EM_ASM_INT({ return window.vcPlaying ? 1 : 0; }) != 0;
}
struct FetchJob
{
WebFileState *file;
WebChunk *chunk;
int retries;
};
static void StartChunkFetch(FetchJob *job);
static void
OnChunkDone(emscripten_fetch_t *fetch)
{
FetchJob *job = (FetchJob*)fetch->userData;
bool ok = fetch->status == 206 || fetch->status == 200;
if(ok)
job->chunk->data.assign((const uint8*)fetch->data, (const uint8*)fetch->data + fetch->numBytes);
int status = fetch->status;
emscripten_fetch_close(fetch);
if(!ok && job->retries++ < MAX_RETRIES){
WEBFILE_TRACE("%s: HTTP %d, retrying", job->file->url.c_str(), status);
StartChunkFetch(job);
return;
}
job->chunk->failed = !ok;
job->chunk->loading = false;
WebFileState *file = job->file;
delete job;
if(file->closing){
for(int i = 0; i < MAX_CHUNKS; i++)
if(file->chunks[i].loading)
return;
delete file;
}
}
static void
StartChunkFetch(FetchJob *job)
{
int64 from = job->chunk->index * CHUNK_SIZE;
int64 to = Min(from + CHUNK_SIZE, job->file->size) - 1;
char range[64];
snprintf(range, sizeof(range), "bytes=%lld-%lld", (long long)from, (long long)to);
const char *headers[] = { "Range", range, nil };
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
attr.requestHeaders = headers; // copied by emscripten_fetch
attr.userData = job;
attr.onsuccess = OnChunkDone;
attr.onerror = OnChunkDone;
emscripten_fetch(&attr, job->file->url.c_str());
}
// Returns the slot holding chunk `index`, starting a fetch if it is not there yet.
static WebChunk *
RequestChunk(WebFileState *f, int64 index)
{
if(index < 0 || index * CHUNK_SIZE >= f->size)
return nil;
WebChunk *victim = nil;
for(int i = 0; i < MAX_CHUNKS; i++){
WebChunk *c = &f->chunks[i];
if(c->index == index && !c->failed){
c->lastUse = ++f->useCounter;
return c;
}
if(c->loading)
continue;
if(victim == nil || c->lastUse < victim->lastUse)
victim = c;
}
if(victim == nil)
return nil; // every slot is loading; the caller waits and asks again
victim->index = index;
victim->data.clear();
PrefetchChunk *ready = FindPrefetched(f->rel, index);
if(ready && !ready->loading && !ready->failed){
victim->data = ready->data;
victim->loading = false;
victim->failed = false;
victim->lastUse = ++f->useCounter;
return victim;
}
victim->loading = true;
victim->failed = false;
victim->lastUse = ++f->useCounter;
StartChunkFetch(new FetchJob{ f, victim, 0 });
return victim;
}
// One request for a big read (a whole sample bank), straight into the caller's buffer.
static ssize_t
DirectRead(WebFileState *f, char *buf, size_t size)
{
struct Job { char *buf; size_t size; ssize_t result; bool done; } job = { buf, size, -1, false };
char range[64];
snprintf(range, sizeof(range), "bytes=%lld-%lld", (long long)f->pos, (long long)(f->pos + size - 1));
const char *headers[] = { "Range", range, nil };
// The first sound bank, which the game waits for, is also a file of its own: the CDN caches that name,
// while ranges of the big file crawl through it. If it is missing or differs, the range read takes over.
bool useHead = f->samples && f->pos == 0;
std::string headUrl = f->url + ".head.bin";
for(int attempt = 0; attempt <= MAX_RETRIES && job.result < 0; attempt++){
bool head = useHead && attempt == 0;
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
attr.requestHeaders = head ? nil : headers;
attr.userData = &job;
attr.onsuccess = [](emscripten_fetch_t *fetch){
Job *j = (Job*)fetch->userData;
size_t n = Min(j->size, (size_t)fetch->numBytes);
memcpy(j->buf, fetch->data, n);
j->result = n;
j->done = true;
emscripten_fetch_close(fetch);
};
attr.onerror = [](emscripten_fetch_t *fetch){
((Job*)fetch->userData)->done = true;
emscripten_fetch_close(fetch);
};
job.done = false;
double waitStart = emscripten_get_now();
emscripten_fetch(&attr, head ? headUrl.c_str() : f->url.c_str());
while(!job.done)
emscripten_sleep(1);
if(head && job.result != (ssize_t)size) job.result = -1;
printf("[web] game waited %.0f ms for a direct read of %s (%zu bytes)\n", emscripten_get_now() - waitStart, f->url.c_str(), size);
}
if(job.result > 0)
f->pos += job.result;
return job.result;
}
static ssize_t
CookieRead(void *cookie, char *buf, size_t size)
{
WebFileState *f = (WebFileState*)cookie;
if(f->pos >= f->size)
return 0;
size = (size_t)Min((int64)size, f->size - f->pos);
if((int64)size >= 4 * CHUNK_SIZE)
return DirectRead(f, buf, size);
size_t done = 0;
bool silenceOk = f->samples && GamePlaying();
while(done < size && f->pos < f->size){
int64 index = f->pos / CHUNK_SIZE;
WebChunk *c;
if(silenceOk){
c = RequestChunk(f, index);
if(c == nil || c->loading || c->failed){
size_t gap = (size_t)Min((int64)(size - done), (index + 1) * CHUNK_SIZE - f->pos);
memset(buf + done, 0, gap);
done += gap;
f->pos += gap;
continue;
}
}
double waitStart = emscripten_get_now();
while((c = RequestChunk(f, index)) == nil || c->loading)
emscripten_sleep(1);
double waited = emscripten_get_now() - waitStart;
if(waited > 100.0)
printf("[web] game waited %.0f ms for %s (chunk %lld)\n", waited, f->url.c_str(), (long long)index);
if(c->failed)
return done > 0 ? (ssize_t)done : -1;
// Streams read forward: have the next chunk on its way before it is needed.
RequestChunk(f, index + 1);
int64 offset = f->pos - index * CHUNK_SIZE;
size_t n = (size_t)Min((int64)(size - done), (int64)c->data.size() - offset);
if(n == 0)
break;
memcpy(buf + done, c->data.data() + offset, n);
done += n;
f->pos += n;
}
return done;
}
static int
CookieSeek(void *cookie, off_t *offset, int whence)
{
WebFileState *f = (WebFileState*)cookie;
int64 base = whence == SEEK_SET ? 0 : whence == SEEK_CUR ? f->pos : f->size;
int64 pos = base + *offset;
if(pos < 0)
return -1;
f->pos = pos;
*offset = pos;
return 0;
}
static int
CookieClose(void *cookie)
{
WebFileState *f = (WebFileState*)cookie;
for(size_t i = 0; i < openFiles.size(); i++)
if(openFiles[i] == f){
openFiles.erase(openFiles.begin() + i);
break;
}
// A fetch still in flight writes into the chunk, so the state lives until it lands.
for(int i = 0; i < MAX_CHUNKS; i++)
if(f->chunks[i].loading){
f->closing = true;
return 0;
}
delete f;
return 0;
}
static std::string
RelativePath(const char *path)
{
std::string rel;
for(const char *p = path; *p; p++)
rel += *p == '\\' ? '/' : (char)tolower(*p);
while(rel.compare(0, 2, "./") == 0)
rel.erase(0, 2);
return rel;
}
static double
RangedSize(const std::string &rel)
{
return EM_ASM_DOUBLE({
const map = Module.vcRangedMap;
const size = map && map.get(UTF8ToString($0));
return size === undefined ? -1 : size;
}, rel.c_str());
}
static std::string
DataUrl(const std::string &rel)
{
char *base = (char*)EM_ASM_PTR({ return stringToNewUTF8(Module.vcDataUrl || "data"); });
std::string url = std::string(base) + "/" + rel;
free(base);
return url;
}
static void
OnPrefetchDone(emscripten_fetch_t *fetch)
{
PrefetchChunk *p = (PrefetchChunk*)fetch->userData;
p->failed = !(fetch->status == 206 || fetch->status == 200);
if(!p->failed)
p->data.assign((const uint8*)fetch->data, (const uint8*)fetch->data + fetch->numBytes);
p->loading = false;
emscripten_fetch_close(fetch);
}
static bool
PrefetchChunkReady(const std::string &rel, int64 size, int64 index)
{
if(index < 0 || index * CHUNK_SIZE >= size)
return true;
PrefetchChunk *p = FindPrefetched(rel, index);
if(p && p->failed && !p->loading){
// Leave it to the ordinary read, which retries and waits.
return true;
}
if(p){
p->lastUse = ++prefetchCounter;
return !p->loading;
}
if(prefetched.size() >= MAX_PREFETCH){
PrefetchChunk *victim = nil;
for(PrefetchChunk *c : prefetched)
if(!c->loading && (victim == nil || c->lastUse < victim->lastUse))
victim = c;
if(victim == nil)
return false;
p = victim;
}else{
p = new PrefetchChunk();
prefetched.push_back(p);
}
p->rel = rel;
p->index = index;
p->data.clear();
p->lastUse = ++prefetchCounter;
p->loading = true;
p->failed = false;
int64 from = index * CHUNK_SIZE;
char range[64];
snprintf(range, sizeof(range), "bytes=%lld-%lld", (long long)from, (long long)(Min(from + CHUNK_SIZE, size) - 1));
const char *headers[] = { "Range", range, nil };
emscripten_fetch_attr_t attr;
emscripten_fetch_attr_init(&attr);
strcpy(attr.requestMethod, "GET");
attr.attributes = EMSCRIPTEN_FETCH_LOAD_TO_MEMORY;
attr.requestHeaders = headers;
attr.userData = p;
attr.onsuccess = OnPrefetchDone;
attr.onerror = OnPrefetchDone;
emscripten_fetch(&attr, DataUrl(rel).c_str());
return false;
}
bool
WebFilePrefetch(const char *path, double fraction)
{
if(!GamePlaying())
return true;
std::string rel = RelativePath(path);
double size = RangedSize(rel);
if(size < 0)
return true;
int64 target = (int64)(Clamp(fraction, 0.0, 1.0) * size) / CHUNK_SIZE;
bool ready = PrefetchChunkReady(rel, (int64)size, 0);
// The decoder looks for a tag at the very end of the file when it opens it.
ready = PrefetchChunkReady(rel, (int64)size, ((int64)size - 1) / CHUNK_SIZE) && ready;
ready = PrefetchChunkReady(rel, (int64)size, target) && ready;
ready = PrefetchChunkReady(rel, (int64)size, target + 1) && ready;
return ready;
}
FILE *
WebFileOpen(const char *path, const char *mode)
{
std::string rel = RelativePath(path);
double size = RangedSize(rel);
if(size < 0 || mode[0] != 'r')
return fcaseopen(path, mode);
WebFileState *f = new WebFileState();
f->url = DataUrl(rel);
f->rel = rel;
f->size = (int64)size;
for(int i = 0; i < MAX_CHUNKS; i++)
f->chunks[i].index = -1;
f->samples = rel.size() >= 4 && rel.compare(rel.size() - 4, 4, ".raw") == 0;
if(!f->samples)
openFiles.push_back(f);
cookie_io_functions_t io = { CookieRead, nil, CookieSeek, CookieClose };
return fopencookie(f, mode, io);
}
bool
WebStreamsReady(void)
{
if(openFiles.empty() || !GamePlaying())
return true;
bool ready = true;
for(WebFileState *f : openFiles){
if(f->pos >= f->size)
continue;
int64 index = f->pos / CHUNK_SIZE;
for(int64 i = index; i <= index + 1; i++){
if(i * CHUNK_SIZE >= f->size)
break;
WebChunk *c = RequestChunk(f, i);
if(c == nil || c->loading || c->failed)
ready = false;
}
}
return ready;
}
#endif

14
src/core/WebFile.h Normal file
View file

@ -0,0 +1,14 @@
#pragma once
// Opens a game file for reading. In the browser build, files the data manifest lists
// as "ranged" (big audio files) are not in memory: they are read over HTTP range
// requests in chunks, behind an ordinary FILE*. Everywhere else this is fcaseopen.
FILE *WebFileOpen(const char *path, const char *mode);
// False while a music or ambience file still waits for the data its decoder reads next. The game
// must not wait for the network: the stream skips its update and the sound catches up by itself.
bool WebStreamsReady(void);
// Radio switch: fetches the start of the file and the part around `fraction` (0..1) in the background.
// True once they are here, or when there is nothing to wait for. Opening the file afterwards does not wait.
bool WebFilePrefetch(const char *path, double fraction);

34
src/online/Online.cpp Normal file
View file

@ -0,0 +1,34 @@
#include "common.h"
#include "Online.h"
#include "OnlineSpawn.h"
#include "OnlineNet.h"
#include "World.h"
static bool spawned;
void
COnline::Init(void)
{
COnlineSpawn::Load();
COnlineNet::Load();
}
void
COnline::Reset(void)
{
spawned = false;
COnlineNet::Reset();
}
// Runs after the scripts each frame. The free roam script creates the player on its
// first frame; the player is then moved to the beach once.
void
COnline::Process(void)
{
if(!spawned && FindPlayerPed()){
COnlineSpawn::SpawnPlayer();
COnlineNet::GiveStartWeapons();
spawned = true;
}
COnlineNet::Process();
}

10
src/online/Online.h Normal file
View file

@ -0,0 +1,10 @@
#pragma once
// Free roam online: entry points the game calls (see #ifdef ONLINE in core/).
class COnline
{
public:
static void Init(void);
static void Reset(void);
static void Process(void);
};

30
src/online/OnlineData.cpp Normal file
View file

@ -0,0 +1,30 @@
#include "common.h"
#include "OnlineData.h"
#include <fstream>
#include <string>
#ifdef _WIN32
#include <windows.h>
#endif
void
OnlineDataError(const char *path, const char *what)
{
std::string text = std::string("Online data error:\n") + path + ": " + what;
#ifdef _WIN32
MessageBoxA(nil, text.c_str(), "vc-online", MB_OK | MB_ICONERROR);
#endif
printf("%s\n", text.c_str());
exit(1);
}
nlohmann::json
OnlineLoadJson(const char *path)
{
std::ifstream in(path);
nlohmann::json j = in ? nlohmann::json::parse(in, nil, false) : nlohmann::json();
if(j.is_discarded() || !j.is_object())
OnlineDataError(path, "cannot read the file");
return j;
}

6
src/online/OnlineData.h Normal file
View file

@ -0,0 +1,6 @@
#pragma once
#include "../../vendor/nlohmann/json.hpp"
// Reads a data file of the online mode; a missing or broken file stops the game with a message.
nlohmann::json OnlineLoadJson(const char *path);
[[noreturn]] void OnlineDataError(const char *path, const char *what);

1253
src/online/OnlineNet.cpp Normal file

File diff suppressed because it is too large Load diff

19
src/online/OnlineNet.h Normal file
View file

@ -0,0 +1,19 @@
#pragma once
// Connection to the game server: sends the local player's state and shows the other players.
class COnlineNet
{
public:
static void Load(void); // reads online/net.json
static void Process(void); // every frame while playing
static void GiveStartWeapons(void); // the weapons every player starts with
// True when ped is another player; a hit from the local player goes to the server.
static bool RemoteHit(class CPed *ped, class CEntity *by, int weapon, float damage);
static bool IsRemotePlayer(class CEntity *e);
static float AimAmount(void); // 0 walking around, 1 right button fully aimed
static float AimFov(float normal);
static float AimDistance(void);
static void DrawBubbles(void); // what players said, above their heads
static void PumpOutbox(void); // page messages to the server, every frame even in menus
static void Reset(void); // the world is being restarted: drop the remote players
};

View file

@ -0,0 +1,78 @@
#include "common.h"
#include "OnlineSpawn.h"
#include "General.h"
#include "World.h"
#include "Streaming.h"
#include "PlayerPed.h"
#include "Camera.h"
#include "OnlineData.h"
#include <vector>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
struct SpawnPoint
{
CVector pos;
float heading;
};
static std::vector<SpawnPoint> points;
static float spreadRadius;
void
COnlineSpawn::Load(void)
{
nlohmann::json j = OnlineLoadJson("online/spawn.json");
if(!j.contains("points") || !j["points"].is_array() || j["points"].empty())
OnlineDataError("online/spawn.json", "\"points\" must list at least one spawn point");
if(!j.contains("spreadRadius") || !j["spreadRadius"].is_number())
OnlineDataError("online/spawn.json", "\"spreadRadius\" is missing");
points.clear();
for(auto &p : j["points"]){
if(!p.contains("x") || !p.contains("y") || !p.contains("heading"))
OnlineDataError("online/spawn.json", "every point needs x, y and heading");
points.push_back({ CVector(p["x"].get<float>(), p["y"].get<float>(), 0.0f), p["heading"].get<float>() });
}
spreadRadius = j["spreadRadius"].get<float>();
}
// A random point, moved a little so players joining together do not stack up.
// The ground height is looked up once the area's collision is loaded. Heading in degrees, as CRestart uses.
void
COnlineSpawn::Pick(CVector *pos, float *heading)
{
const SpawnPoint &p = points[CGeneral::GetRandomNumberInRange(0, (int32)points.size())];
#ifdef __EMSCRIPTEN__
// The game's own generator starts from the same seed in every browser: everybody would draw the same spot.
float angle = (float)EM_ASM_DOUBLE({ return Math.random(); }) * TWOPI;
float dist = (float)EM_ASM_DOUBLE({ return Math.sqrt(Math.random()); }) * spreadRadius;
#else
float angle = CGeneral::GetRandomNumberInRange(0.0f, TWOPI);
float dist = CGeneral::GetRandomNumberInRange(0.0f, spreadRadius);
#endif
*pos = p.pos + CVector(Cos(angle) * dist, Sin(angle) * dist, 0.0f);
CStreaming::LoadSceneCollision(*pos);
bool found;
float z = CWorld::FindGroundZFor3DCoord(pos->x, pos->y, 1000.0f, &found);
pos->z = (found ? z : 10.0f) + 1.0f;
*heading = p.heading;
}
void
COnlineSpawn::SpawnPlayer(void)
{
CPlayerPed *player = FindPlayerPed();
if(player == nil)
return;
CVector pos;
float heading;
Pick(&pos, &heading);
CStreaming::LoadScene(pos);
player->Teleport(pos);
heading = DEGTORAD(heading);
player->m_fRotationCur = player->m_fRotationDest = heading;
player->SetHeading(heading);
TheCamera.SetCameraDirectlyBehindForFollowPed_CamOnAString();
}

11
src/online/OnlineSpawn.h Normal file
View file

@ -0,0 +1,11 @@
#pragma once
// Where players appear: on joining and after every death or arrest.
// The points come from online/spawn.json next to the game data.
class COnlineSpawn
{
public:
static void Load(void);
static void Pick(CVector *pos, float *heading);
static void SpawnPlayer(void);
};