### Install Dependencies Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/SubtractOne/gui/README.md Run this command to install the necessary project dependencies. ```bash npm install ``` -------------------------------- ### Input Value File Format Example Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Test File Format.md Example JSON structure for input value endpoints. It includes 'frameOffset' for timing, 'value' for the target value, and 'framesToReachValue' for smoothing duration. ```JSON [ { "frameOffset": 100, "value": 0.4, "framesToReachValue": 100 }, { "frameOffset": 150, "value": 1.0, "framesToReachValue": 10 } ] ``` -------------------------------- ### Canvas Setup in connectedCallback (After Fix) Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/Claude/FilterEQ/claudeSession.txt Demonstrates the corrected approach for canvas setup, moving it to connectedCallback() to ensure the element is in the DOM, with a fallback delayed redraw. ```javascript connectedCallback() { this.setupCanvas(); setTimeout(() => this.setupCanvas(), 100); // Backup redraw } ``` -------------------------------- ### Input Event File Format Example Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Test File Format.md Example JSON structure for input event endpoints. 'frameOffset' specifies the frame number, and 'event' contains the value to be sent. The 'frameOffset' values must be monotonically increasing. ```JSON [ { "frameOffset" : 10, "event" : 1.0 }, { "frameOffset" : 100, "event" : 5.0 } ] ``` -------------------------------- ### Start Local Development Server Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/SubtractOne/gui/README.md Use this script to run a local server for development. It includes hot reloading for source file changes. ```bash npm run start ``` -------------------------------- ### Initialize GUI Module with PatchConnection Source: https://github.com/cmajor-lang/cmajor/blob/main/javascript/Javascript README.md Example of how to initialize a GUI module, access Cmajor version, and use MIDI utilities via the PatchConnection object. ```javascript export default function createPatchView (patchConnection) { console.log (`Cmajor version: ${patchConnection.getCmajorVersion()}`); console.log (`MIDI message: ${patchConnection.midi.getMIDIDescription (0x924030)}`); const keyboard = new patchConnection.utilities.PianoKeyboard(); } ``` -------------------------------- ### Start Cmaj WASM Audio Engine Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/SubtractOne/gui/README.md This script starts the full web app with the cmaj WASM audio engine enabled. ```bash npm run start:cmaj-wasm ``` -------------------------------- ### Cmajor Channel Layout Examples Source: https://github.com/cmajor-lang/cmajor/blob/main/CLAUDE.md Provides examples of defining input and output streams for mono, stereo, and multi-channel audio processors. ```cmajor // Mono processor input stream float audioIn; output stream float audioOut; // Stereo processor input stream float<2> audioIn; output stream float<2> audioOut; // Multi-channel input stream float<8> audioIn; ``` -------------------------------- ### Canvas Setup in Constructor (Before Fix) Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/Claude/FilterEQ/claudeSession.txt Illustrates the incorrect placement of canvas setup within the constructor, leading to timing issues as the element may not be in the DOM yet. ```javascript constructor() { this.setupCanvas(); // Too early! } ``` -------------------------------- ### Start Cmaj Patch View Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/SubtractOne/gui/README.md This script starts a stripped-down version of the app for viewing cmajor patches. ```bash npm run start:cmaj-patch ``` -------------------------------- ### Variable and parameter declaration Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Provides examples of declaring local variables and function parameters using explicit types and the 'let'/'var' keywords for auto-deduced constants and mutable variables. ```cpp void myFunction (int param1, const float param2) { int64 a = 1; // a is a mutable int64 const int c = 2; // c is a const int32 let b = 2; // b is a const int32 var d = 2; // d is a mutable int32 var e = bool[10](); // e is a mutable array of 10 bools bool[10] f; // f is a mutable array of 10 bools complex64 g; // g is a complex number, initialised to zero MyStruct h; // h is an object, with all its fields zero-initialised. } ``` -------------------------------- ### Clone GuitarLSTM Repository Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/GuitarLSTM/README.md Clone the GuitarLSTM repository to access the example code and scripts. Ensure submodules are initialized and updated. ```bash git clone git@github.com:cmajor-lang/GuitarLSTM.git cd GuitarLSTM git submodule init git submodule update ``` -------------------------------- ### Get help for Cmajor command-line tool Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Quick Start.md Run `cmaj help` to display the available arguments and options for the Cmajor command-line tool. ```shell $ cmaj help ``` -------------------------------- ### Access Array Size and Elements Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Illustrates how to get the size of an array and access elements using the `[]` operator. Explains runtime index checking and the `.at()` method. ```cpp int[8] x; let sizeOfX = x.size; // This is 8 let a1 = x[3]; // OK let a2 = x[-1]; // OK: this returns the last element of the array let a3 = x[10]; // Error: the compiler sees that this constant integer is out of bounds. wrap<8> wrappedInt = ... // 'wrappedInt' is a wrap<8> so has the range 0 to 7 int normalInt = ... // 'normalInt' is a normal integer so could have any value let a4 = x[wrappedInt]; // This produces efficient code because the compiler knows that the wrap<8> // value can never exceed the bounds of an array with size 8. let a5 = x[normalInt]; // This compiles, but will emit a performance warning because the compiler // needs to insert a wrap operation to make sure the integer index is in-range. let a6 = x.at(normalInt); // Using .at() instead of [] tells the compiler not to emit a performance warning let a7 = x[wrap<8> (normalInt)]; // Casting the integer to a wrap<8> also removes the performance warning ``` -------------------------------- ### Frequency-Dependent Calculations Source: https://github.com/cmajor-lang/cmajor/blob/main/CLAUDE.md Example demonstrating frequency-dependent calculations in Cmajor, using the processor's frequency property. ```cmajor // Frequency-dependent calculations phase += freq / float(processor.frequency); ``` -------------------------------- ### Worker Script Example Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Patch Format.md The worker module must export a default function that accepts a PatchConnection object. Use this object to communicate with the patch, manage timers, and send events. ```javascript export default function myWorker (patchConnection) { patchConnection.addStatusListener ((status) => console.log (status)); patchConnection.requestStatusUpdate(); setTimeout (() => { patchConnection.sendEventOrValue ("myevent", 1234); }, 1000); } ``` -------------------------------- ### Standard Function Declaration in Cmaj Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Illustrates the basic syntax for declaring functions in Cmaj, similar to C/C++/Java/C#. Includes examples of functions with different return types and parameters. ```cpp void doSomething (int parameter1, bool parameter2) { // ... } ``` ```cpp float calculateAverage (float f1, float f2) { return (f1 + f2) / 2.0f; } ``` -------------------------------- ### Fix Import Statement Placement in Cmajor Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/Claude/FilterEQ/claudeSession.txt Cmajor requires import statements to be declared at the start of a namespace. This example shows the correction of an import statement that was misplaced. ```cmajor 1 + import std.filters; 2 + 3 /* 4 FilterEQ - A multiband filter with interactive GUI 5 ... 8 - Individual filter enable/disable controls 9 */ 10 11 - import std.filters; 12 - 11 /// Main FilterEQ processor 12 processor FilterEQ [[ main ]] 13 { ``` -------------------------------- ### Build GUI with npm Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/FilterBank/README.md Navigate to the GUI directory and run the build script to compile the React application for use in the patch. ```bash > cd gui > npm run build ``` -------------------------------- ### Processor and Endpoint Annotations Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Demonstrates how to attach annotations to processors, endpoints, and variables using double-square-brackets for metadata. ```cpp // A processor annotation is written after its name and before the open-brace: processor P [[ name: "hello", animal: "cat", size: 123 ]] { // An endpoint or variable annotation goes between its name and the semi-colon: input event float in [[ name: "input", min: 10.0, max: 100.0 ]]; int x [[ desc: "blah", number: 1234 ]]; } ``` -------------------------------- ### macOS Platform Configuration Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/native_apps/CMakeLists.txt Links necessary frameworks for macOS, including WebKit, Accelerate, CoreAudio, CoreMIDI, AudioToolbox, Foundation, IOKit, and Cocoa. ```cmake if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") target_link_libraries(RenderPatchSharedLib PRIVATE "-framework WebKit") target_link_libraries(RenderPatchSharedLib PRIVATE "-framework Accelerate") target_link_libraries(RenderPatchSharedLib PRIVATE "-framework CoreAudio") target_link_libraries(RenderPatchSharedLib PRIVATE "-framework CoreMIDI") target_link_libraries(RenderPatchSharedLib PRIVATE "-framework AudioToolbox") target_link_libraries(RenderPatchSharedLib PRIVATE "-framework Foundation") target_link_libraries(RenderPatchSharedLib PRIVATE "-framework IOKit") target_link_libraries(RenderPatchSharedLib PRIVATE "-framework Cocoa") endif() ``` -------------------------------- ### Declare and Initialize Arrays Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Shows various ways to declare and initialize arrays, including direct value assignment and zero-initialization. ```cpp let x = int[4] (1, 2, 3, 4); // these all declare an array containing 1, 2, 3, 4 let x = int[] (1, 2, 3, 4); int[] x = (1, 2, 3, 4); int[4] y; // these are all zero-initialised int[4] y = (); var y = int[4](); ``` -------------------------------- ### Convert Time to Frames Source: https://github.com/cmajor-lang/cmajor/blob/main/CLAUDE.md Example of converting time to frames using the processor's frequency property in Cmajor. ```cmajor // Convert time to frames let framesPerSecond = int(processor.frequency); ``` -------------------------------- ### Configure CLAP Interface Library Source: https://github.com/cmajor-lang/cmajor/blob/main/modules/plugin/include/clap/CMakeLists.txt Creates an interface library target for CLAP, setting include directories and C++ standard features. ```cmake add_library(clap INTERFACE) target_include_directories(clap INTERFACE $) target_compile_features(clap INTERFACE c_std_11) ``` -------------------------------- ### Connection Expressions Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Shows how to use expressions, constants, and built-in functions as sources for connections. This allows for data manipulation before it reaches the destination endpoint. ```cpp /// specify a constant 0.5f -> node1.in; /// Perform an arithmetic expression on multiple input values or streams in1 * in2 -> node2.in; /// Take the minimum of two inputs std::min (in1, in2) -> node2.in; ``` -------------------------------- ### Link macOS WebKit Dependency Source: https://github.com/cmajor-lang/cmajor/blob/main/modules/plugin/include/common/CMakeLists.txt Conditionally links the WebKit library on macOS systems. This is part of the platform-specific dependency setup. ```cmake if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") find_library(MAC_WEBKIT WebKit) target_link_libraries(cmaj_public_deps_for_plugin_wrapper INTERFACE ${MAC_WEBKIT}) endif() ``` -------------------------------- ### Linux Platform Configuration Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/native_apps/CMakeLists.txt Configures dependencies for Linux, including PkgConfig, GTK3, and WebKit2. It also sets up extra libraries like dl, pthread, and asound. ```cmake if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") find_package(PkgConfig REQUIRED) pkg_check_modules (GTK3 REQUIRED gtk+-3.0 IMPORTED_TARGET) pkg_check_modules (WEBKIT2 REQUIRED ${WEBKIT2_GTK_VERSION} IMPORTED_TARGET) target_include_directories (RenderPatchSharedLib PUBLIC ${GTK3_INCLUDE_DIRS} ${WEBKIT2_INCLUDE_DIRS}) target_link_libraries (RenderPatchSharedLib PUBLIC ${GTK3_LIBRARIES} ${WEBKIT2_LIBRARIES}) if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "armv7l") target_link_libraries (RenderPatchSharedLib PUBLIC atomic) endif() set (EXTRA_LIBS dl ${GTK3_LIBRARIES} ${WEBKIT2_LIBRARIES} "-pthread" "-lasound") endif() ``` -------------------------------- ### Calculate Oscillator Phase Increment Source: https://github.com/cmajor-lang/cmajor/blob/main/CLAUDE.md Example of calculating the phase increment for an oscillator in Cmajor, utilizing processor frequency and period properties. ```cmajor // Calculate phase increment for oscillator let phaseDelta = frequency * processor.period * twoPi; ``` -------------------------------- ### Configure Cmajor CLAP Interface Library Source: https://github.com/cmajor-lang/cmajor/blob/main/modules/plugin/include/clap/CMakeLists.txt Sets up an interface library for Cmajor's CLAP integration, including source files, include paths, C++ standard, and linking dependencies. ```cmake add_library(cmaj_clap INTERFACE) target_sources(cmaj_clap INTERFACE cmaj_CLAPPlugin.h) target_include_directories(cmaj_clap INTERFACE $) target_compile_features(cmaj_clap INTERFACE cxx_std_17) target_link_libraries(cmaj_clap INTERFACE cmaj_plugin_helpers clap) ``` -------------------------------- ### Cmajor Patch Manifest Example Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Patch Format.md This JSON defines the properties of a Cmajor patch, including version, ID, name, and source file. ```json { "CmajorVersion": 1, "ID": "dev.cmajor.examples.helloworld", "version": "1.0", "name": "Hello World", "description": "The classic audio Hello World", "manufacturer": "Cmajor Software Ltd", "category": "generator", "isInstrument": false, "source": "HelloWorld.cmajor" } ``` -------------------------------- ### Define Cmajor Include Path Source: https://github.com/cmajor-lang/cmajor/blob/main/modules/plugin/include/common/CMakeLists.txt Ensures the CMAJ_INCLUDE_PATH environment variable is set to locate Cmajor headers. This is a critical setup step. ```cmake if(NOT CMAJ_INCLUDE_PATH) message (FATAL_ERROR "You must define the CMAJ_INCLUDE_PATH variable to point to your local Cmajor folder") endif() ``` -------------------------------- ### Dynamic Gain Executable Configuration Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/native_apps/CMakeLists.txt Defines the build for the 'DynamicGain' executable. It sets the project name, languages, C++ standard, compiler options, sources, and links necessary libraries. ```cmake project( DynamicGain VERSION 0.1 LANGUAGES CXX C) add_executable(DynamicGain) target_compile_features(DynamicGain PRIVATE cxx_std_17) target_compile_options(DynamicGain PRIVATE ${CMAJ_WARNING_FLAGS}) target_sources(DynamicGain PRIVATE DynamicGain/DynamicGain.cpp) target_link_libraries(DynamicGain PRIVATE examples_cmaj_lib ${CMAKE_DL_LIBS} $<$,$,9.0>>:stdc++fs> ) ``` -------------------------------- ### Processor and Namespace Aliases Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Provides syntax for creating aliases for parameterized processor and namespace names as a shortcut. ```cpp processor MyAlias1 = my_namespace::MyProcessor(float<2>, 1234), MyAlias2 = my_namespace::MyProcessor(float<3>, 5432); namespace n123 = some_namespace(float64)::other_namespace(1.0f); ``` -------------------------------- ### Project and Executable Definition Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/native_apps/CMakeLists.txt Defines the project name, version, languages, and creates an executable target. ```cmake project( RenderPatchSharedLib VERSION 0.1 LANGUAGES CXX C) add_executable(RenderPatchSharedLib) ``` -------------------------------- ### Type Casting in Cmaj Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Cmaj supports functional-style type casting. Examples show casting to integers, float vectors, and integer vectors. ```cpp let x = int (2.5); // x has value 2 (int32) let y = float<3> (int<3> (1, 2, 3)); // y is a float<3> vector 1.0f, 2.0f, 3.0f let z = int<3> (3); // z is (3, 3, 3) ``` -------------------------------- ### Get Filter Frequency by Name Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/Claude/FilterEQ/claudeSession.txt Retrieves the current frequency value for a given filter type. Defaults to 1000Hz if the filter type is not recognized. ```javascript getFilterFrequency(filterName) { switch (filterName) { case 'hp': return this.getCurrentParameterValue('hpFrequency'); case 'peak1': return this.getCurrentParameterValue('peak1Frequency'); case 'peak2': return this.getCurrentParameterValue('peak2Frequency'); case 'peak3': return this.getCurrentParameterValue('peak3Frequency'); case 'lp': return this.getCurrentParameterValue('lpFrequency'); default: return 1000; } } ``` -------------------------------- ### 32-bit Integer Literals in Cmaj Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Shows examples of 32-bit signed integer literals in Cmaj, including decimal, hexadecimal, and binary formats. No suffix is required. ```cpp -12345 // 32-bit signed decimal 0x12345 // 32-bit hex 0b101101 // 32-bit binary ``` -------------------------------- ### Declare Arrays of Different Types Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Demonstrates the syntax for declaring arrays of integers, 64-bit floats, and custom structs. ```cpp int[3] x; // an array of 3 integers float64[6] y; // an array of 6 64-bit floats MyStruct[4] z; // an array of 4 'MyStruct' objects ``` -------------------------------- ### Array Node and Endpoint Connections Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Illustrates valid and invalid connection scenarios involving array nodes and endpoints. It highlights restrictions on connecting arrays of arrays and demonstrates correct indexing for array elements. ```cpp graph ReturnsArray { output stream float32 out1[3]; output stream float32 out2; } graph Test { output stream float32 out; output stream float32 instanceOut[3]; output stream float32 arrayElement[10]; node n = ReturnsArray[10]; connection { n.out1 -> arrayElement; // invalid - the node is an array, and the endpoint is also an array type n.out1[1] -> arrayElement; // invalid - as above, n.out1 is an invalid type, so you can't take an index n[2].out1 -> instanceOut; // valid - n[2] selects a node, so the type is float32[3] n[2].out1[2] -> out; // valid - n[2] selects a node, out1[2] selects an array member, so type is float n.out2 -> arrayElement; // valid - type is float[10] n[1].out2 -> out; // valid - type is float } } ``` -------------------------------- ### Get Filter Gain by Name Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/Claude/FilterEQ/claudeSession.txt Retrieves the current gain value for a given filter type. Defaults to 0 if the filter type does not have adjustable gain. ```javascript getFilterGain(filterName) { switch (filterName) { case 'peak1': return this.getCurrentParameterValue('peak1Gain'); case 'peak2': return this.getCurrentParameterValue('peak2Gain'); case 'peak3': return this.getCurrentParameterValue('peak3Gain'); default: return 0; } } ``` -------------------------------- ### Loop Statement in Cmaj Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Provides examples of the `loop` statement in Cmaj for infinite loops and a fixed number of iterations. It's recommended for infinite loops over `while(true)`. ```cpp loop { advance(); } // infinite loop int i = 0; loop (5) console <- ++i; // prints 1, 2, 3, 4, 5 ``` -------------------------------- ### Cmaj Test File Structure Example Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Test File Format.md A typical Cmaj test file structure showing global JavaScript definitions and test blocks separated by '##' delimiters. ```javascript // All the text before the first delimiter line is parsed as javascript, and is available globally to all the tests. This is where you'd put any shared helper functions that your tests need to use. ## testFunction() ...The chunk of text in each section is provided to the test function that is called above... ## expectError ("...") ...Likewise, this chunk of text is passed to the "expectError" function... ``` -------------------------------- ### Load Cmajor Patch from URL (JavaScript) Source: https://github.com/cmajor-lang/cmajor/blob/main/tools/wasm_compiler/embedded-compiler-demo.html Loads and builds a Cmajor patch from a given URL. It initializes the AudioContext, creates a CmajorCompiler instance, and sets the manifest URL. ```javascript window.loadPatchFromURL = async function (url) { loadPatch ((compiler) => { const parts = url.split ("/"); const manifestPath = parts.pop(); const baseURL = new URL (parts.join ("/") + "/"); compiler.setManifestURL (baseURL, manifestPath); }); } ``` -------------------------------- ### Parameterized Namespace Aliasing Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Shows how to use namespace aliases to simplify repeated use of parameterized namespaces. ```cpp namespace ExampleNamespace (using Type, int value) { Type addValue (Type x) { return x + Type (value); } } void f() { // When using a parameterised namespace, it can be quite long-winded... let x1 = ExampleNamespace (int, 10)::addValue (100); // ...so you can use 'namespace' to declare a local alias: namespace N = ExampleNamespace (int, 10); let x2 = N::addValue (101); let x3 = N::addValue (102); } ``` -------------------------------- ### Basic Console Output Test Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Test File Format.md This snippet demonstrates a simple Cmajor processor that outputs 'hello world' to the console. It's used for basic verification of console output. ```Cmajor processor P { output stream int out; void main() { console <- "hello " <- "world"; out <- -1; advance(); } } ``` -------------------------------- ### Cmajor Graph Declaration Example Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Quick Start.md Defines a Cmajor graph named 'TwoGainsInSeries'. It specifies input and output streams and declares two 'GainProcessor' nodes, connecting them in series. ```cpp graph TwoGainsInSeries { input stream float in; output stream float out; node gain1 = GainProcessor; node gain2 = GainProcessor; connection in -> gain1 -> gain2 -> out; } ``` -------------------------------- ### Start Canvas Drag for Filter Handles Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/Claude/FilterEQ/claudeSession.txt Initiates the dragging of a filter handle on the canvas. It detects if a handle was clicked, sets the dragging state, and records initial drag parameters. ```javascript startCanvasDrag(event) { const rect = this.canvas.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; // Find if we clicked on a handle const clickedHandle = this.findHandleAtPosition(x, y); if (clickedHandle) { event.preventDefault(); this.isDragging = true; this.dragHandle = clickedHandle; this.dragStartX = event.clientX; this.dragStartY = event.clientY; this.dragStartFrequency = this.getFilterFrequency(clickedHandle); this.dragStartGain = this.getFilterGain(clickedHandle); document.body.style.cursor = 'move'; } } ``` -------------------------------- ### Configure and Build on Linux with CMake and Ninja Source: https://github.com/cmajor-lang/cmajor/blob/main/README.md Configure the Cmajor build for Linux using CMake with the Ninja generator, disabling plugin building and setting the build type to Release. Then, navigate to the build directory and execute ninja to build the project. ```bash cmake -Bbuild -GNinja -DBUILD_PLUGIN=OFF -DCMAKE_BUILD_TYPE=Release . cd build ninja ``` -------------------------------- ### Cmaj Struct Initialization Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Illustrates different ways to create and initialize struct objects, including zero-initialization, explicit member assignment, parenthesized lists, and implicit conversion from lists. ```cpp struct Position { float x, y; } Position getMovedPosition (Position p) { Position newPos; newPos.x = p.x + 10.0f; newPos.y = p.y - 5.0f; return newPos; } ``` ```cpp struct Position { float x, y; } Position getMovedPosition (Position p) { let newPos = Position (p.x + 10.0f, p.y - 5.0f); return newPos; } ``` ```cpp struct Position { float x, y; } Position getMovedPosition (Position p) { return (p.x + 10.0f, p.y - 5.0f); } ``` -------------------------------- ### Generic function with static_assert Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Illustrates using a static_assert within a generic function to enforce type constraints at compile time. This example ensures the input is an array before accessing its first element. ```cpp Type.elementType getFirstElement (Type array) { static_assert (Type.isArray, "The argument supplied to this function must be an array!"); return array[0]; } ``` -------------------------------- ### Implement Auto-Scaling GUI with getScaleFactorLimits Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Patch Format.md To enable automatic GUI scaling when the patch window is resized, include a `getScaleFactorLimits()` method in your web component. This method should return an object specifying the minimum and maximum scale factors for your GUI. ```javascript class MyAmazingPatchView extends HTMLElement { // constructor and other methods... getScaleFactorLimits() { return { minScale: 0.5, maxScale: 1.25 }; } } ``` -------------------------------- ### Configure Build for Windows with CMake Source: https://github.com/cmajor-lang/cmajor/blob/main/README.md Use this command to configure the Cmajor build system for Windows using CMake and generate a Visual Studio project. Specify -DBUILD_PLUGIN=OFF to disable plugin building on Windows/arm64. ```bash cmake -Bbuild -G"Visual Studio 16 2019" . ``` -------------------------------- ### Update Canvas Setup in connectedCallback Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/Claude/FilterEQ/claudeSession.txt Initializes the canvas drawing context within the connectedCallback method to ensure the element is part of the DOM before accessing its dimensions. This resolves issues where getBoundingClientRect() returned zero. ```javascript connectedCallback() { // Called when the element is added to the DOM // Now we can set up the canvas since the element is in the DOM this.setupCanvas(); if (this.patchConnection) { this.setupCmajorConnection(); } ``` -------------------------------- ### Compile Features and Options Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/native_apps/CMakeLists.txt Sets the C++ standard to C++17 and applies common warning flags. ```cmake target_compile_features(RenderPatchSharedLib PRIVATE cxx_std_17) target_compile_options(RenderPatchSharedLib PRIVATE ${CMAJ_WARNING_FLAGS}) ``` -------------------------------- ### Cmajor Processor Declaration Example Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Quick Start.md Defines a Cmajor processor named 'GainProcessor'. It includes an input and output stream of floats and a 'main' function with an infinite loop that processes the input by multiplying it by 0.5 and sending it to the output. ```cpp processor GainProcessor { input stream float in; output stream float out; void main() { loop { out <- in * 0.5f; advance(); } } } ``` -------------------------------- ### Floating-point Literals in Cmaj Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Provides examples of 64-bit and 32-bit floating-point literals in Cmaj, using suffixes like f64, _f64, f, f32, or _f32. Floating-point literals must contain a decimal point. ```cpp 1234.0 // 64-bit float 1234.0_f64 // 64-bit float 1234.0f // 32-bit float 1234.0_f32 // 32-bit float ``` -------------------------------- ### Filesystem Access with File Class Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Script File Format.md The File class provides methods for interacting with the filesystem, including checking existence, reading/writing content, and finding child files or folders. ```javascript class File { constructor (path) // Creates a file from a path string path // A property containing the file path as a string exists() // True if the file exists isFolder() // True if the file is a folder getModificationTime() // Get the last modification time of the file parent() // Returns a new File object representing the parent folder getChild (relativePath) // Returns a new File object by appenting this relative path getSibling (relativePath) // Returns a new File object for a sibling file with the given path // Reads the content of the file and returns it as a string (if it's valid UTF8) or // an array of bytes if not. Returns an error object on failure. read() // reads an audio file and returns it as an object containing // fields for rate, length, and channel data as arrays of floats readAudioData (annotations) // attempts to overwrite this file with the given string or array of bytes, // returning an error on failure overwrite (newContent) // Scans this folder for children and returns the list as an array of File objects. // If shouldFindFolders is true, it only looks for folders, if false, only looks // for files. If recursive is true, it's recursive. The wildcard parameter is an // optional simple wildcard expression to use. findChildren (shouldFindFolders, recursive, wildcard) } ``` -------------------------------- ### Handle Zero Dimensions in setupCanvas Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/patches/Claude/FilterEQ/claudeSession.txt Modifies the setupCanvas method to handle cases where the canvas might not have dimensions yet. It uses fallback dimensions if rect.width or rect.height are zero, and ensures the canvas and its styles are updated correctly. ```javascript setupCanvas() { if (!this.canvas) return; const rect = this.canvas.getBoundingClientRect(); const dpr = window.devicePixelRatio || 1; // If canvas has no dimensions, use fallback dimensions const width = rect.width > 0 ? rect.width : 740; const height = rect.height > 0 ? rect.height : 350; this.canvas.width = width * dpr; this.canvas.height = height * dpr; this.ctx.scale(dpr, dpr); this.canvas.style.width = width + 'px'; this.canvas.style.height = height + 'px'; this.drawFrequencyResponse(); } ``` -------------------------------- ### Diode Clipper Executable Configuration Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/native_apps/CMakeLists.txt Defines the build for the 'DiodeClipper' executable. It sets the project name, languages, C++ standard, compiler options, sources, and links necessary libraries. ```cmake project( DiodeClipper VERSION 0.1 LANGUAGES CXX C ) add_executable(DiodeClipper) target_compile_features(DiodeClipper PRIVATE cxx_std_17) target_compile_options(DiodeClipper PRIVATE ${CMAJ_WARNING_FLAGS}) target_sources(DiodeClipper PRIVATE DiodeClipper/DiodeClipper.cpp) target_link_libraries(DiodeClipper PRIVATE examples_cmaj_lib ${CMAKE_DL_LIBS} $<$,$,9.0>>:stdc++fs> ) ``` -------------------------------- ### Configure Include Directories Source: https://github.com/cmajor-lang/cmajor/blob/main/modules/CMakeLists.txt Configures include directories for the Cmajor library. Public includes point to the main include directory, while private includes point to third-party and LLVM directories. System includes are set for Boost libraries. ```cmake target_include_directories (${CMAJ_LIBRARY_NAME} PUBLIC ${CMAJ_MODULE_DIR}/../include ) target_include_directories (${CMAJ_LIBRARY_NAME} PRIVATE ${CMAJ_MODULE_DIR}/../3rdParty ${LLVM_PATH_ROOT}/include ) target_include_directories(${CMAJ_LIBRARY_NAME} SYSTEM PRIVATE ${CMAJ_MODULE_DIR}/../3rdParty/boost/align/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/asio/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/assert/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/beast/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/bind/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/config/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/core/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/date_time/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/endian/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/intrusive/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/is_placeholder/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/io/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/logic/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/optional/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/static_assert/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/smart_ptr/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/system/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/move/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/mp11/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/mpl/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/numeric_conversion/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/preprocessor/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/predef/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/regex/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/throw_exception/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/type_traits/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/utility/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/winapi/include/ ${CMAJ_MODULE_DIR}/../3rdParty/boost/static_string/include/ ) ``` -------------------------------- ### Build Static Cmajor Library Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/native_apps/CMakeLists.txt Configures the build for a static Cmajor library, enabling playback and the LLVM performer. ```cmake MAKE_CMAJ_LIBRARY ( LIBRARY_NAME examples_cmaj_lib INCLUDE_PLAYBACK ENABLE_PERFORMER_LLVM ) ``` -------------------------------- ### Asset Handling Methods Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Patch Format.md Methods for handling assets within a patch bundle, specifically for retrieving resource addresses. ```APIDOC ## Asset handling methods ### `getResourceAddress (path)` This takes a relative path to an asset within the patch bundle, and converts it to a path relative to the root of the browser that is showing the view. You need to use this in your view code to translate your asset URLs to a form that can be safely used in your view's HTML DOM (e.g. in its CSS). This is needed because the host's HTTP server (which is delivering your view pages) may have a different '/' root than the root of your patch (e.g. if a single server is serving multiple patch GUIs). ``` -------------------------------- ### Resizable and Auto-Scaling GUI Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Patch Format.md Controls for making a patch's GUI resizable and auto-scaling. ```APIDOC ## Resizable and Auto-Scaling GUI The `.cmajorpatch` file's `view.resizable` property controls whether the patch window can be resized. If you want your GUI to automatically scale when the window is resized, your web component should include a `getScaleFactorLimits()` method. This method should return an object specifying the minimum and maximum scale factors for your GUI. ```js class MyAmazingPatchView extends HTMLElement { // constructor and other methods... getScaleFactorLimits() { return { minScale: 0.5, maxScale: 1.25 }; } } ``` ``` -------------------------------- ### Chaining Node Connections Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Demonstrates chaining connections between node endpoints and graph-level endpoints. Endpoint names can be omitted for nodes with single inputs/outputs. ```cpp // Node endpoints use the syntax . connection node1.output1 -> node3.input2; // The graph's top-level endpoints are referred to by using their name on its own connection node3.output7 -> output3; // For nodes that only have a single input or output, the endpoint name can // be omitted, and you can write chains of connections as a single statement: connection node1.output1 -> node2 -> node3 -> output3; // You can use a comma-separated list to send an output to multiple destinations: connection node.output1 -> node2.in1, node3.in3; // As for nodes and endpoints, you can also use a braced block to declare the connections: connection { node3.output7 -> output3; node1.output1 -> node2 -> node3 -> output3; } ``` -------------------------------- ### Default Parameter Values Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Demonstrates how to provide default values for trailing parameters in graph declarations. ```cpp graph G (int v = 100, processor P = MyProcessor) { ``` -------------------------------- ### Configure Scripting Support Source: https://github.com/cmajor-lang/cmajor/blob/main/modules/CMakeLists.txt Conditionally enables scripting support for Linux systems by finding and linking against GTK3, WebKit2, and JACK libraries. Includes system include directories for these packages. ```cmake if (CMAJ_INCLUDE_SCRIPTING) if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") find_package(PkgConfig REQUIRED) pkg_check_modules (GTK3 REQUIRED gtk+-3.0 IMPORTED_TARGET) pkg_check_modules (WEBKIT2 REQUIRED ${WEBKIT2_GTK_VERSION} IMPORTED_TARGET) pkg_check_modules (JACK REQUIRED jack IMPORTED_TARGET) target_link_libraries (${CMAJ_LIBRARY_NAME} PUBLIC ${GTK3_LIBRARIES} ${WEBKIT2_LIBRARIES}) target_include_directories(${CMAJ_LIBRARY_NAME} SYSTEM PUBLIC ${GTK3_INCLUDE_DIRS} ${WEBKIT2_INCLUDE_DIRS}) endif() endif() ``` -------------------------------- ### Run Performance Tests with Single Thread Source: https://github.com/cmajor-lang/cmajor/blob/main/tests/Tests README.md Use the --singleThread option when running performance tests for more consistent results across different platforms and builds. ```bash --singleThread ``` -------------------------------- ### Processor Specialization Parameters Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Define processors with parameters for custom types and constant values. These parameters must be provided when instantiating the processor. ```cpp // When anything tries to create an instant of this processor, the type MySampleType // and the integer myConstant must be provided. processor MyProcessor (using MySampleType, int myConstant) { output stream MySampleType out; void main() { MySampleType x[myConstant]; out <- MySampleType (myConstant + 10); advance(); } } graph G { // when instantiating a processor that takes parameters, you put the values // in parentheses after the name. In this example, the compiler will create // two different versions of MyProcessor with these two sets of parameters. node p1 = MyProcessor (float, 100), p2 = MyProcessor (float64<2>, 200); } ``` -------------------------------- ### Expose Multiple Child Endpoints with Wildcard Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Use a wildcard pattern with hoisted endpoints to expose multiple child node outputs that match the pattern. ```cpp graph Parent { output child.out*; // expose all of this node's outputs that begin with the characters "out" node child = MyChildProcessor; } ``` -------------------------------- ### Configure Build for MacOS with CMake Source: https://github.com/cmajor-lang/cmajor/blob/main/README.md Use this command to configure the Cmajor build system for MacOS using CMake and generate an Xcode project. ```bash cmake -Bbuild -GXcode . ``` -------------------------------- ### Cmajor Voice Allocation with Array Connections Source: https://github.com/cmajor-lang/cmajor/blob/main/CLAUDE.md Demonstrates connecting a VoiceAllocator to an array of voice processors. Ensure correct syntax for connections. ```cmajor node voices = MyVoice[8]; node voiceAllocator = std::voices::VoiceAllocator(8); connection { voiceAllocator.voiceEventOut -> voices.eventIn; voices -> audioOut; } ``` -------------------------------- ### Expose Child Node Endpoints Using Hoisted Syntax Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Language Guide.md Shorten the process of exposing child node outputs by using the hoisted endpoint syntax directly in the parent graph. ```cpp graph Parent { output child.out1, child.out2; node child = MyChildProcessor; } ``` -------------------------------- ### Cmajor Hello World Patch Source: https://github.com/cmajor-lang/cmajor/blob/main/tools/wasm_compiler/embedded-compiler-demo.html A basic Cmajor patch demonstrating a simple audio generator that plays a melody. It defines a Note struct and a main function to play a sequence of notes. ```cmajor processor HelloWorld { output stream float out; // This simple struct holds a note + duration for our melody struct Note { int pitch, length; void play() const { let numFrames = this.length * framesPerQuarterNote; let frequency = std::notes::noteToFrequency (this.pitch); let phaseDelta = float (frequency * processor.period * twoPi); loop (numFrames) { out <- volume * sin (phase); phase = addModulo2Pi (phase, phaseDelta); advance(); } } } // This is our processor's entry-point function, which is invoked // by the system void main() { let melody = Note[] ( (79, 1), (77, 1), (69, 2), (71, 2), (76, 1), (74, 1), (65, 2), (67, 2), (74, 1), (72, 1), (64, 2), (67, 2), (72, 4) ); for (wrap i) melody[i].play(); } // We'll define a couple of constants here to set the volume and tempo let volume = 0.15f; let framesPerQuarterNote = int (processor.frequency / 7); float phase; } ``` -------------------------------- ### Cmajor Help Command Source: https://github.com/cmajor-lang/cmajor/blob/main/tests/Tests README.md Display available command-line options for the Cmajor compiler, including test-related flags. ```bash cmaj --help ``` -------------------------------- ### RenderPatch CMake Configuration Source: https://github.com/cmajor-lang/cmajor/blob/main/examples/native_apps/CMakeLists.txt Configures a C++ executable named RenderPatch with C++17 support. Includes platform-specific library linking for Linux (GTK3, WebKitGTK) and macOS (WebKit, Accelerate, CoreAudio, etc.). ```cmake project( RenderPatch VERSION 0.1 LANGUAGES CXX C) add_executable(RenderPatch) target_compile_features(RenderPatch PRIVATE cxx_std_17) target_compile_options(RenderPatch PRIVATE ${CMAJ_WARNING_FLAGS}) if (${CMAKE_SYSTEM_NAME} MATCHES "Linux") find_package(PkgConfig REQUIRED) pkg_check_modules (GTK3 REQUIRED gtk+-3.0 IMPORTED_TARGET) pkg_check_modules (WEBKIT2 REQUIRED ${WEBKIT2_GTK_VERSION} IMPORTED_TARGET) target_include_directories (RenderPatch PUBLIC ${GTK3_INCLUDE_DIRS} ${WEBKIT2_INCLUDE_DIRS}) target_link_libraries (RenderPatch PUBLIC ${GTK3_LIBRARIES} ${WEBKIT2_LIBRARIES}) if (${CMAKE_SYSTEM_PROCESSOR} MATCHES "armv7l") target_link_libraries (RenderPatch PUBLIC atomic) endif() set (EXTRA_LIBS dl ${GTK3_LIBRARIES} ${WEBKIT2_LIBRARIES} "-pthread" "-lasound") endif() if (${CMAKE_SYSTEM_NAME} MATCHES "Darwin") target_link_libraries(RenderPatch PRIVATE "-framework WebKit") target_link_libraries(RenderPatch PRIVATE "-framework Accelerate") target_link_libraries(RenderPatch PRIVATE "-framework CoreAudio") target_link_libraries(RenderPatch PRIVATE "-framework CoreMIDI") target_link_libraries(RenderPatch PRIVATE "-framework AudioToolbox") target_link_libraries(RenderPatch PRIVATE "-framework Foundation") target_link_libraries(RenderPatch PRIVATE "-framework IOKit") target_link_libraries(RenderPatch PRIVATE "-framework Cocoa") endif() target_sources(RenderPatch PRIVATE RenderPatch/Main.cpp) target_link_libraries(RenderPatch PRIVATE examples_cmaj_lib ${CMAKE_DL_LIBS} $<$,$,9.0>>:stdc++fs> ${EXTRA_LIBS} ) ``` -------------------------------- ### Play a Cmajor patch using the console app Source: https://github.com/cmajor-lang/cmajor/blob/main/docs/Cmaj Quick Start.md Use the `cmaj play` command to open and run a Cmajor patch, displaying its GUI and handling audio/MIDI input. ```shell $ cmaj play /path-to-your-repo/examples/patches/HelloWorld/HelloWorld.cmajorpatch ``` -------------------------------- ### Configure Windows Build with CMake Source: https://github.com/cmajor-lang/cmajor/blob/main/CLAUDE.md Configure the Cmajor build for Windows using CMake and the Visual Studio 2019 generator. Note that -DBUILD_PLUGIN=OFF is recommended for Windows/arm64, and only Release and RelWithDebugInfo builds are supported due to LLVM runtime requirements. ```bash cmake -Bbuild -G"Visual Studio 16 2019" . # Use -DBUILD_PLUGIN=OFF for Windows/arm64 # Only Release and RelWithDebugInfo builds supported due to LLVM runtime requirements ```