Skip to content

Commit

Permalink
Support emscipten target -> wasm better
Browse files Browse the repository at this point in the history
  • Loading branch information
Hugh Sanderson committed Aug 28, 2024
1 parent 9e252c0 commit 48b8b9f
Show file tree
Hide file tree
Showing 8 changed files with 124 additions and 53 deletions.
3 changes: 1 addition & 2 deletions project/ToolkitBuild.xml
Original file line number Diff line number Diff line change
Expand Up @@ -640,8 +640,7 @@
<vflag name="-framework" value="QuartzCore" />
</section>


<section if="emscripten">
<section if="jsprime">
<vflag name="-s" value="EXPORTED_FUNCTIONS=['_malloc']" />
</section>

Expand Down
13 changes: 11 additions & 2 deletions project/src/audio/OpenALSound.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -464,7 +464,6 @@ class OpenALDoubleBufferChannel : public OpenALSourceChannel
};



class OpenALStreamChannel : public OpenALDoubleBufferChannel
{
public:
Expand Down Expand Up @@ -498,10 +497,20 @@ class OpenALStreamChannel : public OpenALDoubleBufferChannel
}

//LOG_SOUND("STREAM\n");
char pcm[MAX_STREAM_BUFFER_SIZE];

int bytes = ( (stream->getIsStereo() ? 4 : 2) * stream->getRate() * 400/1000 );
if (bytes > MAX_STREAM_BUFFER_SIZE)
bytes = MAX_STREAM_BUFFER_SIZE;

#ifdef EMSCRIPTEN
std::vector<char> pcmFillBuffer(bytes);
char *pcm = pcmFillBuffer.data();
#else
char pcm[MAX_STREAM_BUFFER_SIZE];
#endif



bytes = bytes & ~7;
int size = 0;
int emptyBuffersCount = 0;
Expand Down
62 changes: 49 additions & 13 deletions project/src/common/Font.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@
#define strcasecmp stricmp
#endif

#ifdef HXCPP_JS_PRIME
#if (defined(HXCPP_JS_PRIME) || defined(EMSCRIPTEN) )
#define LINKED_FONT_DATA
#endif

#ifdef LINKED_FONT_DATA
#include <zlib.h>

extern int gSansFullSize;
Expand Down Expand Up @@ -375,13 +379,20 @@ const char *RemapFontName(const char *inName)
typedef std::map<FontInfo, Font *> FontMap;
FontMap sgFontMap;

#ifdef HXCPP_JS_PRIME
BufferData *decompressFontData(int srcLen, int destLen, const unsigned char *inData)
#ifdef LINKED_FONT_DATA
FontBuffer decompressFontData(int srcLen, int destLen, const unsigned char *inData)
{
BufferData *data = new BufferData();
#ifdef JS_PRIME
FontBuffer data = new FontBuffer();
data->IncRef();

data->setDataSize(destLen,false);
Bytef *dataPtr = (Bytef*)data->getData();
#else
AutoGCUnblocking unblock;
ByteArray byteArray(destLen);
Bytef *dataPtr = byteArray.Bytes();
FontBuffer data = new AutoGCRoot(byteArray.mValue);
#endif

z_stream z;
memset(&z,0,sizeof(z_stream));
Expand All @@ -393,8 +404,8 @@ BufferData *decompressFontData(int srcLen, int destLen, const unsigned char *inD
z.next_in = (Bytef*)inData;
z.avail_in = srcLen;

z.next_out = (Bytef*)data->getData();
z.avail_out = data->getDataSize();
z.next_out = dataPtr;
z.avail_out = destLen;
int code = 0;
if( (code = ::inflate(&z,flush)) < 0 )
{
Expand All @@ -408,6 +419,28 @@ BufferData *decompressFontData(int srcLen, int destLen, const unsigned char *inD
}
#endif

class EmptyFontFace : public FontFace
{
int height;

public:
EmptyFontFace(int inHeight) : height(inHeight) { }

bool GetGlyphInfo(int inChar, int &outW, int &outH, int &outAdvance,
int &outOx, int &outOy)
{
return false;
}
void RenderGlyph(int inChar,const RenderTarget &outTarget) { }

void UpdateMetrics(TextLineMetrics &ioMetrics)
{
ioMetrics.ascent = std::max( ioMetrics.ascent, (float)height);
ioMetrics.descent = std::max( ioMetrics.descent, (float)height);
ioMetrics.height = std::max( ioMetrics.height, (float)height);
}
int Height() { return height; }
};



Expand Down Expand Up @@ -502,7 +535,7 @@ Font *Font::Create(TextFormat &inFormat,double inScale,bool inNative,AntiAliasTy
// printf("No resource\n");
}

#ifdef HXCPP_JS_PRIME
#ifdef LINKED_FONT_DATA
if (!bytes)
{
if (norm=="_sans")
Expand Down Expand Up @@ -540,13 +573,16 @@ Font *Font::Create(TextFormat &inFormat,double inScale,bool inNative,AntiAliasTy
if (!native && !face)
face = FontFace::CreateNative(inFormat,inScale, aaType);
#endif

if (!face)
{
//printf("Missing face : %s\n", fontName.c_str() );
TextFormat defaultFormat = inFormat;
defaultFormat.font = UTF8ToWide("_sans");
return Create(defaultFormat, inScale, inNative, aaType, inInitRef);
return 0;
if (fontName!="_sans")
{
TextFormat defaultFormat = inFormat;
defaultFormat.font = UTF8ToWide("_sans");
return Create(defaultFormat, inScale, inNative, aaType, inInitRef);
}
face = new EmptyFontFace(info.height);
}

font = new Font(face,info.height,inInitRef);
Expand Down
1 change: 1 addition & 0 deletions project/src/sdl/SDLStage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
#ifdef EMSCRIPTEN
#include <emscripten.h>
#include <emscripten/html5.h>
#include <emscripten/bind.h>
#endif

#ifdef NME_MIXER
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -644,7 +644,7 @@ class PiratePigGame extends Sprite {

private function TileContainer_onMouseDown (event:MouseEvent):Void {

if (Std.is (event.target, Tile)) {
if (Std.isOfType(event.target, Tile)) {

selectedTile = cast event.target;
cacheMouse = new Point (event.stageX, event.stageY);
Expand Down
8 changes: 8 additions & 0 deletions templates/jsprime/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
progress: function() {
var loaded = this.downloadedNmeJs + this.downloadedNmeApp + this.downloadedNmeClasses;
if (this.binaryIsReady) loaded++;
console.log("progress: " + this.binaryIsReady + "/" + loaded);


var preloadUpdate = window.preloadUpdate;
Expand Down Expand Up @@ -196,6 +197,7 @@

<script>
::if (NME_MEM_FILE)::
// NME_JS_MEM
(function() {
var memoryInitializer = '::NME_JS::.mem';
if (typeof Module['locateFile'] === 'function') {
Expand All @@ -211,8 +213,10 @@
::end::

(function() {
// NME_JS
Module.totalDownloads++;
var xhr = new XMLHttpRequest;
console.log("::NME_JS::...");
xhr.open("GET", "::NME_JS::", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
Expand All @@ -234,8 +238,10 @@


(function() {
// NME_APP_JS
Module.totalDownloads++;
var xhr = new XMLHttpRequest;
console.log("::NME_APP_JS::...");
xhr.open("GET", "::NME_APP_JS::", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
Expand All @@ -256,6 +262,7 @@
xhr.send();
}) ();

::if (NME_CLASSES_JS)::
(function() {
Module.totalDownloads++;
window.nmeOnClasses = function() { Module.progress() };
Expand All @@ -278,6 +285,7 @@
};
xhr.send();
}) ();
::end::

</script>

Expand Down
2 changes: 2 additions & 0 deletions tools/make_classes/Export.hx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ class Export
var global:Dynamic = untyped js.Syntax.code("$global");
global.nmeClassesLoaded = true;
// String map hack
#if (js_es < 5)
global.__map_reserved = untyped __map_reserved;
#end

if (typeOf(global.nmeOnClasses) == 'function')
global.nmeOnClasses();
Expand Down
86 changes: 51 additions & 35 deletions tools/nme/src/platforms/EmscriptenPlatform.hx
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,36 @@ class EmscriptenPlatform extends DesktopPlatform
private var sdkPath:String;
private var python:String;
private var memFile:Bool;
var htmlOut = false;

override public function getOutputExtra() : String { return ext==".js" ? "jsprime" : ""; }
override public function getOutputExtra() : String { return "jsprime"; }

public function new(inProject:NMEProject)
{
super(inProject);

setupSdk();

ext = project.hasDef("EMSCRIPTEN_HTML") ? ".html" : ".js";
htmlOut = true; //project.hasDef("EMSCRIPTEN_HTML");
ext = htmlOut ? ".html" : ".js";
applicationDirectory = getOutputDir();
executableFile = "ApplicationMain" + ext;


executableFile = "ApplicationMain.js";
executablePath = applicationDirectory + "/" + executableFile;
outputFiles.push(executableFile);

var wasmFile = "ApplicationMain.js";
executablePath = applicationDirectory + "/" + executableFile;
outputFiles.push(executableFile);

project.haxeflags.push('-D exe_link');
project.haxeflags.push('-D HXCPP_LINK_EMSCRIPTEN_EXT=$ext');
project.haxeflags.push('-D HXCPP_LINK_EMRUN');

memFile = project.getBool("emscriptenMemFile", true);

project.haxeflags.push('-D HXCPP_LINK_MEM_FILE=' + (memFile?"1":"0") );
memFile = project.getBool("emscriptenMemFile", false);
if (memFile)
project.haxeflags.push('-D HXCPP_LINK_MEM_FILE=1');
}

override public function getPlatformDir() : String { return "emscripten"; }
Expand All @@ -45,44 +54,26 @@ class EmscriptenPlatform extends DesktopPlatform

override public function copyBinary():Void
{
var dbg = project.debug ? "-debug" : "";

// Must keep the same name
if (project.debug)
var src = haxeDir + '/cpp/ApplicationMain$dbg';
if (htmlOut && false)
{
var src = haxeDir + "/cpp/ApplicationMain-debug";

if (ext==".html") // no 'debug'
FileHelper.copyFile(src + ext, applicationDirectory+"/ApplicationMain.html");
else
FileHelper.copyFile(src + ext, applicationDirectory+"/ApplicationMain-debug"+ext);

// Needed of O2?
if (memFile)
FileHelper.copyFile(src + ext+".mem", applicationDirectory+"/ApplicationMain-debug"+ext + ".mem" );

if (ext==".html")
FileHelper.copyFile(src + ".js", applicationDirectory+"/ApplicationMain-debug.js");

FileHelper.copyFile(src + ".html", applicationDirectory+"/index.html");
}
else
{
var src = haxeDir + "/cpp/ApplicationMain";

FileHelper.copyFile(src + ext, executablePath);
// Needed of O2?
if (memFile)
FileHelper.copyFile(src + ext+".mem", executablePath+".mem");

if (ext==".html")
FileHelper.copyFile(src + ".js", applicationDirectory+"/ApplicationMain.js");
}
FileHelper.copyFile(src + ".js", applicationDirectory+'/ApplicationMain$dbg.js');
FileHelper.copyFile(src + ".wasm", applicationDirectory+'/ApplicationMain$dbg.wasm');
}

override function generateContext(context:Dynamic)
{
super.generateContext(context);
context.NME_LIB_JS = project.debug ? "ApplicationMain-debug.js" : "ApplicationMain.js";
var dbg = project.debug ? "-debug" : "";
context.NME_JS = 'ApplicationMain$dbg.js';
context.NME_MEM_FILE = memFile;
context.NME_APP_JS = null;
context.NME_APP_JS = 'ApplicationMain$dbg.wasm';
}


Expand All @@ -108,9 +99,34 @@ class EmscriptenPlatform extends DesktopPlatform
}

override public function run(arguments:Array<String>):Void
{
if (true)
{
runPython(arguments);
}
else
{
var server = new nme.net.http.Server( new nme.net.http.FileServer([FileSystem.fullPath(applicationDirectory) ]).onRequest );

var port = 2323;
server.listen(port);
new nme.net.URLRequest('http://localhost:$port/index.html' ).launchBrowser();

server.untilDeath();
}



//var fullPath = FileSystem.fullPath('$applicationDirectory/index.html');
//new nme.net.URLRequest("file://" + fullPath).launchBrowser();
}


public function runPython(arguments:Array<String>):Void
{
var command = sdkPath==null ? "emrun" : sdkPath + "/emrun";
var source = ext == ".html" ? Path.withoutDirectory(executablePath) : "index.html";
var source = "index.html";
//var source = ext == ".html" ? Path.withoutDirectory(executablePath) : "index.html";
var browser = CommandLineTools.browser;
var browserOps = browser=="none" ? ["--no_browser"] : browser==null ? [] : ["--browser",browser];
if (python!=null)
Expand Down

0 comments on commit 48b8b9f

Please sign in to comment.