Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Emscripten -Transpiling C
/ C++ to JS / HTML5
DaveVoyles
Sr.Tech Evangelist, Philadelphia
DaveVoyles.com
JavaScript is standards-based and the only
language that runs in all web browsers
You can run only JavaScript in browsers,...
Everything compiles to LLVM bitcode
Which we can then turn into JavaScript
Native code has its perks (performance!)
But so does rapid testing/sharing.
Transpile to JS and just share a URL
This is nothing new (well, sort of…)
C#, Python, Java,Typescript
All transpile to JavaScript
• Pyjs – Python
• JSIL – C#
•...
Why now?
non-standardized approaches (ActiveX, Silverlight,
Flash/Alchemy, PNaCl/PPAPI) have had limited success in the
pa...
Why now?
Plugins outside of HTML5 standards have not received
widespread adoption for both technical and non-technical
rea...
Besides, they are on their way out
No plugins for iOS devices, Google nixes NPAPI, etc.
This is great for the web! Standards!
JavaScript is a standard, so why not compile to that?
Example: gaming on the web
Experience w/ typical games:
• Go to platform-specific store, log in, find game, purchase,
down...
JS then vs JS now
Then: JS began as a slow interpreted language
JS then vs JS now
Implicit, statically typed code in JS, just like the competition
JS then vs JS now
Now: Asm.js – highly optimized, performant subset of JS
asm.js overview
Emscripten overview
•Open source (MIT/LLVM)
•Began in 2010
Emscripten is built on LLVM
• clang C++ frontend
• LLVM optimizer
• libc++ C++ standard library
• libc++abi low-level C++ ...
Clang supports nearly all C++ features, so
Emscripten does as well
Exception handling takes some work,
though
Runtime functions
What about other libraries?
SDL & OpenGL are implemented viaWeb APIs,
same with musl (Linux)
• Bullet
• Box2D
• Python
• L...
Not without its limitations
•64-bit integer math will not work
•No multithreading with shared state
•No Direct3D support, ...
Debugging
This is a problem in general with compiling for
the web. Source maps can help, but browsers do
have more work to...
How does it work?
Numerictypes
JS
• double
LLVM
•i8, i16, i32, float,
double
Performance
LLVM
• types & operations map
~1:1 to CPU
• RAII offers Predictability
JS
• virtual machine (VM)
• just in tim...
Builds
C++
•Need to recompile for
each CPU / OS
JS
•One build to rule them all
Variables
LLVM
•Local vars have function
scope
JS
•Local vars have function
scope
Security concerns
JS
•Sandboxed
• Cannot see the machine it
is running on
C++
•Apps can use system libs
•Access local file...
Security concerns (cont’d)
The JS stack is managed and unobservable/unmodifiable by
executing code.
Compiled C++ is immune...
More speed
Loads in LLVM IR become reads from typed array
(binary data in the browser) in JS, which become reads in
machin...
Why do this?
• Download just parts of the app, stream the rest
• Ex: Star Citizen: 100GB+Vs.Age ofAscent: 50Mb
• Circumven...
Browser support
native executable
Compiling with Emscripten
Generating code
The target file name extension defines the output type to
be generated:
<name> .js : JavaScript.
<name> .h...
Porting process
emcc is a drop-in replacement for gcc or clang
In many cases, you can use your normal build
system, plug i...
Porting process
emcc is a drop-in replacement for gcc or clang
In many cases, you can use your normal build
system, plug i...
Connecting C / C++ and JS
Call compiled C++ classes from JavaScript using bindings created with:
• Embind orWebIDL-Binder
...
Why not just turn your JavaScript
code into asm.js?
Run-time type checking takes time.
Why not just turn your JavaScript
code into asm.js?
In statically typed languages, such as C, the
compiler knows the type ...
Offline experience
• IndexedDB
• Local database of records, holding simple values and
hierarchical objects
• AppCache
• Of...
Performance
UnityWebGL benchmark
(Higher is better)
Unity WebGL Benchmarks
Unity WebGL Benchmarks
• In benchmarks which stressWebGL rendering performance (Particles,
Asteroid Field), Edge performs ...
Case study: Owlchemy Labs
• 200+ levels
• 300 assets can be spawned a runtime
• 38 full length songs
• 1 million lines of ...
Exporting with Unity
What goes in must come out
When you build a WebGL project, Unity will create a folder with
the following files:
• index.ht...
Some missing features
• Networking other thanWWW class (a WebSockets plug-in is
available)
• Support for WebCam and Microp...
Conclusion
The advantages of porting C/C++ to JavaScript are
clear:
• Often a smaller package size
• Easily demo or share ...
References
Thank you to Alon Zakai (@Kripken)and his
wonderful work on the project!
• http://twvideo01.ubm-
us.net/o1/vaul...
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Upcoming SlideShare
Loading in …5
×

Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5

5,994 views

Published on

The video for this talk can be found here:https://channel9.msdn.com/Blogs/raw-tech/Getting-started-with-Emscripten--Transpiling-C--C-to-JavaScript--HTML5

I cover how to transpile code from C/C++ to HTML5/JS using Emscripten, an open source compiler tool from Mozilla and Alon Zakai.

Published in: Technology

Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5

  1. 1. Emscripten -Transpiling C / C++ to JS / HTML5 DaveVoyles Sr.Tech Evangelist, Philadelphia DaveVoyles.com
  2. 2. JavaScript is standards-based and the only language that runs in all web browsers You can run only JavaScript in browsers, but you can write in another language - if you compile it to JavaScript
  3. 3. Everything compiles to LLVM bitcode Which we can then turn into JavaScript
  4. 4. Native code has its perks (performance!) But so does rapid testing/sharing. Transpile to JS and just share a URL
  5. 5. This is nothing new (well, sort of…) C#, Python, Java,Typescript All transpile to JavaScript • Pyjs – Python • JSIL – C# • Java – GoogleWebToolkit
  6. 6. Why now? non-standardized approaches (ActiveX, Silverlight, Flash/Alchemy, PNaCl/PPAPI) have had limited success in the past
  7. 7. Why now? Plugins outside of HTML5 standards have not received widespread adoption for both technical and non-technical reasons
  8. 8. Besides, they are on their way out No plugins for iOS devices, Google nixes NPAPI, etc.
  9. 9. This is great for the web! Standards! JavaScript is a standard, so why not compile to that?
  10. 10. Example: gaming on the web Experience w/ typical games: • Go to platform-specific store, log in, find game, purchase, download, install, patch, play Experience w/ web games: • www.DaveVoyles.com (Launches the game!)
  11. 11. JS then vs JS now Then: JS began as a slow interpreted language
  12. 12. JS then vs JS now Implicit, statically typed code in JS, just like the competition
  13. 13. JS then vs JS now Now: Asm.js – highly optimized, performant subset of JS
  14. 14. asm.js overview
  15. 15. Emscripten overview •Open source (MIT/LLVM) •Began in 2010
  16. 16. Emscripten is built on LLVM • clang C++ frontend • LLVM optimizer • libc++ C++ standard library • libc++abi low-level C++ support
  17. 17. Clang supports nearly all C++ features, so Emscripten does as well Exception handling takes some work, though
  18. 18. Runtime functions
  19. 19. What about other libraries? SDL & OpenGL are implemented viaWeb APIs, same with musl (Linux) • Bullet • Box2D • Python • Lua • Ruby • zlib
  20. 20. Not without its limitations •64-bit integer math will not work •No multithreading with shared state •No Direct3D support, only OpenGL
  21. 21. Debugging This is a problem in general with compiling for the web. Source maps can help, but browsers do have more work to do to make debugging compiled code a smoother experience. Start with your compiled code.
  22. 22. How does it work?
  23. 23. Numerictypes JS • double LLVM •i8, i16, i32, float, double
  24. 24. Performance LLVM • types & operations map ~1:1 to CPU • RAII offers Predictability JS • virtual machine (VM) • just in time (JIT) compilers w/ type profiling • garbage collection • Etc.
  25. 25. Builds C++ •Need to recompile for each CPU / OS JS •One build to rule them all
  26. 26. Variables LLVM •Local vars have function scope JS •Local vars have function scope
  27. 27. Security concerns JS •Sandboxed • Cannot see the machine it is running on C++ •Apps can use system libs •Access local filesystem
  28. 28. Security concerns (cont’d) The JS stack is managed and unobservable/unmodifiable by executing code. Compiled C++ is immune to some types of buffer overflow attacks Can be beneficial, though….
  29. 29. More speed Loads in LLVM IR become reads from typed array (binary data in the browser) in JS, which become reads in machine code.
  30. 30. Why do this? • Download just parts of the app, stream the rest • Ex: Star Citizen: 100GB+Vs.Age ofAscent: 50Mb • Circumvent app stores • Want to push updates? Just update your web app • No more 1 week waiting period, iOS • Distribution through sources other than curated app stores • Release apps on your website
  31. 31. Browser support
  32. 32. native executable
  33. 33. Compiling with Emscripten
  34. 34. Generating code The target file name extension defines the output type to be generated: <name> .js : JavaScript. <name> .html : HTML + separate JavaScript file (<name>.js). (Having the separate JavaScript file improves page load time.) <name> .bc : LLVM bitcode (default).
  35. 35. Porting process emcc is a drop-in replacement for gcc or clang In many cases, you can use your normal build system, plug in emcc
  36. 36. Porting process emcc is a drop-in replacement for gcc or clang In many cases, you can use your normal build system, plug in emcc
  37. 37. Connecting C / C++ and JS Call compiled C++ classes from JavaScript using bindings created with: • Embind orWebIDL-Binder Call compiled C functions from normal JavaScript: • Using ccall or cwrap. • Using direct function calls (faster but more complicated). Call JavaScript functions from C/C++: • Using emscripten_run_script(). • Using EM_ASM() (faster). • Using a C API implemented in JavaScript. • As function pointers from C. • Using the Embind val class.
  38. 38. Why not just turn your JavaScript code into asm.js? Run-time type checking takes time.
  39. 39. Why not just turn your JavaScript code into asm.js? In statically typed languages, such as C, the compiler knows the type of each object when it is being compiled.
  40. 40. Offline experience • IndexedDB • Local database of records, holding simple values and hierarchical objects • AppCache • Offline browsing, stores content on the disk instead of network • Service Workers • Coming soon
  41. 41. Performance
  42. 42. UnityWebGL benchmark
  43. 43. (Higher is better) Unity WebGL Benchmarks
  44. 44. Unity WebGL Benchmarks • In benchmarks which stressWebGL rendering performance (Particles, Asteroid Field), Edge performs best of all tested browsers. • When you are mostly GPU-bound, you can expect WebGL to perform very similar to native code. • In some areas,WebGL will actually outperform native code significantly. (Mandlebrot & Cryptohash) • Native code can still be several times faster thanWebGL for areas heavily optimized to use multi-threading and/or SIMD, such as the 3D physics tests.
  45. 45. Case study: Owlchemy Labs • 200+ levels • 300 assets can be spawned a runtime • 38 full length songs • 1 million lines of JavaScript • WebGL build (With Unity engine!) = 68.8Mb • PC build = 192 Mb
  46. 46. Exporting with Unity
  47. 47. What goes in must come out When you build a WebGL project, Unity will create a folder with the following files: • index.html file that embeds your content in a web page. • JavaScript file containing the code for your player. • .mem file containing a binary image to initialize the heap memory for your player. • .data file containing the asset data and scenes. • some supporting JavaScript files to initialize and load the player.
  48. 48. Some missing features • Networking other thanWWW class (a WebSockets plug-in is available) • Support for WebCam and Microphone access • Threads • Any .NET features requiring dynamic code generation • Runtime generation of Substance textures
  49. 49. Conclusion The advantages of porting C/C++ to JavaScript are clear: • Often a smaller package size • Easily demo or share projects on the web • Reuse existing code
  50. 50. References Thank you to Alon Zakai (@Kripken)and his wonderful work on the project! • http://twvideo01.ubm- us.net/o1/vault/gdconline12/Presentations/Emscripten%20(pt%201).pdf • https://www.reddit.com/r/programming/comments/2k3b4j/alon_zakai_emscripten_and_as mjs_cs_role_in_the/http://llvm.org/devmtg/2013-11/slides/Zakai-Emscripten.pdf • http://llvm.org/devmtg/2013-11/slides/Zakai-Emscripten.pdf

×