### Install Build Prerequisites for rawdrawwasm (APT) Source: https://github.com/cntools/rawdraw/blob/master/wasm/README.md This snippet provides `apt-get` commands to install essential development tools like `npm`, `binaryen`, `clang`, `llvm`, and `lld`, which are required for compiling and building the `rawdrawwasm` project. It also includes a global installation of `terser` via `npm`. ```bash sudo apt-get install npm binaryen clang llvm lld sudo npm install terser -g ``` -------------------------------- ### Install rawdraw prerequisites on Arch Linux Source: https://github.com/cntools/rawdraw/blob/master/README.md Commands to synchronize package databases and install necessary development libraries for rawdraw on Arch Linux, including Xorg, X11, Mesa, and GLU. ```Shell sudo pacman -Sy xorg-server-devel libx11 libxinerama libxext mesa glu ``` -------------------------------- ### Install rawdraw prerequisites on Debian/Ubuntu Source: https://github.com/cntools/rawdraw/blob/master/README.md Commands to update package lists and install necessary development libraries for rawdraw on Debian or Ubuntu systems, including Xorg, X11, Mesa, and GLU. ```Shell sudo apt-get update sudo apt-get install xorg-dev libx11-dev libxinerama-dev libxext-dev mesa-common-dev libglu1-mesa-dev ``` -------------------------------- ### JavaScript Commented System Initialization Function Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html This commented-out JavaScript function, `SystemStart`, appears to be an initial setup routine for the drawing system. If active, it would have set the document title and initialized the WebGL canvas dimensions (`wgl.viewportWidth`, `canvas.width`, `wgl.viewportHeight`, `canvas.height`) based on provided width and height parameters. ```JavaScript /* function SystemStart( title, w, h ) { document.title = toUTF8( title ); wgl.viewportWidth = canvas.width = w; wgl.viewportHeight = canvas.height = h; } */ ``` -------------------------------- ### Basic Rawdraw Application Example in C Source: https://github.com/cntools/rawdraw/blob/master/README.md This C code demonstrates a minimal Rawdraw application. It initializes a window, handles input, clears the frame, sets colors, and draws various shapes such as text, pixels, segments, rectangles, triangles, and blitted images using Rawdraw's API. It also shows the basic event loop structure. ```C //Make it so we don't need to include any other C files in our build. #define CNFG_IMPLEMENTATION #include "rawdraw_sf.h" void HandleKey( int keycode, int bDown ) { } void HandleButton( int x, int y, int button, int bDown ) { } void HandleMotion( int x, int y, int mask ) { } int HandleDestroy() { return 0; } int main() { CNFGSetup( "Example App", 1024, 768 ); while(CNFGHandleInput()) { CNFGBGColor = 0x000080ff; //Dark Blue Background short w, h; CNFGClearFrame(); CNFGGetDimensions( &w, &h ); //Change color to white. CNFGColor( 0xffffffff ); CNFGPenX = 1; CNFGPenY = 1; CNFGDrawText( "Hello, World", 2 ); //Draw a white pixel at 30, 30 CNFGTackPixel( 30, 30 ); //Draw a line from 50,50 to 100,50 CNFGTackSegment( 50, 50, 100, 50 ); //Dark Red Color Select CNFGColor( 0x800000FF ); //Draw 50x50 box starting at 100,50 CNFGTackRectangle( 100, 50, 150, 100 ); //Bright Purple Select CNFGColor( 0x800000FF ); //Draw a triangle RDPoint points[3] = { { 30, 36}, {20, 50}, { 40, 50 } }; CNFGTackPoly( points, 3 ); //Draw a bunch of random pixels as a blitted image. { static uint32_t data[64*64]; int x, y; for( y = 0; y < 64; y++ ) for( x = 0; x < 64; x++ ) data[x+y*64] = 0xff | (rand()<<8); CNFGBlitImage( data, 150, 30, 64, 64 ); } //Display the image and wait for time to display next frame. CNFGSwapBuffers(); } } ``` -------------------------------- ### JavaScript Canvas Resizing and Animation Loop Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html This code defines the main rendering and update loop for the application. The `FrameStart` function adjusts the canvas dimensions and WebGL viewport based on fullscreen status or requested size, ensuring correct rendering coordinates. The `AnimationFrame` function is the primary animation loop, continuously calling `TickWebsocket` (for processing incoming data) and `FrameStart` (for frame setup) using `requestAnimationFrame` to maintain smooth updates. ```JavaScript function FrameStart() { //console.log( globalwebsocket_connected + " " + frame_transfer_done ); if( !globalwebsocket_connected ) return; if( fullscreenoverride === null ) { // Don't affect fullscreen } else { fullscreen = fullscreenoverride; } //Fixup canvas sizes if( fullscreen ) { wgl.viewportWidth = canvas.width = window.innerWidth; wgl.viewportHeight = canvas.height = window.innerHeight; canvas.style = "position:absolute; top:0; left:0;" } else { wgl.viewportWidth = canvas.width = request_w; wgl.viewportHeight = canvas.height = request_h; } if( frame_transfer_done ) { //Make sure viewport and input to shader is correct. //We do this so we can pass literal coordinates into the shader. wgl.viewport( 0, 0, wgl.viewportWidth, wgl.viewportHeight ); //Update geometry transform (Scale/shift) wgl.uniform4f( wglUXFRM, 1./wgl.viewportWidth, -1./wgl.viewportHeight, -0.5, 0.5); SendSwap(); } } function AnimationFrame() { TickWebsocket(); FrameStart(); requestAnimationFrame( AnimationFrame ); } requestAnimationFrame( AnimationFrame ); ``` -------------------------------- ### Blit Image Data to WebGL Canvas Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Renders a raw image data buffer (uint8memdata) onto the WebGL canvas at a specified position and size. It handles texture creation, parameter setup, and uses the blitting shader to draw the image as a textured quad. ```javascript function CNFGBlitImageInternal(uint8memdata, x, y, w, h ) { if( w <= 0 || h <= 0 ) return; wgl.useProgram(wglBlit); // Most of the time we don't use textures, so don't initiate at start. if( wglTex == null ) wglTex = wgl.createTexture(); wgl.activeTexture(wgl.TEXTURE0); const t2d = wgl.TEXTURE_2D; wgl.bindTexture(t2d, wglTex); // Note that unlike the normal color operation, we don't have an extra offset. wgl.uniform4f( wglUXFRMBlit, 1./wgl.viewportWidth, -1./wgl.viewportHeight, -.5+x/wgl.viewportWidth, .5-y/wgl.viewportHeight ); // These parameters are required. Not sure why the defaults don't work. wgl.texParameteri(t2d, wgl.TEXTURE_WRAP_T, wgl.CLAMP_TO_EDGE); wgl.texParameteri(t2d, wgl.TEXTURE_WRAP_S, wgl.CLAMP_TO_EDGE); wgl.texParameteri(t2d, wgl.TEXTURE_MIN_FILTER, wgl.NEAREST); wgl.texImage2D(t2d, 0, wgl.RGBA, w, h, 0, wgl.RGBA, wgl.UNSIGNED_BYTE, uint8memdata ); CNFGEmitBackendTrianglesJS( new Float32Array( [0,0,0, w,0,0, w,h,0, 0,0,0, w,h,0, 0,h,0 ] ), new Uint8Array( [0,0,0,0, 255,0,0,0, 255,255,0,0, 0,0,0,0, 255,255,0,0, 0,255,0,0] ), 6 ); wgl.useProgram(wglShader); } ``` -------------------------------- ### Set Line Width for Drawing Operations Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Sets the global line width used for subsequent drawing operations, specifically for functions like `CNFGTackPixel` and `CNFGTackSegment`. The input `width` is divided by 2 to get `wgl_last_width_over_2`. ```javascript function CNFGSetLineWidth( width ) { wgl_last_width_over_2 = width/2.0;// + 0.5; } ``` -------------------------------- ### Get Current Absolute Time in Seconds Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Returns the current time in seconds since the Unix epoch. This function is used for timing operations, such as managing WebSocket connection timeouts. ```javascript function OGGetAbsoluteTime() { return new Date().getTime()/1000.; } ``` -------------------------------- ### Run rawdraw sample program Source: https://github.com/cntools/rawdraw/blob/master/README.md Command to execute the compiled 'simple' sample program, demonstrating basic rawdraw functionality. ```Shell ./simple ``` -------------------------------- ### JavaScript WebAssembly Module Loading Logic Source: https://github.com/cntools/rawdraw/blob/master/wasm/README.md This JavaScript code demonstrates a strategy for loading WebAssembly modules. It attempts a synchronous instantiation for small modules (under 4KB) using `WebAssembly.Module` and `WebAssembly.Instance` to avoid a flash, and falls back to the asynchronous `WebAssembly.instantiate` method for larger modules, calling a `wasmloaded` callback upon completion. ```javascript function wasmloaded(wa) { instance = wa; wasmExports = instance.exports; instance.exports.main(); } //If at all possible, we should attempt to load in-thread //This will make the load not flash. if( blob.length < 4096 ) { let mod = new WebAssembly.Module(array); var wa = new WebAssembly.Instance( mod, imports ); wasmloaded( wa ); } else { WebAssembly.instantiate(array, imports).then( function(wa) { wasmloaded(wa.instance); } ); } ``` -------------------------------- ### Compile rawdraw sample program Source: https://github.com/cntools/rawdraw/blob/master/README.md Command to compile the 'simple.c' sample program using `make`, which creates an executable named 'simple' in the current directory. ```Shell make ``` -------------------------------- ### Download rawdraw_sf.h for single-file inclusion Source: https://github.com/cntools/rawdraw/blob/master/README.md Command to download the single-file header `rawdraw_sf.h` directly from GitHub, allowing for easy inclusion into a project without managing multiple source files. ```Shell wget https://raw.githubusercontent.com/cntools/rawdraw/master/rawdraw_sf.h ``` -------------------------------- ### Initialize Git repository for submodule Source: https://github.com/cntools/rawdraw/blob/master/README.md Command to initialize a new Git repository in the current directory, which may be necessary before adding a submodule if the directory is not already a Git repository. ```Shell git init ``` -------------------------------- ### Initialize WebGL Solid Color Shader and Buffers Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Sets up the primary WebGL shader program for rendering solid-colored geometry. It defines vertex and fragment shaders, compiles them, and initializes vertex and color array buffers for drawing. ```javascript let wglShader = null; //Standard flat color shader let wglABV = null; //Array buffer for vertices let wglABC = null; //Array buffer for colors. let wglUXFRM = null; //Uniform location for transform on solid colors // We load two shaders, one is a solid-color shader, for most rawdraw objects. wglShader = wgl_makeShader( "uniform vec4 xfrm; attribute vec3 a0; attribute vec4 a1; varying vec4 vc; void main() { gl_Position = vec4( a0.xy*xfrm.xy+xfrm.zw, a0.z, 0.5 ); vc = a1; }", "precision mediump float; varying vec4 vc; void main() { gl_FragColor = vec4(vc.xyzw); }" ); wglUXFRM = wgl.getUniformLocation(wglShader, "xfrm" ); // Compile the shaders. wgl.useProgram(wglShader); // Get some vertex/color buffers, to put geometry in. wglABV = wgl.createBuffer(); wglABC = wgl.createBuffer(); // We're using two buffers, so just enable them, now. wgl.enableVertexAttribArray(0); wgl.enableVertexAttribArray(1); // Enable alpha blending wgl.enable(wgl.BLEND); wgl.blendFunc(wgl.SRC_ALPHA, wgl.ONE_MINUS_SRC_ALPHA); ``` ```glsl Vertex Shader (Solid Color): uniform vec4 xfrm; attribute vec3 a0; attribute vec4 a1; varying vec4 vc; void main() { gl_Position = vec4( a0.xy*xfrm.xy+xfrm.zw, a0.z, 0.5 ); vc = a1; } Fragment Shader (Solid Color): precision mediump float; varying vec4 vc; void main() { gl_FragColor = vec4(vc.xyzw); } ``` -------------------------------- ### Compile Rawdraw Application on Linux with GCC Source: https://github.com/cntools/rawdraw/blob/master/README.md Command to compile a Rawdraw application (`simple.c`) on Linux using the GCC compiler. It links against math, X11, and OpenGL libraries. ```Shell gcc -o simple simple.c -lm -lX11 -lGL ``` -------------------------------- ### os_generic.h Library Configuration Options Source: https://github.com/cntools/rawdraw/blob/master/README.md This section describes configuration options for `os_generic.h`, a platform-independent library for threading, TLS, mutexes, semaphores, and time management. Options include preventing implementation inclusion, overriding function prefixes, and disabling static function declarations. ```APIDOC os_generic.h Configuration options: * OSG_NO_IMPLEMENTATION: Do not include implementation as static functions. * OSG_PREFIX: Override function prefix. * OSG_NOSTATIC: Do not declare the functions as static. ``` -------------------------------- ### Compile Rawdraw Application on Windows with Clang Source: https://github.com/cntools/rawdraw/blob/master/README.md Command to compile a Rawdraw application (`simple.c`) on Windows using the Clang compiler. It links against OpenGL, GDI, and User32 libraries. ```Shell clang simple.c -o simple -Irawdraw -lopengl32 -lgdi32 -luser32 ``` -------------------------------- ### Enable rawdraw library implementation Source: https://github.com/cntools/rawdraw/blob/master/README.md C preprocessor directive required to include the full implementation of the rawdraw library when using it as a single-file header or by including 'CNFG.c' in your project. ```C #define CNFG_IMPLEMENTATION ``` -------------------------------- ### Rawdraw Library Configuration Options Source: https://github.com/cntools/rawdraw/blob/master/README.md This section lists various preprocessor macros that can be defined to configure the Rawdraw library's behavior, including enabling implementation code, targeting specific platforms (Android, Windows), selecting rendering backends (OpenGL, Rasterizer), and integrating 3D functionality. It also covers platform-specific X11 options. ```APIDOC CNFG Configuration options: * CNFG_IMPLEMENTATION: Include code for implementation. * __android__: Build Android port. * WINDOWS, WIN32, WIN64: Windows build. * CNFGOGL: Make underlying functions use OpenGL if possible. * CNFGRASTERIZER: Make the underlying graphics engine rasterized functions (software rendering). * CNFG3D: Include CNFG3D with this rawdraw build. Provides *rasterized* graphics functions. Only use with rasterizer. Platform-Specific: * HAS_XSHAPE: Include extra functions for handling on-screen display functionality in X11. * HAS_XINERAMA: Use X11's Xinerama to handle full-screen more cleanly. Flags you will probably never want to use: * EGL_LEAN_AND_MEAN: Bare bones EGL Driver. ``` -------------------------------- ### Export LLVM Binaries to System PATH Source: https://github.com/cntools/rawdraw/blob/master/wasm/README.md This `bash` command adds the specified LLVM binaries directory (e.g., `/usr/lib/llvm-10/bin`) to the system's `PATH` environment variable. This is often necessary to ensure that the build system can locate the correct `clang` and `llvm` executables. ```bash export PATH=$PATH:/usr/lib/llvm-10/bin ``` -------------------------------- ### Compile Rawdraw Application on Windows with TCC Source: https://github.com/cntools/rawdraw/blob/master/README.md Command to compile a Rawdraw application (`simple.c`) on Windows using the Tiny C Compiler (TCC). It links against OpenGL, GDI, User32, and msvcrt.dll. ```Shell C:\tcc\tcc simple.c -Irawdraw -lopengl32 -lgdi32 -luser32 C:\windows\system32\msvcrt.dll ``` -------------------------------- ### Initialize WebGL Context Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Obtains the WebGL rendering context from an HTML canvas element. Includes a retry mechanism for specific browser/GPU combinations that might require it. ```javascript let canvas = document.getElementById('canvas'); let wgl = canvas.getContext('webgl'); if( !wgl ) { //Janky - on Firefox 83, with NVIDIA GPU, you need to ask twice. wgl = canvas.getContext('webgl'); } ``` -------------------------------- ### Add rawdraw as a Git submodule Source: https://github.com/cntools/rawdraw/blob/master/README.md Command to add the rawdraw repository as a Git submodule to your project, enabling version-controlled integration and easy updates. ```Shell git submodule add https://github.com/cntools/rawdraw ``` -------------------------------- ### Initialize WebGL Texture Blitting Shader Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Sets up a separate WebGL shader program specifically for blitting (drawing) textures or images onto the canvas. It defines the vertex and fragment shaders required for texture mapping. ```javascript let wglBlit = null; //Blitting shader for texture let wglTex = null; //Texture handle for blitting. let wglUXFRMBlit = null; //Uniform location for transform on blitter wglBlit = wgl_makeShader( "uniform vec4 xfrm; attribute vec3 a0; attribute vec4 a1; varying vec2 tc; void main() { gl_Position = vec4( a0.xy*xfrm.xy+xfrm.zw, a0.z, 0.5 ); tc = a1.xy; }", "precision mediump float; varying vec2 tc; uniform sampler2D tex; void main() { gl_FragColor = texture2D(tex,tc).wzyx;}" ); wglUXFRMBlit = wgl.getUniformLocation(wglBlit, "xfrm" ); ``` ```glsl Vertex Shader (Texture Blitting): uniform vec4 xfrm; attribute vec3 a0; attribute vec4 a1; varying vec2 tc; void main() { gl_Position = vec4( a0.xy*xfrm.xy+xfrm.zw, a0.z, 0.5 ); tc = a1.xy; } Fragment Shader (Texture Blitting): precision mediump float; varying vec2 tc; uniform sampler2D tex; void main() { gl_FragColor = texture2D(tex,tc).wzyx; } ``` -------------------------------- ### Utility to Create WebGL Shader Program Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html A helper function that compiles and links vertex and fragment shader source code into a WebGL program. It includes basic error checking for shader compilation status. ```javascript function wgl_makeShader( vertText, fragText ) { let vert = wgl.createShader(wgl.VERTEX_SHADER); wgl.shaderSource(vert, vertText ); wgl.compileShader(vert); if (!wgl.getShaderParameter(vert, wgl.COMPILE_STATUS)) { alert(wgl.getShaderInfoLog(vert)); } let frag = wgl.createShader(wgl.FRAGMENT_SHADER); wgl.shaderSource(frag, fragText ); wgl.compileShader(frag); if (!wgl.getShaderParameter(frag, wgl.COMPILE_STATUS)) { alert(wgl.getShaderInfoLog(frag)); } let ret = wgl.createProgram(); wgl.attachShader(ret, frag); wgl.attachShader(ret, vert); wgl.linkProgram(ret); wgl.bindAttribLocation( ret, 0, "a0" ); wgl.bindAttribLocation( ret, 1, "a1" ); return ret; } ``` -------------------------------- ### JavaScript User Input Event Handlers for Canvas Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html This JavaScript section sets up event listeners for various user interactions on the canvas and document. It captures mouse movements, clicks, touch gestures, and keyboard presses. Each event is then dispatched to a corresponding handler function (`HandleMotion`, `HandleButton`, `HandleKey`) with relevant event data, enabling interactive control of the drawing application. ```JavaScript canvas.addEventListener('mousemove', e => { HandleMotion( e.offsetX, e.offsetY, e.buttons ); } ); canvas.addEventListener('touchmove', e => { HandleMotion( e.touches[0].clientX, e.touches[0].clientY, 1 ); } ); canvas.addEventListener('mouseup', e => { HandleButton( e.offsetX, e.offsetY, e.button, 0 ); return false; } ); canvas.addEventListener('mousedown', e => { HandleButton( e.offsetX, e.offsetY, e.button, 1 ); return false; } ); document.addEventListener('keydown', e => { HandleKey( e.keyCode, 1 ); } ); document.addEventListener('keyup', e => { HandleKey( e.keyCode, 0 ); } ); ``` -------------------------------- ### JavaScript WebSocket Connection and Binary Protocol Message Handler Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html This JavaScript code manages the WebSocket connection lifecycle and processes incoming binary data. The `onopen` handler confirms connection and sends an initial 'swap' message. The core `onmessage` handler parses a custom binary protocol, using a switch statement to interpret 4-bit opcodes for various drawing commands (e.g., setting color, drawing pixels, segments, rectangles, polygons, blitting images, and configuring the frame). It handles buffer accumulation and error checking. The `onclose` handler logs connection termination. ```JavaScript globalwebsocket.onopen = function(event) { document.getElementById( "status" ).innerHTML = "Connected"; globalwebsocket_connected = true; SendSwap(); } globalwebsocket.onmessage = function (event) { let ab = event.data; globalwebsocket_time = OGGetAbsoluteTime(); if( ab.byteLength == 0 ) { //Process buffer. let i = 0|0; let lastdata = 0; while( i < accumulated_buffer_place ) { let data = accumulated_buffer[i++]; if( ( data >>> 24 ) & 0xf && ( ( data >>> 28) != 2 ) ) { console.log( "Fault at " + i + " Reading " + data + " last " + lastdata + " // " + accumulated_buffer[i-1] + " " + accumulated_buffer[i-2] + " " + accumulated_buffer[i - 3] + " " + accumulated_buffer[i-4] ); break; } lastdata = data; switch( data >>> 28 ) { case 6: case 0: // Continuation - we should never get here. break; case 1: // Color { let col = accumulated_buffer[i++]; cnfg_color = ( ( col >>> 24 ) & 0xff ) | ( ( ( col >>> 16 ) & 0xff ) << 8 ) | ( ( ( col >>> 8 ) & 0xff ) << 16 ) | ( ( ( col >>> 0 ) & 0xff ) << 24 ); break; } case 2: CNFGTackPixel( data & 0x3fff, ( data >>> 14 ) & 0x3fff ); break; case 3: { let nextfew = new Int16Array( accumulated_buffer.buffer.slice( i*4, i*4+8 ) ); i+=2; CNFGTackSegment( nextfew[0], nextfew[1], nextfew[2], nextfew[3] ); break; } case 4: { let nextfew = new Int16Array( accumulated_buffer.buffer.slice( i*4, i*4+8 ) ); i+=2; CNFGTackRectangle( nextfew[0], nextfew[1], nextfew[2], nextfew[3] ); break; } case 5: { let numpts = data & 0xfffff; let ab = new Int16Array( accumulated_buffer.buffer.slice( i*4, i*4+numpts*4 ) ); i += numpts; CNFGTackPoly( ab, numpts ); break; } case 7: { //break; //blit! CNFGFlushRender(); let xy = accumulated_buffer[i++]; let x = xy & 0xffff; let y = (xy >>> 16 ) & 0xffff; let w = data & 0x3fff; let h = (data>>>14) & 0x3fff; let ab = new Uint8Array( accumulated_buffer.buffer.slice( i*4, i*4+ w*h*4 ) ); i += w*h; CNFGBlitImageInternal( ab, x, y, w, h ) break; } case 8: { CNFGFlushRender(); let numblocks = data & 0xff; let fsreq = ( data >>> 8 ) & 0x1; let titlelen = (data >>> 16 ) & 0xff; cnfg_bgcolor = accumulated_buffer[i++]; let reqs = accumulated_buffer[i++]; request_w = reqs & 0xffff; request_h = ( reqs >> 16 ) & 0xffff; CNFGClearFrameInternal( cnfg_bgcolor ); let j = 0|0; let title = new Uint8Array( accumulated_buffer.buffer.slice( i*4, i*4+titlelen ) ); i += numblocks - 3; document.title = new TextDecoder().decode( title ); fullscreen = fsreq; break; } case 9: //Swap buffers (not realy used - we detect end of frame with a 0-length message.) CNFGFlushRender(); break; case 10: //set line width CNFGSetLineWidth( data & 0xfff ); break; } } frame_transfer_done = true; accumulated_buffer_place = 0; } else { accumulated_buffer.set( new Uint32Array( ab ), accumulated_buffer_place ); accumulated_buffer_place += ab.byteLength/4; } } globalwebsocket.onclose = function(event) { console.log( "Forced close." ); globalwebsocket_connected = false; } ``` -------------------------------- ### Send Swap Frame Command via WebSocket Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Sends a 'SWAP' command over the WebSocket connection to signal that a new frame is ready. It includes the current viewport dimensions. This function only executes if the WebSocket is connected. ```javascript function SendSwap() { if( !globalwebsocket_connected ) return; let w = wgl.viewportWidth; let h = wgl.viewportHeight; if( w === undefined ) { w = wgl.drawingBufferWidth; h = wgl.drawingBufferHeight; } frame_transfer_done = false; globalwebsocket.send( new Uint8Array( [ 83, 87, 65, 80, w, w>>8, h, h>>8 ] ) ); //"SWAP" } ``` -------------------------------- ### Manage WebSocket Connection and Status Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Periodically checks the WebSocket connection status. If disconnected or timed out, it attempts to re-establish a new WebSocket connection to the server and updates the UI status. It sets up the `onopen` event handler. ```javascript function TickWebsocket() { if( OGGetAbsoluteTime() - globalwebsocket_time > 3 ) { document.getElementById( "status" ).innerHTML = "Connecting"; // Need to connect. globalwebsocket_time = OGGetAbsoluteTime(); globalwebsocket_connected = false; globalwebsocket = new WebSocket( "ws://" + location.host + "/d/ws/cmdbuf" ); globalwebsocket.binaryType = 'arraybuffer'; globalwebsocket.onopen = function() { document.getElementById( "st ``` -------------------------------- ### Draw a Rectangle Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Draws a rectangle defined by two corner points (x1, y1) and (x2, y2). It uses `EmitQuad` to render the rectangle. ```javascript function CNFGTackRectangle( x1, y1, x2, y2 ) { let ix1 = x1; let iy1 = y1; let ix2 = x2; let iy2 = y2; EmitQuad( ix1,iy1,ix2,iy1,ix1,iy2,ix2,iy2 ); } ``` -------------------------------- ### Emit and Draw WebGL Triangles Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Buffers vertex positions and color data into WebGL buffers and then draws the specified number of triangles. This function is designed for dynamic drawing of geometry. ```javascript function CNFGEmitBackendTrianglesJS( vertsF, colorsI, vertcount ) { if( vertcount <= 0 ) return; const ab = wgl.ARRAY_BUFFER; wgl.bindBuffer(ab, wglABV); wgl.bufferData(ab, vertsF, wgl.DYNAMIC_DRAW); wgl.vertexAttribPointer(0, 3, wgl.FLOAT, false, 0, 0); wgl.bindBuffer(ab, wglABC); wgl.bufferData(ab, new Uint8Array( colorsI.buffer ), wgl.DYNAMIC_DRAW); wgl.vertexAttribPointer(1, 4, wgl.UNSIGNED_BYTE, true, 0, 0); wgl.drawArrays(wgl.TRIANGLES, 0, vertcount ); globalv = vertsF; } ``` -------------------------------- ### Send Keyboard Event via WebSocket Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Sends keyboard key press or release events (key code and down state) over the WebSocket connection. The data is encoded as a 'KEYB' command. ```javascript function HandleKey( key, down ) { if( globalwebsocket_connected ) globalwebsocket.send( new Uint8Array( [ 75, 69, 89, 66, 0, 0, key, down ] ) ); //"KEYB" } ``` -------------------------------- ### Send Mouse Motion Event via WebSocket Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Sends mouse motion coordinates (x, y) and button state over the WebSocket connection. The data is encoded as a 'MOTN' command followed by the coordinates and button information. ```javascript function HandleMotion( x, y, but ) { if( globalwebsocket_connected ) globalwebsocket.send( new Uint8Array( [ 77, 79, 84, 78, x, x>>8, y, y>>8, 0, 0, 0, but ] ) ); //"MOTN" } ``` -------------------------------- ### Emit Quad as Two Triangles Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Emits a quadrilateral by breaking it down into two triangles and adding their vertices and colors to the internal rendering buffers. This function handles buffer overflow by flushing if necessary. ```javascript function EmitQuad( cx0, cy0, cx1, cy1, cx2, cy2, cx3, cy3 ) { //Because quads are really useful, but it's best to keep them all triangles if possible. //This lets us draw arbitrary quads. if( CNFGVertPlace >= CNFG_BATCH-6 ) CNFGFlushRender(); CNFGVertDataV[CNFGVertPlace*3+0] = cx0; CNFGVertDataV[CNFGVertPlace*3+1] = cy0; CNFGVertDataV[CNFGVertPlace*3+3] = cx1; CNFGVertDataV[CNFGVertPlace*3+4] = cy1; CNFGVertDataV[CNFGVertPlace*3+6] = cx2; CNFGVertDataV[CNFGVertPlace*3+7] = cy2; CNFGVertDataV[CNFGVertPlace*3+9] = cx2; CNFGVertDataV[CNFGVertPlace*3+10] = cy2; CNFGVertDataV[CNFGVertPlace*3+12] = cx1; CNFGVertDataV[CNFGVertPlace*3+13] = cy1; CNFGVertDataV[CNFGVertPlace*3+15] = cx3; CNFGVertDataV[CNFGVertPlace*3+16] = cy3; CNFGVertDataC[CNFGVertPlace+0] = cnfg_color; CNFGVertDataC[CNFGVertPlace+1] = cnfg_color; CNFGVertDataC[CNFGVertPlace+2] = cnfg_color; CNFGVertDataC[CNFGVertPlace+3] = cnfg_color; CNFGVertDataC[CNFGVertPlace+4] = cnfg_color; CNFGVertDataC[CNFGVertPlace+5] = cnfg_color; CNFGVertPlace += 6; } ``` -------------------------------- ### Send Mouse Button Event via WebSocket Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Sends mouse button press or release events (x, y coordinates, button ID, and down state) over the WebSocket connection. The data is encoded as a 'BUTN' command. ```javascript function HandleButton( x, y, btn, down ) { if( globalwebsocket_connected ) globalwebsocket.send( new Uint8Array( [ 66, 85, 84, 78, x, x>>8, y, y>>8, 0, 0, down, btn ] ) ); //"BUTN" } ``` -------------------------------- ### Draw a Polygon Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Draws a polygon given an array of points and the number of vertices. It triangulates the polygon by creating triangles fanning out from the first vertex. This function handles buffer overflow by flushing if needed. ```javascript function CNFGTackPoly( points, verts ) { verts |= 0; let i = 0|0; let tris = verts-2; if( CNFGVertPlace >= CNFG_BATCH-tris*3 ) CNFGFlushRender(); for( i = 0; i < tris; i++ ) { CNFGVertDataV[CNFGVertPlace*3+0] = points[0]; CNFGVertDataV[CNFGVertPlace*3+1] = points[1]; CNFGVertDataV[CNFGVertPlace*3+3] = points[i*2+2]; CNFGVertDataV[CNFGVertPlace*3+4] = points[i*2+3]; CNFGVertDataV[CNFGVertPlace*3+6] = points[i*2+4]; CNFGVertDataV[CNFGVertPlace*3+7] = points[i*2+5]; CNFGVertDataC[CNFGVertPlace+0] = cnfg_color; CNFGVertDataC[CNFGVertPlace+1] = cnfg_color; CNFGVertDataC[CNFGVertPlace+2] = cnfg_color; CNFGVertPlace += 3; } } ``` -------------------------------- ### Toggle Fullscreen Override Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html A simple JavaScript function to toggle a boolean flag that can be used to control fullscreen behavior. ```javascript let rendering = false; let fullscreen = false; let fullscreenoverride = null; function ToggleFS() { fullscreenoverride = !fullscreenoverride; } ``` -------------------------------- ### Clear WebGL Color and Depth Buffers Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Clears the WebGL color and depth buffers, preparing the canvas for a new frame. This is a common operation at the beginning of each rendering loop. ```javascript r( wgl.COLOR_BUFFER_BIT | wgl.COLOR_DEPTH_BIT ); ``` -------------------------------- ### Retrieve Canvas Dimensions Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Retrieves the current width and height of the HTML canvas element and stores them in the provided memory locations (likely for WASM or C interop via HEAP16). ```javascript function CNFGGetDimensions(pw, ph) { HEAP16[pw>>1] = canvas.width; HEAP16[ph>>1] = canvas.height; } ``` -------------------------------- ### Draw a Single Pixel Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Draws a single pixel at the specified coordinates (x1, y1) by emitting a small quad. The pixel size is influenced by `wgl_last_width_over_2`. ```javascript function CNFGTackPixel( x1, y1 ) { x1++; y1++; let l2 = wgl_last_width_over_2; let l2u = wgl_last_width_over_2+0.5; EmitQuad( x1-l2u, y1-l2u, x1+l2, y1-l2u, x1-l2u, y1+l2, x1+l2, y1+l2 ); } ``` -------------------------------- ### Draw a Line Segment Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Draws a line segment between two points (x1, y1) and (x2, y2). It calculates orthogonal vectors to create a thick line segment using `EmitQuad`. Note: The comment indicates the logic might be incorrect. ```javascript function CNFGTackSegment( x1, y1, x2, y2 ) { // console.log( x1 + " " + y1 + " " + x2 + " " + y2 ); let ix1 = x1; let iy1 = y1; let ix2 = x2; let iy2 = y2; let dx = ix2-ix1; let dy = iy2-iy1; let imag = 1./Math.sqrt(dx*dx+dy*dy); dx *= imag; dy *= imag; let orthox = dy*wgl_last_width_over_2; let orthoy =-dx*wgl_last_width_over_2; ix2 += dx/2 + 0.5; iy2 += dy/2 + 0.5; ix1 -= dx/2 - 0.5; iy1 -= dy/2 - 0.5; //This logic is incorrect. XXX FIXME. EmitQuad( (ix1 - orthox), (iy1 - orthoy), (ix1 + orthox), (iy1 + orthoy), (ix2 - orthox), (iy2 - orthoy), ( ix2 + orthox), ( iy2 + orthoy) ); } ``` -------------------------------- ### Flush Accumulated Render Data Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Flushes the accumulated vertex and color data to the backend rendering system. This function is called when the internal buffer is full or when rendering needs to be finalized. ```javascript function CNFGFlushRender() { CNFGEmitBackendTrianglesJS( CNFGVertDataV, CNFGVertDataC, CNFGVertPlace ); CNFGVertPlace = 0; } ``` -------------------------------- ### Clear WebGL Frame with Color Source: https://github.com/cntools/rawdraw/blob/master/tools/rawdraw_http_files/index.html Clears the WebGL drawing buffer with a specified 32-bit integer color value. The color is converted from an RGBA integer to normalized float components for WebGL's `clearColor` function. ```javascript let frame_transfer_done = false; function CNFGClearFrameInternal( color ) { color |= 0; wgl.clearColor( ((color>>24)&0xff)/255., ((color>>16)&0xff)/255., ((color>>8)&0xff)/255., ((color>>0)&0xff)/255. ); wgl.clear(wgl.COLOR_BUFFER_BIT); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.