### Install Jinja and Hub Packages Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@huggingface/jinja/README.md Installs the necessary packages for using the Jinja templating engine and interacting with the Hugging Face Hub. ```sh npm i @huggingface/jinja npm i @huggingface/hub ``` -------------------------------- ### Install Transformers.js Package Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@huggingface/jinja/README.md Installs the Transformers.js library, which provides tools for working with pre-trained models and tokenizers. ```sh npm i @huggingface/transformers ``` -------------------------------- ### Apply 4-bit Quantization for Sentiment Analysis Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@huggingface/transformers/README.md This code example illustrates how to apply 4-bit quantization (`q4`) to a sentiment analysis model. Quantization reduces model size and can improve performance, especially in resource-constrained environments like web browsers. The Transformers.js library is necessary for this functionality. ```javascript // Run the model at 4-bit quantization const pipe = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', { dtype: 'q4', }); ``` -------------------------------- ### Determine Startup Path for XUL/HTA Applications (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html This function determines the appropriate startup path for System Animator XUL or HTA applications, considering different operating system versions (Vista and above) and the execution mode (xul_mode). It constructs a path to the user's Start Menu Programs Startup folder. ```javascript var w = System.Gadget.document.parentWindow var startup_path = (xul_mode) ? XPCOM_object._getSpecialPath("Progs") : System.Environment.getEnvironmentVariable("USERPROFILE") + ((Vista_or_above) ? '\\AppData\\Roaming\\Microsoft\\Windows' : '') + '\\Start Menu\\Programs'; startup_path += '\\Startup' var script_name = startup_path + '\\System Animator XUL - Host' ``` -------------------------------- ### Convert and Quantize Model to ONNX using Python Script Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@huggingface/transformers/README.md This script converts and quantizes PyTorch, TensorFlow, or JAX models to ONNX format using the 🤗 Optimum library. It takes the model ID as input and saves the converted ONNX files, including a quantized version, to a local directory. Ensure you have the necessary dependencies installed. ```bash python -m scripts.convert --quantize --model_id ``` ```bash python -m scripts.convert --quantize --model_id bert-base-uncased ``` -------------------------------- ### Use a Custom Model for Sentiment Analysis Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@huggingface/transformers/README.md This example demonstrates how to specify a different pre-trained model for the sentiment analysis pipeline. By providing the model ID as the second argument to the `pipeline` function, you can leverage various sentiment analysis models available in the Hugging Face Hub. This requires the Transformers.js library. ```javascript // Use a different model for sentiment-analysis const pipe = await pipeline('sentiment-analysis', 'Xenova/bert-base-multilingual-uncased-sentiment'); ``` -------------------------------- ### Get XUL Path - JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Retrieves the path to the XUL application. It can optionally check if Firefox is installed. ```javascript function getXULPath(no_warning) { var _xul_path = SystemEXT.GetXULPath(); return _xul_path; } ``` -------------------------------- ### Create XUL Startup Shortcut - JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Creates a startup shortcut for the XUL host. It handles both standard startup shortcuts and WSH-specific shortcuts, and can optionally remove existing shortcuts. ```javascript function createXULStartupShortcut(remove_file) { // set "no_warning" to true to suppress the dialog when Firefox is not installed, since "createXULStartupShortcut" is always run after settings update if (!getXULPath(true)) return; var startup_path = (xul_mode) ? XPCOM_object._getSpecialPath("Progs") : System.Environment.getEnvironmentVariable("USERPROFILE") + ((Vista_or_above) ? '\\AppData\\Roaming\\Microsoft\\Windows' : '') + '\\Start Menu\\Programs'; startup_path += '\\Startup'; if (EnforceWSH.checked && !xul_mode) { var doc_path = System.Environment.getEnvironmentVariable("USERPROFILE") + '\\Documents'; // createXULHostShortcut(doc_path, remove_file) var script_name = 'System Animator XUL - Host'; var lnk_path = startup_path + '\\' + script_name + ' - WSH.lnk'; if (remove_file) { if (FSO_OBJ.FileExists(lnk_path)) { try { FSO_OBJ.DeleteFile(lnk_path); } catch (err) {} } return; } var shortcut = oShell.CreateShortcut(lnk_path); shortcut.TargetPath = System.Environment.getEnvironmentVariable("SystemRoot") + "\\System32\\WScript.exe"; shortcut.WorkingDirectory = doc_path; shortcut.Arguments = '"' + script_name + '.js"'; shortcut.Save(); } else { createXULHostShortcut(startup_path, remove_file); } } ``` -------------------------------- ### Configure XUL Startup and Path Settings - JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html This code snippet handles the configuration for XUL (XML User Interface Language) integration. It includes logic to create a startup shortcut, set the browse path for XUL files, and manage temporary configuration files. It also attempts to update the user's XUL path if a new one is provided and handles cases where the browse element is hidden. ```javascript try { var bv = (webkit\_mode) ? (LXUL\_browse.value && LXUL\_browse.files[0].path) : LXUL\_browse.value if ((LXUL\_browse.style.visibility != "hidden") && bv) { if (bv != SystemEXT.GetXULPath\_USER()) { SystemEXT.GetXULPath\_USER(bv) } } else if (LXUL\_browse.style.visibility == "hidden") { var temp\_config\_xul\_path = System.Gadget.path + '\\TEMP\\\_config\_xul\_path.tmp' if (FSO\_OBJ.FileExists(temp\_config\_xul\_path)) { FSO\_OBJ.DeleteFile(temp\_config\_xul\_path) } } } catch (err) {} ``` -------------------------------- ### Get WebKit Path - JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Determines the path to the Electron/node-webkit executable. It checks user-defined paths and system extensions, alerting the user if no path is found. ```javascript function getWebKitPath(path) { if (!webkit_mode && !LWebKit_browse.value && !SystemEXT.GetWebKitPath(null)) { SA_alert("Please specifiy a path to Electron/node-webkit first.") return "" } var _webkit_path = LWebKit_browse.value && LWebKit_browse.files[0].path; if (!_webkit_path) _webkit_path = SystemEXT.GetWebKitPath(path); return _webkit_path; } ``` -------------------------------- ### Perform Sentiment Analysis with Transformers.js Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@huggingface/transformers/README.md This snippet shows how to initialize and use a sentiment analysis pipeline from the Transformers.js library. It takes a string as input and returns a JSON object containing the predicted sentiment label and its confidence score. Ensure the '@huggingface/transformers' library is installed. ```javascript import { pipeline } from '@huggingface/transformers'; // Allocate a pipeline for sentiment-analysis const pipe = await pipeline('sentiment-analysis'); const out = await pipe('I love transformers!'); // [{'label': 'POSITIVE', 'score': 0.999817686}] ``` -------------------------------- ### Convert 2D Images to 3D Depth-Mapped Wallpapers (JavaScript) Source: https://context7.com/butzyung/systemanimatoronline/llms.txt This snippet demonstrates how to initialize and configure the 3D wallpaper mode using SystemAnimatorOnline. It covers setting rendering options, estimating depth from an image, loading the wallpaper, and handling dynamic wallpaper changes via drag-and-drop. Dependencies include the MMD_SA and DragDrop modules. ```javascript // Initialize 3D wallpaper mode MMD_SA_options = { MMD_disabled: true, // Disable character animation use_THREEX: true, // Enable 3D rendering engine width: 1920, height: 1080 }; // Configure depth estimation MMD_SA.Wallpaper3D.options_general = { depth_shift_percent: 10, // Shift depth range (-300 to 300) depth_contrast_percent: -30, // Adjust depth contrast (-50 to 300) depth_blur: 4, // Blur depth edges (0-16px) depth_model: null, // AI model selection SR_mode: 0, // Super resolution: 0=off, 1=on SR_model: null // SR model selection }; // Load and display 3D wallpaper const wallpaper_src = 'C:/path/to/image.jpg'; MMD_SA.Wallpaper3D.load(wallpaper_src).then(() => { console.log('3D wallpaper ready'); // Dynamic camera control based on mouse MMD_SA_options.look_at_mouse = true; // Adjust position offsets MMD_SA.Wallpaper3D.options.pos_x_offset_percent = 0; MMD_SA.Wallpaper3D.options.pos_y_offset_percent = 0; MMD_SA.Wallpaper3D.options.scale_xy_percent = 150; MMD_SA.Wallpaper3D.options.scale_z_percent = 100; }); // Handle drag-and-drop wallpaper change DragDrop.onDrop_finish = function(item) { if (item.isFileSystem && /\.(jpg|png|webp)$/i.test(item.path)) { MMD_SA.Wallpaper3D.load(item.path); } }; ``` -------------------------------- ### Retrieve XULRunner Path (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html This function retrieves the path to the XULRunner executable. It first checks if a path has been selected via an input element (LXUL_browse). If not, it attempts to get the path using SystemEXT.GetXULPath(). It can optionally suppress warnings if the path is not found. ```javascript function getXULPath(no_warning) { var bv = (webkit_mode) ? (LXUL_browse.value && LXUL_browse.files[0].path) : LXUL_browse.value; if (!bv && !SystemEXT.GetXULPath()) { if (!no_warning) SA_alert("Please specifiy a path to Firefox/XULRunner first."); return ""; } var _xul_path = bv; if (!_xul_pat ``` -------------------------------- ### Audio Visualization and BPM Detection Source: https://context7.com/butzyung/systemanimatoronline/llms.txt Integrate music visualization with beat detection and configure audio event handling. ```APIDOC ## Audio Visualization and BPM Detection API ### Description This API provides functionality to integrate music visualization within the System Animator framework, including real-time beat detection and custom responses to audio events. ### Method Not Applicable (Configuration and Event Handling) ### Endpoint Not Applicable (Configuration and Event Handling) ### Parameters #### Request Body - **Settings_default._custom_.EventToMonitor** (string) - Optional - Specifies the audio events to monitor (e.g., "SOUND_ALL"). - **Settings_default._custom_.UseAudioFFT** (string) - Optional - Enables audio Fast Fourier Transform (FFT) analysis (e.g., "non_default"). - **motion_config** (object) - Optional - Configuration for motion related to audio. - **BPM** (object) - Optional - Beats per minute settings. - **rewind** (boolean) - Optional - Rewind to start when motion ends. - **BPM** (number) - Optional - Beats per minute. - **beat_frame** (number) - Optional - Frame number of the first beat. - **match_even_beats_only** (boolean) - Optional - Sync only on even beats. #### Query Parameters - **Audio_BPM.vo.audio_obj.BPM** (number) - Read-only - Current BPM value. - **Audio_BPM.vo.audio_obj.currentTime** (number) - Read-only - Current playback position of the audio. #### Request Body - **MMD_SA_options.motion_para.[motion_name].BPM** (object) - Optional - BPM settings for a specific motion. - **rewind** (boolean) - Optional - Rewind to start when motion ends. - **BPM** (number) - Optional - Beats per minute. - **beat_frame** (number) - Optional - Frame number of the first beat. - **range** (array) - Optional - Time range for motion playback. - **time** (array) - Optional - [startTime, endTime] for playback range. ### Request Example ```json { "Settings_default": { "_custom_": { "EventToMonitor": "SOUND_ALL", "UseAudioFFT": "non_default" } }, "motion_config": { "BPM": { "rewind": true, "BPM": 128.01, "beat_frame": 820, "match_even_beats_only": true } }, "MMD_SA_options": { "motion_para": { "dance_motion": { "loopback_fading": true, "BPM": { "rewind": true, "BPM": 120, "beat_frame": 450 }, "range": [{ "time": [300, 0] }] } } } } ``` ### Response #### Success Response (200) - **Audio_BPM.vo.audio_obj.BPM** (number) - The current Beats Per Minute. - **Audio_BPM.vo.audio_obj.currentTime** (number) - The current playback position in seconds. #### Response Example ```json { "Audio_BPM.vo.audio_obj.BPM": 125.5, "Audio_BPM.vo.audio_obj.currentTime": 45.78 } ``` ``` -------------------------------- ### Sentiment Analysis Pipeline: Python vs. JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@huggingface/transformers/README.md Demonstrates the usage of the sentiment analysis pipeline in both Python and JavaScript. The JavaScript version mirrors the Python API, allowing for easy translation of existing code. Both examples allocate a pipeline and process an input string. ```python from transformers import pipeline # Allocate a pipeline for sentiment-analysis pipe = pipeline('sentiment-analysis') out = pipe('I love transformers!') ``` ```javascript import { pipeline } from '@huggingface/transformers'; // Allocate a pipeline for sentiment-analysis const pipe = await pipeline('sentiment-analysis'); const out = await pipe('I love transformers!'); ``` -------------------------------- ### Load System Animator Scripts (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/SystemAnimator_online_multiplayer.html This code segment demonstrates the initialization and loading of core System Animator functionalities. It sets up global variables for browser mode and readme URLs, and then calls sequential loading functions (SA_load_scripts, SA_load_body, SA_load_body2) to prepare the application environment. ```JavaScript var use_SA_browser_mode = true var _readme_url_ = "http://www.animetheme.com/system_animator_online/readme_multiplayer.txt" var _url_search_params_ = { cmd_line: "/TEMP/DEMO/rpg_test01" } SA_load_scripts() SA_load_body() SA_load_body2() ``` -------------------------------- ### Create Animation Host for System Animator Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html This JavaScript function dynamically creates a destination folder for animation assets on the user's desktop. It handles path differences between Windows and Linux environments, ensuring the correct desktop path is identified. It also manages versioning and appends a unique index if the destination folder already exists. ```javascript function createAnimationHost() { var desktop_path if (windows_mode) { desktop_path = (xul_mode) ? XPCOM_object._getSpecialPath("Desk") : System.Environment.getEnvironmentVariable("USERPROFILE") + '\\Desktop'; } else if (linux_mode) { desktop_path = SA_require('process').env.HOME + "/Desktop" } var path_parent = desktop_path + toLocalPath('\\SA') + System.Gadget.version.replace(/\..+$/, "") + ' - Animation Host ' var index = 0 var path_destination do { path_destination = path_parent + (++index) } while (FSO_OBJ.FolderExists(path_destination)) FSO_OBJ.CopyFolder(System.Gadget.path + toLocalPath("\\images\\Animation Host"), path_destination) } ``` -------------------------------- ### Manage Hosted HTA Applications and Startup Scripts (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html This script manages a list of hosted HTA applications and creates a startup script to launch them. It handles file operations for temporary configuration files and constructs JavaScript code to check for and launch hosted applications. It supports different browser modes like XUL, WebKit, and Electron. ```javascript if (!use_SA_browser_mode || !(ie9_native || w3c_mode) || !windows_mode) return; var w = System.Gadget.document.parentWindow; var path = Folder.value; if (/^demo/.test(path)) path = w.path_demo[path]; if (path == w.Settings.f_path) path = w.Settings.f_path_folder; var existed; var _hosted_SA_HTA = []; for (var i = 0; i < hosted_SA_HTA.length; i++) { var p = hosted_SA_HTA[i]; if (decodeURIComponent(p) == path) existed = true; else _hosted_SA_HTA.push(p); } if (existed && HTALoadAnimationAtStartup.checked) return; hosted_SA_HTA = _hosted_SA_HTA; if (HTALoadAnimationAtStartup.checked) hosted_SA_HTA.push(encodeURIComponent(path)); var host_path = System.Gadget.path + '\\TEMP\\_hosted_SA_HTA.txt'; var startup_folder = ((xul_mode) ? XPCOM_object._getSpecialPath("Progs") : System.Environment.getEnvironmentVariable("USERPROFILE") + ((Vista_or_above) ? '\\AppData\\Roaming\\Microsoft\\Windows' : '') + '\\Start Menu\\Programs') + '\\Startup'; var script_name = 'System Animator HTA - Host'; var startup_path = startup_folder + '\\' + script_name + ((EnforceWSH.checked) ? ' - WSH.lnk' : '.js'); if (!hosted_SA_HTA.length) { try { if (FSO_OBJ.FileExists(host_path)) FSO_OBJ.DeleteFile(host_path); if (FSO_OBJ.FileExists(startup_path)) FSO_OBJ.DeleteFile(startup_path); } catch (err) {} return; } var f = FSO_OBJ.OpenTextFile(host_path, 2, true); f.Write('["' + hosted_SA_HTA.join('","') + '"]'); f.Close(); var rn = '\r\n'; var js = checkGadgetJS(); var ER_check = electronRegisterCheck(); if (xul_mode) { js += rn + SystemEXT.CheckXULJS(); } else if (webkit_mode && !ER_check) { js += rn + SystemEXT.CheckWebKitJS(); } js += rn + 'var host_path = hta + "\\TEMP\\_hosted_SA_HTA.txt";' + rn + 'if (fso.FileExists(host_path)) {' + rn + ' var file = fso.OpenTextFile(host_path, 1);' + rn + ' var txt = file.ReadAll();' + rn + ' file.Close();' + rn + rn + ' var hosted_SA_HTA = [];' + rn + ' if (txt)' + rn + ' hosted_SA_HTA = eval(txt);' + rn + rn + ' for (var i = 0; i < hosted_SA_HTA.length; i++) {' + rn + ' var f = decodeURIComponent(hosted_SA_HTA[i]);' + rn if (ie9_native) { js += ' oShell.ShellExecute(hta + "\\SystemAnimator_ie.hta", \'"\' + f + \'"\');' + rn; } else if (xul_mode) { js += ' oShell.ShellExecute(XUL_path, ((/firefox.exe/i.test(XUL_path)) ? "-app " : "") + \'"\' + hta + \'\\\_xul_gadget\\application.ini" "\'" + f + \'"\');' + rn; } else { if (ER_check) { js += ' oShell.ShellExecute("system-animator://" + encodeURIComponent(f));' + rn; } else { js += ' oShell.ShellExecute(WebKit_path, \'"\' + hta + \'" "\'" + f + \'"\');' + rn; } } js += ' }' + rn + '}' + rn; js = js.replace(/\\/g, "\\\\"); var doc_path, startup_js; if (EnforceWSH.checked) { doc_path = System.Environment.getEnvironmentVariable("USERPROFILE") + '\\Documents'; startup_js = doc_path + '\\' + script_name + '.js'; } else startup_js = startup_path; var f = FSO_OBJ.OpenTextFile(startup_js, 2, true); f.Write(js); f.Close(); //} catch (err) {webkit_electron_remote.dialog.showMessageBox(null, {type:"info", buttons:["OK"], message:startup_js+'\n'+navigator.userAgent})} if (EnforceWSH.checked) SystemEXT.CreateShortcut([System.Environment.getEnvironmentVariable("SystemRoot") + "\\System32\\WScript.exe", startup_path, doc_path, '"' + script_name + '.js"']); ``` -------------------------------- ### Configure Webcam Motion Capture (JavaScript) Source: https://context7.com/butzyung/systemanimatoronline/llms.txt Sets up AI-based full-body motion capture using a webcam. It configures MediaPipe for pose, face, and hand tracking, along with performance settings for detection and rendering, and options for recording motion data in various formats. ```javascript // Enable full-body motion capture MMD_SA_options.motion_capture = { enabled: true, mode: "full_body", // "face", "upper_body", "full_body" // MediaPipe configuration mediapipe: { pose: true, // Body tracking face: true, // Face tracking with 52 blendshapes hands: true, // Hand/finger tracking smoothing: 0.5 // Smoothing factor (0-1) }, // Performance settings detection_fps: 30, // Pose detection frame rate render_fps: 60, // 3D rendering frame rate // Recording options recording: { format: "vmd", // "vmd", "bvh", "gltf" enabled: false } }; // Start motion capture function startMotionCapture() { navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => { MMD_SA.motion_capture.start(stream); }) .catch(err => { console.error("Camera access denied:", err); }); } // Record and export motion MMD_SA.motion_capture.startRecording(); setTimeout(() => { MMD_SA.motion_capture.stopRecording(); MMD_SA.motion_capture.export("my_motion.vmd"); }, 30000); // Record for 30 seconds ``` -------------------------------- ### Create XUL Host Shortcut - JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Creates a host shortcut for the XUL application. This function can also be used to remove an existing shortcut if the 'remove_file' parameter is true. ```javascript function createXULHostShortcut(path, remove_file) { path += '\\System Animator XUL - Host.js'; if (remove_file) { if (FSO_OBJ.FileExists(path)) { try { FSO_OBJ.DeleteFile(path); } catch (err) {} } return; } var rn = '\r\n'; var js = checkGadgetJS() + rn + SystemEXT.CheckXULJS() + rn + ``` -------------------------------- ### JavaScript Drag and Drop Event Handling with Electron Source: https://github.com/butzyung/systemanimatoronline/blob/master/drop_area.html Handles drag and drop events for files within an Electron application. It extends the File prototype to get the file path and sets up event listeners for drag enter, exit, over, and drop. The drop handler retrieves the file path and sends it to the main process via Electron's remote module or IPC. ```javascript window.onload = function () { // assumed electron v32+ Object.defineProperty(File.prototype, "path", ( ()=>{ const { webUtils } = require('electron'); return { get: function () { return webUtils.getPathForFile(this); } }; })()); document.ondblclick = function () { window.close() } var _dragCancelDefault = function (e) { e.stopPropagation(); e.preventDefault(); } var _dragEnter = function (e) { _dragCancelDefault(e) } var _dragExit = function (e) { _dragCancelDefault(e) } var _dragOver = function (e) { _dragCancelDefault(e) } var _drop = function (e) { _dragCancelDefault(e); var path = e.dataTransfer.files[0].path; /* var item = new System.Shell._FolderItem(new WebKit_object["Shell.Application"]._FolderItem({path:path})) if (DragDrop.validate_func(item)) DragDrop.onDrop_finish(item) */ // NOTE: getGlobal is NOT reliable here with the current version of @electron/remote //if ((require('electron').remote || require('@electron/remote')).getGlobal("is_transparent")) document.getElementById('Ldrop_area').style.visibility="hidden"; //(require('electron').remote || require('@electron/remote')).getGlobal("DropArea_drop")(path); var remote = require('electron').remote; if (remote) { remote.getGlobal("DropArea_drop")(path); } else { let ipcRenderer = require('electron').ipcRenderer; ipcRenderer.send('getGlobal', 'DropArea_drop', path); } } document.addEventListener("dragenter", _dragEnter, false); document.addEventListener("dragexit", _dragExit, false); document.addEventListener("dragover", _dragOver, false); document.addEventListener("drop", _drop, false); } ``` -------------------------------- ### Execute Application with ShellExecute Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Executes an application using the ShellExecute method. It supports launching Firefox with an application flag if the path matches. Requires a reference to 'oShell' and 'XUL_path' variable. ```javascript oShell.ShellExecute(XUL_path, ((/firefox.exe/i.test(XUL_path)) ? "-app " : "") + '"' + hta + '\\_xul_gadget_host\\application.ini"'); ``` -------------------------------- ### Read Wallpaper Source from File (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html This code reads the source path for the SA wallpaper from a text file located in the TEMP directory. It uses the FileSystemObject (FSO_OBJ) to check if the file exists, open it, read the first line, and store it in 'SA_wallpaper_src'. Error handling is included. ```javascript if (!use_SA_browser_mode) return SA_wallpaper_path = System.Gadget.path + toLocalPath('\\TEMP\\SA_wallpaper_src.txt') SA_wallpaper_src = "" if (FSO_OBJ.FileExists(SA_wallpaper_path)) { try { var f = FSO_OBJ.OpenTextFile(SA_wallpaper_path, 1); SA_wallpaper_src = f.ReadLine() f.Close() LSAWallpaperSrc.innerText = SA_wallpaper_src } catch (err) {} } ``` -------------------------------- ### Create Holistic Landmarker (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@mediapipe/tasks/tasks-vision/README.md Creates a Holistic Landmarker instance from a specified task file. This task combines pose, face, and hand landmark detection for comprehensive human body analysis. It requires the initialized vision tasks and a model path. ```javascript const holisticLandmarker = await HolisticLandmarker.createFromModelPath(vision,"https://storage.googleapis.com/mediapipe-models/holistic_landmarker/holistic_landmarker/float16/1/hand_landmark.task"); const image = document.getElementById("image") as HTMLImageElement; const landmarks = holisticLandmarker.detect(image); ``` -------------------------------- ### Define Custom Actions and Interactions (JavaScript) Source: https://context7.com/butzyung/systemanimatoronline/llms.txt This snippet illustrates how to define custom interactive behaviors and model customizations within SystemAnimatorOnline. It shows how to register built-in actions like 'cover_undies' and define custom actions with associated motions and animation checks. It also covers overriding default interaction behaviors like double-clicking. Dependencies include MMD_SA and System.Gadget.path. ```javascript MMD_SA_options.custom_action = [ "cover_undies" // Built-in action ]; // Built-in actions are pre-defined, or define custom ones: MMD_SA.custom_action_default["cover_undies"] = { action: { // Action will be assigned motion_index automatically name: "Cover Undies", icon: System.Gadget.path + "/images/icon_dress.png" }, motion: { path: System.Gadget.path + '/MMD.js/motion/cover_undies.vmd' }, animation_check: function() { // Return true to enable this action return MMD_SA.MMD_started && !MMD_SA.music_mode; } }; // Define custom interaction MMD_SA_options.ondblclick = function(e) { // Override default double-click behavior console.log("Custom double-click action"); MMD_SA.SpeechBubble.message(0, "You clicked me! ^_^", 3000); return true; // Return true to prevent default action }; ``` -------------------------------- ### Browse and Select Animation Folder (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html The 'BrowseFolder' function allows users to select a folder containing animations. It uses 'System.Shell.chooseFolder' for folder selection and updates the 'Folder' dropdown accordingly. It also calls 'hidemacface' to adjust UI elements based on the selected folder's properties. ```javascript function BrowseFolder() { if (webkit_mode) { parent_window.document.getElementById("Idialog").style.visibility = "hidden" parent_window.SA_OnFolder() return } var shellFolder = System.Shell.chooseFolder("Choose a folder with animation supported by System Animator.", 0); if (shellFolder) { Folder.options[0].value = Folder.options[0].innerText = shellFolder.path Folder.options[0].selected = true } hidemacface(); } ``` -------------------------------- ### Create XUL Desktop Shortcut - JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Creates a desktop shortcut for the XUL host. If WSH is enforced and not in XUL mode, it creates a specific WSH shortcut. ```javascript function createXULDesktopShortcut() { if (!getXULPath()) return; var desktop_path = (xul_mode) ? XPCOM_object._getSpecialPath("Desk") : System.Environment.getEnvironmentVariable("USERPROFILE") + '\\Desktop'; if (EnforceWSH.checked && !xul_mode) { var doc_path = System.Environment.getEnvironmentVariable("USERPROFILE") + '\\Documents'; createXULHostShortcut(doc_path); var script_name = 'System Animator XUL - Host'; var shortcut = oShell.CreateShortcut(desktop_path + '\\' + script_name + ' - WSH.lnk'); shortcut.TargetPath = System.Environment.getEnvironmentVariable("SystemRoot") + "\\System32\\WScript.exe"; shortcut.WorkingDirectory = doc_path; shortcut.Arguments = '"' + script_name + '.js"'; shortcut.Save(); } else createXULHostShortcut(desktop_path); } ``` -------------------------------- ### Manage Motion Playlists and Shuffle (JavaScript) Source: https://context7.com/butzyung/systemanimatoronline/llms.txt This code configures the motion playback for character animations. It defines a list of motion files (e.g., VMDs), sets up shuffle pools and specific playback sequences, including custom sequences for different songs. It also allows disabling random range variation for precise control. Dependencies include System.Gadget.path. ```javascript MMD_SA_options.motion = [ { path: System.Gadget.path + '/MMD.js/motion/stand.vmd' }, // Index 0 { path: System.Gadget.path + '/MMD.js/motion/dance1.vmd' }, // Index 1 { path: System.Gadget.path + '/MMD.js/motion/dance2.vmd' }, // Index 2 { path: System.Gadget.path + '/MMD.js/motion/dance3.vmd' }, // Index 3 { must_load: true, no_shuffle: true, path: System.Gadget.path + '/MMD.js/motion/special.vmd' } // Index 4 ]; // Define shuffle pool and sequence MMD_SA_options.motion_shuffle_pool_size = 5; // Number of motions to shuffle MMD_SA_options.motion_shuffle = [1, 3, 2, 1, 3]; // Play order by index MMD_SA_options.motion_shuffle_list_default = [0]; // Default motion when idle // Song-specific motion sequences MMD_SA_options.motion_shuffle_by_song_name = { "favorite_song.mp3": [1, 2, 3, 1, 2], // Custom sequence for this song "another_song.mp3": [3, 3, 1, 2, 1] }; // Disable random range variation for precise timing MMD_SA_options.random_range_disabled = true; ``` -------------------------------- ### Configure Audio Visualization and BPM Detection in System Animator Source: https://context7.com/butzyung/systemanimatoronline/llms.txt This JavaScript code configures audio visualization and beat detection for System Animator. It sets audio monitoring, FFT usage, and defines parameters for beat synchronization, including BPM, rewind, and frame offsets. It also shows how to access real-time audio data and handle audio end events for custom logic. ```javascript // Configure audio visualization Settings_default._custom_.EventToMonitor = "SOUND_ALL"; Settings_default._custom_.UseAudioFFT = "non_default"; // Beat detection configuration var motion_config = { BPM: { rewind: true, // Rewind to start when motion ends BPM: 128.01, // Beats per minute beat_frame: 820, // Frame number where first beat occurs match_even_beats_only: true // Optional: sync only on even beats } }; // Access audio data in real-time Audio_BPM.vo.audio_obj.BPM; // Current BPM Audio_BPM.vo.audio_obj.currentTime; // Playback position // Custom beat response MMD_SA_options.motion_para["dance_motion"] = { loopback_fading: true, BPM: { rewind: true, BPM: 120, beat_frame: 450 }, range: [{ time: [300, 0] }] // Skip first 300 frames }; // Handle audio events Audio_BPM.vo.audio_onended = function(e) { console.log("Audio ended, triggering next action"); // Custom logic here }; ``` -------------------------------- ### JavaScript Dialog Handling and UI Initialization Source: https://github.com/butzyung/systemanimatoronline/blob/master/SystemAnimator_browse.html This snippet manages the native dialog behavior in WebKit mode, including setting return values, handling user interactions ('OK', 'Cancel'), and updating the UI. It addresses potential variable scope issues and dynamically creates a file/folder browse input element. Dependencies include `LBFF_browse`, `opener`, `parent`, `SA_dialog_restore_parent_size`, `AudioFFT_active`, `SA_DragDropEMU`, `Shell_OBJ`, and `SA_dialog_resize`. ```javascript /* Native dialog in WebKit mode (v0.8.0-rc1): - "self.xxx" and "var xxx" are messed up sometimes. Some variables declared in a block may disappear in another block for unknown reasons. */ self.returnValue = null if (opener) opener.returnValue = null var webkit_mode = /WebKit/i.test(navigator.userAgent) function _ok() { self.returnValue = LBFF_browse.value; if (opener) opener.returnValue = LBFF_browse.value; _finish(); if (parent.use_inline_dialog) { self.location.replace("z_blank.html"); } else { self.close(); } } function _cancel() { _finish(); if (parent.use_inline_dialog) { self.location.replace("z_blank.html"); } else { self.close(); } } function _finish() { if (parent.use_inline_dialog) { SA_dialog_restore_parent_size(); parent.document.getElementById("Idialog").style.visibility = "hidden"; parent.AudioFFT_active && parent.AudioFFT_active.restartCaptureAudioWE && parent.AudioFFT_active.restartCaptureAudioWE(); var v = self.returnValue; if (v) { if (/folder/.test(title)) parent.SA_DragDropEMU((new parent.Shell_OBJ._Folder({path:v})).Self.Path); else parent.SA_DragDropEMU(LBFF_browse.files[0]); } } } var title = (/title\=([^\&]+)/.test(location.search)) ? decodeURIComponent(RegExp.$1) : "Dialog"; document.write(''); if (opener) Lbuttons.style.left = "60px"; if (webkit_mode) Lbrowse_for_file.style.top = "20px"; var w = 405 + ((opener) ? 60 : 0); var h = 24 + ((opener) ? 0 : 14); document.getElementById("Lsettings_main").style.width = w + "px"; SA_dialog_resize(w, h + ((parent.use_inline_dialog) ? 50 : 0)); onload = function () { document.getElementById("Stitle").innerHTML = title; } ``` -------------------------------- ### 3D Scene Customization with Mirror/Water Effects in System Animator Source: https://context7.com/butzyung/systemanimatoronline/llms.txt This JavaScript code demonstrates how to create reflective surfaces and 3D environmental effects in System Animator, specifically implementing a water surface with reflection. It configures the mirror object's style, reflection properties, plane dimensions, and water shader parameters. It also includes a custom action function for animating the water surface and reacting to music beats. ```javascript MMD_SA_options.mirror_obj = [ { // Water surface reflection style: 'rotateX:' + (-Math.PI/2) + ';', // Horizontal plane // Reflection settings reflection_alpha: 0.6, fade_radius: 15, fade_min: 0, fade_max: 0.9, // Plane dimensions plane: [30, 30, 100, 100], // [segments_x, segments_y, width, height] // Water shader parameters baseSpeed: 1.15, baseTexture: System.Gadget.path + "/images/watershader_water.jpg", noiseScale: 0.2, noiseTexture: System.Gadget.path + "/images/watershader_cloud.png", // Custom animation logic custom_action: function(mirror) { if (!MMD_SA.MMD_started) return; var mesh = jThree(mirror._mesh_id).three(0); // Position relative to character var cv = MMD_SA.center_view; mesh.position.set(cv[0], 0, cv[2]); // Reactive to music beat if (MMD_SA.music_mode && mesh.material.uniforms.baseSpeed.value) { var beat = (EV_usage_sub && EV_usage_sub.BD) ? EV_usage_sub.BD.beat : 0; mesh.material.uniforms.bumpScale.value = this.bumpScale * (1 + 5 * beat); } } } ]; ``` -------------------------------- ### Create Hand Landmarker (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@mediapipe/tasks/tasks-vision/README.md Creates a Hand Landmarker instance from a specified task file. This task detects landmarks of hands in an image, enabling the localization of key hand points. It requires the initialized vision tasks and a model path. ```javascript const handLandmarker = await HandLandmarker.createFromModelPath(vision,"https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task"); const image = document.getElementById("image") as HTMLImageElement; const landmarks = handLandmarker.detect(image); ``` -------------------------------- ### Generate CPU Usage Options for Dropdown (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html The 'writeCPUOptions' function dynamically generates HTML options for a dropdown menu, representing CPU usage monitoring. It creates options like 'CPU1', 'CPU2', etc., and adjusts the label based on whether it's a core or meter usage. The maximum number of options is determined by 'use_SA_browser_mode' or the system's CPU count. ```javascript function writeCPUOptions() { var html = "" var max = (use_SA_browser_mode) ? 8 : System.Machine.CPUs.count for (var i = 0; i < max; i++) html += '\n' document.write(html) } ``` -------------------------------- ### Launch XUL Application - JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Launches a XUL application, checking for specific browser modes and executing the application. Handles different launch conditions based on whether the application is hosted. ```javascript function launchXUL() { var w = System.Gadget.document.parentWindow.SA_top_window; if (w.is_SA_hosted) { w.opener.openSA(); return; } var _xul_path = getXULPath(); if (_xul_path) { System.Shell.execute(_xul_path, ((/firefox/i.test(_xul_path)) ? '-app ' : '') + '"' + System.Gadget.path + '\\_xul_gadget\\application.ini"');//'\\_xul_gadget_host\\application.ini"' + ((EnforceWSH.checked)?' wsh':''));// } } ``` -------------------------------- ### Check if HTA Animation is Loaded at Startup (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html This snippet checks if a specific HTA animation is set to load at startup. It compares the current folder path ('w.Settings.f_path_folder') with the paths of animations stored in 'hosted_SA_HTA'. If a match is found, it sets the 'HTALoadAnimationAtStartup' checkbox to true. ```javascript var path = w.Settings.f_path_folder for (var i = 0; i < hosted_SA_HTA.length; i++) { if (path == decodeURIComponent(hosted_SA_HTA[i])) { HTALoadAnimationAtStartup.checked = true break } } ``` -------------------------------- ### Reset Load at Startup Settings - JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Resets all startup animation settings for System Animator. This involves deleting specific files related to hosted applications and startup shortcuts. ```javascript function resetLoadAtStartup() { if (non_windows_native_mode) return; if (!confirm("This will reset all startup animation settings for System Animator.")) return; var host_path = System.Gadget.path + '\\TEMP\\_hosted_SA_HTA.txt'; var startup_folder = ((xul_mode) ? XPCOM_object._getSpecialPath("Progs") : System.Environment.getEnvironmentVariable("USERPROFILE") + ((Vista_or_above) ? '\\AppData\\Roaming\\Microsoft\\Windows' : '') + '\\Start Menu\\Programs') + '\\Startup'; var script_name = 'System Animator HTA - Host'; var startup_path = startup_folder + '\\' + script_name + ((EnforceWSH.checked) ? ' - WSH.lnk' : '.js'); hosted_SA_HTA = []; HTALoadAnimationAtStartup.checked = false; var deleted = 0; try { if (FSO_OBJ.FileExists(host_path)) { FSO_OBJ.DeleteFile(host_path); deleted++; } if (FSO_OBJ.FileExists(startup_path)) { FSO_OBJ.DeleteFile(startup_path); deleted++; } } catch (err) {} SA_alert((deleted) ? "All startup animation settings have been cleared." : "No existing animation has been scheduled to load at startup."); } ``` -------------------------------- ### Display Gadget Version in HTML using JavaScript Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html This immediately-invoked function expression (IIFE) retrieves the System Gadget version and writes it to the HTML document. It formats the version string by removing any dot-notation extensions. ```javascript (function () { var html = 'Version ' + System.Gadget.version;//.replace(/\.\d+$/, "") document.write(html) })(); ``` -------------------------------- ### Read Wallpaper Mask Source from File (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html Similar to reading the wallpaper source, this snippet reads the source path for the SA wallpaper mask from a text file in the TEMP directory. It utilizes FSO_OBJ to check for the file's existence, open it, read the first line, and store it in 'SA_wallpaper_mask_src', with error handling. ```javascript SA_wallpaper_mask_path = System.Gadget.path + toLocalPath('\\TEMP\\SA_wallpaper_mask_src.txt') SA_wallpaper_mask_src = "" if (FSO_OBJ.FileExists(SA_wallpaper_mask_path)) { try { var f = FSO_OBJ.OpenTextFile(SA_wallpaper_mask_path, 1); SA_wallpaper_mask_src = f.ReadLine() f.Close() LSAWallpaperMaskSrc.innerText = SA_wallpaper_mask_src } catch (err) {} } ``` -------------------------------- ### Create Face Landmarker (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@mediapipe/tasks/tasks-vision/README.md Creates a Face Landmarker instance from a specified task file. This task detects facial landmarks in an image, allowing for localization of key facial points. It requires the initialized vision tasks and a model path. ```javascript const faceLandmarker = await FaceLandmarker.createFromModelPath(vision,"https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task"); const image = document.getElementById("image") as HTMLImageElement; const landmarks = faceLandmarker.detect(image); ``` -------------------------------- ### Run Sentiment Analysis on WebGPU Source: https://github.com/butzyung/systemanimatoronline/blob/master/js/@huggingface/transformers/README.md This snippet shows how to configure the sentiment analysis pipeline to run on the GPU using WebGPU. This can significantly improve performance in compatible browsers. Ensure your browser supports WebGPU. The Transformers.js library is required. ```javascript // Run the model on WebGPU const pipe = await pipeline('sentiment-analysis', 'Xenova/distilbert-base-uncased-finetuned-sst-2-english', { device: 'webgpu', }); ``` -------------------------------- ### Set Initial Folder Value from Settings (JavaScript) Source: https://github.com/butzyung/systemanimatoronline/blob/master/settings.html The 'setFolderValue' function initializes the 'Folder' dropdown with a previously saved folder path from system settings. If no saved path exists, it defaults to 'Settings_default.Folder'. It iterates through the dropdown options to find and select the saved or default folder. ```javascript function setFolderValue() { var v = System.Gadget.Settings.readString("Folder") if (v && !/^demo\d+/.test(v)) { Folder.options[0].value = Folder.options[0].innerText = v Folder.options[0].selected = true } else { if (!v) v = Settings_default.Folder for (var i = 0; i < Folder.options.length; i++) { var o = Folder.options[i] var vv = o.value if (vv == v) { o.selected = true break } } } } ```