/[svn]/doc/docbase/instrument_scripts/nksp/01_nksp.html
ViewVC logotype

Contents of /doc/docbase/instrument_scripts/nksp/01_nksp.html

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3702 - (show annotations) (download) (as text)
Mon Jan 6 15:55:17 2020 UTC (9 months, 2 weeks ago) by schoenebeck
File MIME type: text/html
File size: 66695 byte(s)
* NKSP language tour: minor corrections (typos and grammar).

1 <html>
2 <head>
3 <meta name="author" content="Christian Schoenebeck">
4 <title>NKSP Language</title>
5 <meta name="description" content="Introduction to the NKSP real-time instrument script language.">
6 </head>
7 <body>
8 <p>
9 This document intends to give you a compact introduction and overview to
10 the NKSP real-time instrument script language, so you can start writing
11 your own instrument scripts in short time. It concentrates on describing
12 the script language. If you rather want to learn how to modify and
13 attach scripts to your sounds, then please refer to the gigedit manual for
14 <a href="gigedit_scripts.html">how to manage instrument scripts with gigedit</a>
15 for Gigasampler/GigaStudio format sounds, or refer to the SFZ opcode
16 <code lang="sfz">script</code> for attaching NKSP scripts with
17 SFZ format sounds.
18 </p>
19
20 <h3>At a Glance</h3>
21 <p>
22 <img src="nksp_file.png" style="height:111px; margin-right:12px;">
23 NKSP stands for "is <b>N</b>ot <b>KSP</b>", which denotes its distinction
24 to an existing proprietary language called <i>KSP</i>.
25 NSKP is a script language specifically designed to write real-time capable
26 software extensions to LinuxSampler's sampler engines that can be bundled
27 individually with sounds by sound designers themselves.
28
29 Instead of defining a completely new script language, NKSP is leaned on
30 that mentioned properiatary script language. The biggest advantage is that
31 sound designers and musicians can leverage the huge amount of existing KSP
32 scripts which are already available for various purposes on the Internet,
33 instead of being forced to write all scripts from scratch in a completely
34 different language.
35 </p>
36 <p>
37 That also means however that there are some differences between those two
38 languages. Some extensions have been added to the NKSP core language to
39 make it a bit more convenient and less error prone to write scripts, and
40 various new functions had to be added due to the large difference of the
41 sampler engines and their underlying sampler format. Efforts have been
42 made though to make NKSP as much compatible to KSP as possible.
43 The NKSP documentation will emphasize individual differences in
44 the two languages and function implementations wherever they may occur, to
45 give you immediate hints where you need to take care of regarding
46 compatibility issues when writing scripts that should be spawned on both
47 platforms.
48 </p>
49 <p>
50 Please note that the current focus of NKSP is the sound controlling aspect
51 of sounds. At this point there is no support for the graphical user
52 interface function set of KSP in NKSP.
53 </p>
54
55 <h2>Event Handlers</h2>
56 <p>
57 NKSP is an event-driven language. That means you are writing so called
58 <i>event handlers</i> which define what the sampler shall do on individual
59 events that occur, while using the sound the script was bundled with.
60 An event handler in general looks like this:
61 </p>
62 <code lang="nksp">
63 on ??event-name??
64
65 ??statements??
66
67 end on
68 </code>
69 <p>
70 There are currently six events available:
71 </p>
72 <table>
73 <tr>
74 <th>Event Type</th> <th>Description</th>
75 </tr>
76 <tr>
77 <td><code>on note</code></td> <td>This event handler is executed when a new note was triggered, i.e. when hitting a key on a MIDI keyboard.</td>
78 </tr>
79 <tr>
80 <td><code>on release</code></td> <td>This event handler is executed when a note was released, i.e. when releasing a key on a MIDI keyboard.</td>
81 </tr>
82 <tr>
83 <td><code>on controller</code></td> <td>This event handler is executed when a MIDI control change event occurred. For instance when turning the modulation wheel at a MIDI keyboard.</td>
84 </tr>
85 <tr>
86 <td><code>on rpn</code></td> <td>This event handler is executed when a MIDI <i>RPN</i> event occurred.</td>
87 </tr>
88 <tr>
89 <td><code>on nrpn</code></td> <td>This event handler is executed when a MIDI <i>NRPN</i> event occurred.</td>
90 </tr>
91 <tr>
92 <td><code>on init</code></td> <td>Executed only once, as very first event handler, right after the script had been loaded. This code block is usually used to initialize variables in your script with some initial, useful data.</td>
93 </tr>
94 </table>
95 <p>
96 You are free to decide for which ones of those event types you are going to
97 write an event handler for. You can write an event handler for only one
98 event type or write event handlers for all of those event types. Also
99 dependent on the respective event type, there are certain things you can
100 do and things which you can't do. But more on that later.
101 </p>
102
103 <h3>Note Events</h3>
104 <p>
105 As a first example, the following tiny script will print a message to your
106 terminal whenever you trigger a new note with your MIDI keyboard.
107 </p>
108 <code>
109 on note
110 message("A new note was triggered!")
111 end on
112 </code>
113 <p>
114 Probably you are also interested to see which note you triggered exactly.
115 The sampler provides you a so called
116 <i title="A script variable which is provided by the sampler and which has a very specific purpose which you cannot override for other purposes.">
117 built-in variable
118 </i>
119 called <code>$EVENT_NOTE</code> which reflects the note number
120 (as value between 0 and 127) of the note that has just been triggered. Additionally
121 the built-in variable <code>$EVENT_VELOCITY</code> provides you the
122 velocity value (also between 0 and 127) of the note event.
123 </p>
124 <code>
125 on note
126 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
127 end on
128 </code>
129 <p>
130 The <code>&</code> character concatenates text strings with each other.
131 In this case it is also automatically converting the note number into a
132 text string.
133 </p>
134 <note class="important">
135 The message() function is not appropriate for being used with your final
136 production sounds, since it can lead to audio dropouts.
137 You should only use the message() function to try out things, and to spot
138 and debug problems with your scripts.
139 </note>
140
141 <h3>Release Events</h3>
142 <p>
143 As counter part to the <code>note</code> event handler, there is also the
144 <code>release</code> event handler, which is executed when a note was
145 released. This event handler can be used similarly:
146 </p>
147 <code>
148 on release
149 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
150 end on
151 </code>
152 <p>
153 Please note that you can hardly find MIDI keyboards which support release
154 velocity. So with most keyboards this value will be 127.
155 </p>
156
157 <h3>Controller Events</h3>
158 <p>
159 Now let's extend the first script to not only show note-on and note-off
160 events, but also to show a message whenever
161 you use a MIDI controller (i.e. modulation wheel, sustain pedal, etc.).
162 </p>
163 <code>
164 on note
165 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
166 end on
167
168 on release
169 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
170 end on
171
172 on controller
173 message("MIDI Controller " & $CC_NUM " changed its value to " & %CC[$CC_NUM])
174 end on
175 </code>
176 <p>
177 It looks very similar to the note event handlers. <code>$CC_NUM</code>
178 reflects the MIDI controller number of the MIDI controller that had been
179 changed and <code>%CC</code> is a so called <i>array variable</i>, which not only
180 contains a single number value, but instead it contains several values at
181 the same time. The built-in <code>%CC</code> array variable contains the current
182 controller values of all 127 MIDI controllers. So <code>%CC[1]</code> for
183 example would give you the current controller value of the modulation
184 wheel, and therefore <code>%CC[$CC_NUM]</code> reflects the new controller
185 value of the controller that just had been changed.
186 </p>
187 <p>
188 There is some special aspect you need to be aware about: in contrast to the MIDI standard,
189 monophonic aftertouch (a.k.a. channel pressure) and pitch bend wheel are
190 handled by NKSP as if they were regular MIDI controllers. So a value change
191 of one of those two triggers a regular <code>controller</code> event handler
192 to be executed. To obtain the current aftertouch value you can use
193 <code>%CC[$VCC_MONO_AT]</code>, and to get the current pitch bend wheel
194 value use <code>%CC[$VCC_PITCH_BEND]</code>.
195 </p>
196
197 <h3>RPN / NRPN Events</h3>
198 <p>
199 There are also dedicated event handlers for
200 MIDI <i title="Registered Parameter Number">RPN</i> and
201 <i title="Non-Registered Parameter Number">NRPN</i>
202 events:
203 </p>
204 <code>
205 on rpn
206 message("RPN address msb=" & msb($RPN_ADDRESS) & ",lsb=" & lsb($RPN_ADDRESS) &
207 "-> value msb=" & msb($RPN_VALUE) & ",lsb=" & lsb($RPN_VALUE))
208 if ($RPN_ADDRESS = 2)
209 message("Standard Coarse Tuning RPN received")
210 end if
211 end on
212
213 on nrpn
214 message("NRPN address msb=" & msb($RPN_ADDRESS) & ",lsb=" & lsb($RPN_ADDRESS) &
215 "-> value msb=" & msb($RPN_VALUE) & ",lsb=" & lsb($RPN_VALUE))
216 end on
217 </code>
218 <p>
219 Since MIDI RPN and NRPN events are actually MIDI controller events,
220 you might as well handle these with the previous
221 <code>controller</code> event handler. But since RPN and NRPN messages
222 are not just one MIDI message, but rather always handled by a set of
223 individual MIDI messages, and since the
224 precise set and sequence of actual MIDI commands sent varies between
225 vendors and even among individual of their products, it highly makes sense to
226 use these two specialized event handlers for these instead, because the
227 sampler will already relief you from that burden to deal with all those
228 low-level MIDI event processing issues and all their wrinkles involved
229 when handling RPNs and NRPNs.
230 </p>
231 <note>
232 Even though there are two separate, dedicated event handlers for RPN and NRPN events,
233 they both share the same built-in variable names as you can see in the
234 example above.
235 </note>
236 <p>
237 So by reading <code>$RPN_ADDRESS</code> you get the RPN / NRPN parameter
238 number that had been changed, and <code>$RPN_VALUE</code> represents the
239 new value of that RPN / NRPN parameter. Note that these two built-in
240 variables are a 14-bit representation of the parameter number and new
241 value. So their possible value range is <code>0 .. 16383</code>. If you
242 rather want to use their (in MIDI world) more common separated two 7 bit
243 values instead, then you can easily do that by wrapping them into either
244 <code>msb()</code> or <code>lsb()</code> calls like also demonstrated above.
245 </p>
246
247 <h3>Script Load Event</h3>
248 <p>
249 As the last one of the six event types available with NKSP, the following
250 is an example of an <code>init</code> event handler.
251 </p>
252 <code>
253 on init
254 message("This script has been loaded and is ready now!")
255 end on
256 </code>
257 <p>
258 You might think, that this is probably a very exotic event. Because in
259 fact, this "event" is only executed once for your script: exactly when
260 the script was loaded by the sampler. This is not an unimportant event
261 handler though. Because it is used to prepare your script for various
262 purposes. We will get more about that later.
263 </p>
264
265 <h2>Comments</h2>
266 <p>
267 Let's face it: software code is sometimes hard to read, especially when you
268 are not a professional software developer who deals with such kinds of
269 things every day. To make it more easy for you to understand, what you
270 had in mind when you wrote a certain script three years ago, and also if
271 some other developer might need to continue working on your scripts one
272 day, you should place as many comments into your scripts as possible. A
273 comment in NKSP is everything that is nested into an opening and closing
274 pair of curly braces.
275 </p>
276 <code>{ This is a comment. }</code>
277 <p>
278 You cannot only use this to leave some human readable explanations here
279 and there, you might also use such curly braces to quickly disable parts
280 of your scripts for a moment, i.e. when debugging certain things.
281 </p>
282 <code>
283 on init
284 { The following will be prompted to the terminal when the sampler loaded this script. }
285 message("My script loaded.")
286
287 { This code block is commented out, so these two messages will not be displayed }
288 {
289 message("Another text")
290 message("And another one")
291 }
292 end on
293 </code>
294
295 <h2>Variables</h2>
296 <p>
297 In order to be able to write more complex and more useful scripts, you
298 also need to remember some data somewhere for being able to use that
299 data at a later point. This can be done by using
300 <i title="A variable is a storage location paired with an associated symbolic name.">
301 variables
302 </i>.
303 We already came across some <i>built-in variables</i>, which are already
304 defined by the sampler for you. To store your own data you need to declare
305 your own <i>user variables</i>, which has the following form:
306 </p>
307 <p>
308 <code>declare $??variable-name?? := ??initial-value??
309 </p>
310 <p>
311 The left hand side's <code>??variable-name??</code> is an arbitrary name
312 you can chose for your variable. That name might consist of English
313 letters A to Z (lower and upper case), digits (<code>0</code> to <code>9</code>),
314 and the underscore character "<code>_</code>".
315 Variable names must be unique. So you can neither declare several variables
316 with the same name, nor can you use a name for your variable that is
317 already been reserved by <i>built-in variables</i>.
318 The right hand side's <code>??initial-value??</code> is simply the first
319 value the variable should store right after it was created. You can also
320 omit that.
321 </p>
322 <p>
323 <code>declare $??variable-name??
324 </p>
325 <p>
326 In that case the sampler will automatically assign <code>0</code> for you
327 as the variable's initial value. This way we could for example count the
328 total amount of notes triggered.
329 </p>
330 <code>
331 on init
332 declare $numberOfNotes := 0
333 end on
334
335 on note
336 $numberOfNotes := $numberOfNotes + 1
337
338 message("This is the " & $numberOfNotes & "th note triggered so far.")
339 end on
340 </code>
341 <p>
342 In the <code>init</code> event handler we create our own variable
343 <code>$numberOfNotes</code> and assign <code>0</code> to it as its
344 initial value. Like mentioned before, that initial assignment is optional.
345 In the <code>note</code> event handler we then increase the
346 <code>$numberOfNotes</code> variable by one, each time a new note was
347 triggered and then print a message to the terminal with the current total
348 amount of notes that have been triggered so far.
349 </p>
350 <note>
351 NKSP allows you to declare variables in all event handlers, however if
352 you want to keep compatibility with KSP, then you should only
353 declare variables in <code>init</code> event handlers.
354 </note>
355
356 <h3>Variable Types</h3>
357 <p>
358 There are currently three different variable types, which you can easily
359 recognize upon their first character.
360 </p>
361 <table>
362 <tr>
363 <th>Variable Form</th> <th>Data Type</th> <th>Description</th>
364 </tr>
365 <tr>
366 <td><code>$??variable-name??</code></td> <td>Integer Scalar</td> <td>Stores one single integer number value.</td>
367 </tr>
368 <tr>
369 <td><code>%??variable-name??</code></td> <td>Integer Array</td> <td>Stores a certain amount of integer number values.</td>
370 </tr>
371 <tr>
372 <td><code>@??variable-name??</code></td> <td>String</td> <td>Stores one text string.</td>
373 </tr>
374 </table>
375 <p>
376 So the first character just before the actual variable name, always
377 denotes the data type of the variable. Also note that all variable types
378 share the same variable name space. That means you cannot declare a
379 variable with a name that has already been used to declare a variable of
380 another variable type.
381 </p>
382
383 <h3>Array Variables</h3>
384 <p>
385 We already used the first two variable types. However we have not seen yet
386 how to declare such array variables. This is the common declaration form
387 for creating your own array variables.
388 </p>
389 <code>
390 on init
391 declare %??variable-name??[??array-size??] := ( ??list-of-values?? )
392 end on
393 </code>
394 <p>
395 So let's say you wanted to create an array variable with the first 12
396 prime numbers, then it might look like this.
397 </p>
398 <code>
399 on init
400 declare %primes[12] := ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 )
401 end on
402 </code>
403 <p>
404 Like with integer variables, assigning some initial values with
405 <code>??list-of-values??</code> is optional. The array
406 declaration form without initial value assignment looks like this.
407 </p>
408 <code>
409 on init
410 declare %??variable-name??[??array-size??]
411 end on
412 </code>
413 <p>
414 When you omit that initial assignment, then all numbers of that array will
415 automatically be initialized with <code>0</code> each. With array
416 variables however, it is always mandatory to provide
417 <code>??array-size??</code> with an array
418 variable declaration, so the sampler can create that array with the
419 requested amount of values when the script is loaded. In contrast to many
420 other programming languages, changing that amount of values of an array
421 variable is not possible after the variable had been declared. That's due
422 to the fact that this language is dedicated to real-time applications, and
423 changing the size of an array variable at runtime would harm real-time
424 stability of the sampler and thus could lead to audio dropouts. So NKSP
425 does not allow you to do that.
426 </p>
427
428
429 <h3>String Variables</h3>
430 <p>
431 You might also store text with variables. These are called <i>text string
432 variables</i>, or short: <i>string variables</i>. Let's skip the common declaration
433 form of string variables and let us modify a prior example to just use
434 such kind of variable.
435 </p>
436 <code>
437 on init
438 declare $numberOfNotes
439 declare @firstText := "This is the "
440 declare @secondText
441 end on
442
443 on note
444 $numberOfNotes := $numberOfNotes + 1
445 @secondText := "th note triggered so far."
446 message(@firstText & $numberOfNotes & @secondText)
447 end on
448 </code>
449 <p>
450 It behaves exactly like the prior example and shall just give you a
451 first idea how to declare and use string variables.
452 </p>
453 <note class="important">
454 Like with the message() function, you should not use string variables
455 with your final production sounds, since it can lead to audio dropouts.
456 You should only use string variables to try out things, and to spot
457 and debug problems with your scripts.
458 </note>
459
460 <h3>Variable Scope</h3>
461 <p>
462 By default, all variables you declare with NKSP are
463 <i title="A variable that is accessible throughout an entire script.">
464 global variables
465 </i>. That means every event handler can access the data of such a global
466 variable. Furthermore, each instance of an event handler accesses the same
467 data when it is referencing that variable. And the latter fact can be a
468 problem sometimes, which we will outline next.
469 </p>
470 <p>
471 Let's assume you wanted to write an instrument script that shall resemble
472 a simple delay effect. You could do that by writing a note event handler
473 that automatically triggers several new notes for each note being
474 triggered on a MIDI keyboard. The following example demonstrates how that
475 could be achieved.
476 </p>
477 <code>
478 on init
479 { The amount of notes to play }
480 declare const $delayNotes := 4
481 { Tempo with which the new notes will follow the orignal note }
482 declare const $bpm := 90
483 { Convert BPM to microseconds (duration between the notes) }
484 declare const $delayMicroSeconds := 60 * 1000000 / $bpm
485 { Just a working variable for being used with the while loop below }
486 declare $i
487 { For each successive note we trigger, we will reduce the velocity a bit}
488 declare $velocity
489 end on
490
491 on note
492 { First initialize the variable $i with 4 each time we enter this event
493 handler, because each time we executed this handler, the variable will be 0 }
494 $i := $delayNotes
495
496 { Loop which will be executed 4 times in a row }
497 while ($i)
498 { Calculate the velocity for the next note being triggered }
499 $velocity := 127 * $i / ($delayNotes + 1)
500 { Suspend this script for a short moment ... }
501 wait($delayMicroSeconds)
502 { ... and after that short break, trigger a new note. }
503 play_note($EVENT_NOTE, $velocity)
504 { Decrement loop counter $i by one }
505 $i := $i - 1
506 end while
507 end on
508 </code>
509 <p>
510 In this example we used a new keyword <code>const</code>. This additional
511 variable qualifier defines that we don't intend to change this variable
512 after declaration. So if you know beforehand, that a certain variable should
513 remain with a certain value, then you might use the <code>const</code>
514 qualifier to avoid that you i.e. change the value accidently when you
515 modify the script somewhere in future.
516 </p>
517 <p>
518 Now when you trigger one single note on your keyboard with that script,
519 you will hear the additional notes being triggered. And also when you
520 hit another note after a while, everything seems to be fine. However if
521 you start playing quick successive notes, you will notice something goes
522 wrong. The amount of notes being triggered by the script is now incorrect
523 and also the volume of the individual notes triggered by the script is wrong.
524 What's going on?
525 </p>
526 <p>
527 To understand the problem in the last example, let's consider what is
528 happening when executing that script exactly: Each time you play a note
529 on your keyboard, a new instance of the <code>note</code> event handler
530 will be spawned and executed by the sampler. In all our examples so far
531 our scripts were so simple, that in practice only one event handler instance
532 was executed at a time. This is different in this case though. Because
533 by calling the <code>wait()</code> function, the respective handler
534 execution instance is paused for a while and in total each handler
535 instance will be executed for more than 2 seconds in this particular
536 example. As a consequence, when
537 you play multiple, successive notes on your keyboard in short time, you
538 will have several instances of the <code>note</code> event handler running
539 simultaniously. And that's where the problem starts. Because by default,
540 as said, all variables are global variables. So the event handler instances
541 which are now running in parallel, are all reading and modifying the same
542 data. Thus the individual event handler instances will modify the
543 <code>$i</code> and <code>$velocity</code> variables of each other, causing
544 an undesired misbehavior.
545 </p>
546 <note>
547 NKSP's built-in function <code>play_note()</code> allows you to pass
548 between one and four function arguments. For the function arguments you
549 don't provide to a <code>play_note()</code> call, NKSP will automatically
550 use default values. If you want your script to be compatible with KSP,
551 then you should always pass four arguments to that function though.
552 </note>
553
554 <h3>Polyphonic Variables</h3>
555 <p>
556 As a logical consequence of the previously described data concurrency
557 problem, it would be desirable to have each event handler instance use
558 its own variable instance, so that the individual handler instances stop
559 interfering with each other. For this purpose the so called
560 <i title="A variable which is effectively a separate variable for each event handler instance.">
561 polyphonic variable
562 </i>
563 qualifier exists with NKSP. Declaring such a variable is identical to
564 declaring a regular variable, just that you add the keyword <code>polyphonic</code>.
565 </p>
566 <code>
567 declare polyphonic $??variable-name??
568 </code>
569 <p>
570 So to fix the bug in our previous example, we simply make the variables
571 <code>$i</code> and <code>$velocity</code> polyphonic variables.
572 </p>
573 <code>
574 on init
575 { The amount of notes to play }
576 declare const $delayNotes := 4
577 { Tempo with which the new notes will follow the orignal note }
578 declare const $bpm := 90
579 { Convert BPM to microseconds (duration between the notes) }
580 declare const $delayMicroSeconds := 60 * 1000000 / $bpm
581 { Just a working variable for being used with the while loop below }
582 declare polyphonic $i { < --- NOW POLYPHONIC !!! }
583 { For each successive note we trigger, we will reduce the velocity a bit}
584 declare polyphonic $velocity { < --- NOW POLYPHONIC !!! }
585 end on
586
587 on note
588 { First initialize the variable $i with 4 each time we enter this event
589 handler, because each time we executed this handler, the variable will be 0 }
590 $i := $delayNotes
591
592 { Loop which will be executed 4 times in a row }
593 while ($i)
594 { Calculate the velocity for the next note being triggered }
595 $velocity := 127 * $i / ($delayNotes + 1)
596 { Suspend this script for a short moment ... }
597 wait($delayMicroSeconds)
598 { ... and after that short break, trigger a new note. }
599 play_note($EVENT_NOTE, $velocity)
600 { Decrement loop counter $i by one }
601 $i := $i - 1
602 end while
603 end on
604 </code>
605 <p>
606 And that's it! The script works now as intended. Now you might wonder, why
607 are variables not <i>polyphonic</i> by default? Isn't that more common and
608 wouldn't that be more safer than using global variables by default? The reason is that
609 a polyphonic variable consumes a lot more memory than a regular (global) variable.
610 That's because for each polyphonic variable, the sampler has to allocate
611 in advance (when the script is loaded) as many instances of that
612 polyphonic variable as there are maximum events
613 allowed with the sampler. So that's a lot! Considering that today's
614 computers have plenty of RAM this might be a theoretical aspect, but in the
615 end: this default scope of variables was already like this with <i>KSP</i>
616 so we are also doing it like this with NKSP for compatibility reasons.
617 </p>
618 <p>
619 Please note that the <i>polyphonic</i> qualifier only exists for integer
620 variables. So you cannot declare polyphonic string variables, nor can you
621 declare polyphonic array variables. Like in the previous explanation,
622 this is due to the fact that it would consume a huge amount of memory
623 for such variables. And with string variables and array variables, the
624 required amount of memory would be much higher than with simple integer
625 variables.
626 </p>
627 <p>
628 As summary, the following are guideline rules describing when you should
629 use the polyphonic qualifier for a certain variable. You should declare
630 a particular variable polyphonic if one (or even both) of the following two
631 conditions apply to that variable.
632 </p>
633 <ol>
634 <li>
635 If you call the <code>wait()</code> function within your event
636 handlers and the respective variable is modified and read before
637 and after at least one of the individual <code>wait()</code> calls.
638 </li>
639 <li>
640 If you have loops that might run for a very long time, while accessing
641 the respective variable in between. That's because if your script is
642 running consecutively for too long, the sampler will automatically suspend your
643 script for a while to avoid your script becoming a real-time stability
644 hazard for the sampler. Your script will then automatically be resumed
645 after a short moment by the sampler, so effectively this is similar to
646 something like an "automated" <code>wait()</code> function call by
647 the sampler.
648 </li>
649 </ol>
650 <p>
651 In all other cases you should rather use regular (global) variables instead.
652 But keep in mind that you might need to re-assign a certain value for
653 some global variables when you enter the respective event handler, just
654 like we did with <code>$i := $delayNotes</code> right from the start
655 during discussion of the previous example script.
656 </p>
657 <p>
658 There is another special aspect regarding the variable scope of polyphonic
659 variables: <code>note</code> handlers and <code>release</code> handlers of
660 the same script share the same polyphonic variable scope, that means you
661 may pass data from a particular note's <code>note</code> handler to its
662 <code>release</code> handler by using the same polyphonic variable name.
663 </p>
664
665 <h2>Control Structures</h2>
666 <p>
667 A computer is more than a calculator that adds numbers and stores them
668 somewhere. One of the biggest strength of a computer, which makes it
669 such powerful, is the ability to do different things depending on various
670 conditions. For example your computer might clean up your hard drive
671 while you are not sitting in front of it, and it might immediately stop
672 doing so when you need all its resources to cut your latest video which
673 you just shot.
674 </p>
675 <p>
676 In order to do that for you, a computer program allows you to define
677 conditions and a list of instructions the computer shall
678 perform for you under those individual conditions. These kinds of
679 software mechanisms are called <i>Control Structures</i>.
680 </p>
681
682 <h3>if Branches</h3>
683 <p>
684 The most fundamental control structure are <i>if branches</i>, which has
685 the following general form.
686 </p>
687 <code>
688 if (??condition??)
689
690 ??statements??
691
692 end if
693 </code>
694 <p>
695 The specified <code>??condition??</code> is evaluated each time script
696 execution reaches this control block. The condition can for example be
697 the value of a variable, some arithmetic expression, a function call or
698 a combination of them. In all cases the sampler expects the
699 <code>??condition??</code> expression to evaluate to some numeric
700 (or boolean) value. If the evaluated number is exactly <code>0</code> then
701 the condition is interpreted to be <i>false</i> and thus the list of
702 <code>??statements??</code> is not executed. If the evaluated value is any
703 other value than <code>0</code> then the condition is interpreted to be
704 <i>true</i> and accordingly the list of <code>??statements??</code> will be
705 executed.
706 </p>
707 <p>
708 Alternatively you might also specify a list of instructions which shall be
709 executed when the condition is <i>false</i>.
710 </p>
711 <code>
712 if (??condition??)
713
714 ??statements-when-true??
715
716 else
717
718 ??statements-when-false??
719
720 end if
721 </code>
722 <p>
723 In this case the first list of statements is executed when the
724 <code>??condition??</code> evaluated to <i>true</i>, otherwise the second
725 list of statements is executed instead.
726 </p>
727 <p>
728 Once again, let's get back to the example of counting triggered notes.
729 You might have noticed that it did not output correct English for the
730 first three notes. Let's correct this now.
731 </p>
732 <code>
733 on init
734 declare $numberOfNotes
735 declare @postfix
736 end on
737
738 on note
739 $numberOfNotes := $numberOfNotes + 1
740
741 if ($numberOfNotes == 1)
742 @postfix := "st"
743 else
744 if ($numberOfNotes == 2)
745 @postfix := "nd"
746 else
747 if ($numberOfNotes == 3)
748 @postfix := "rd"
749 else
750 @postfix := "th"
751 end if
752 end if
753 end if
754
755 message("This is the " & $numberOfNotes & @postfix & " note triggered so far.")
756 end on
757 </code>
758 <p>
759 We are now checking the value of <code>$numberOfNotes</code> before we
760 print out a message. If <code>$numberOfNotes</code> equals one, then we
761 assign the string <code>"st"</code> to the variable <code>@postfix</code>,
762 if <code>$numberOfNotes</code> equals 2 instead we assign the string
763 <code>"nd"</code> instead, if it equals 3 instead we assign
764 <code>"rd"</code>, in all other cases we assign the string
765 <code>"th"</code>. And finally we assemble the text message to be
766 printed out to the terminal on line 23.
767 </p>
768
769 <h3>Select Case Branches</h3>
770 <p>
771 The previous example now outputs the numbers in correct English. But the
772 script code looks a bit bloated, right? That's why there is a short hand
773 form.
774 </p>
775 <code>
776 select ??expression??
777
778 case ??integer-1??
779
780 ??statements-1??
781
782
783 case ??integer-2??
784
785 ??statements-2??
786
787 .
788 .
789 .
790 end select
791 </code>
792 <p>
793 The provided <code>??expression??</code> is first evaluated to an integer
794 value. Then this value is compared to the integer values of the nested
795 <code>case</code> lines. So it first compares the evaluated value of
796 <code>??expression??</code> with <code>??integer-1??</code>, then it
797 compares it with <code>??integer-2??</code>, and so on. The first integer
798 number that matches with the evaluated value of <code>??expression??</code>,
799 will be interpreted as being the current valid condition. So if
800 <code>??expression??</code> equals <code>??integer-1??</code>,
801 then <code>??statements-1??</code> will be executed, otherwise if
802 <code>??expression??</code> equals <code>??integer-2??</code>,
803 then <code>??statements-2??</code> will be executed, and so on.
804 </p>
805 <p>
806 Using a select-case construct, our previous example would look like follows.
807 </p>
808 <code>
809 on init
810 declare $numberOfNotes
811 declare @postfix
812 end on
813
814 on note
815 $numberOfNotes := $numberOfNotes + 1
816 @postfix := "th"
817
818 select $numberOfNotes
819 case 1
820 @postfix := "st"
821 case 2
822 @postfix := "nd"
823 case 3
824 @postfix := "rd"
825 end select
826
827 message("This is the " & $numberOfNotes & @postfix & " note triggered so far.")
828 end on
829 </code>
830 <note>
831 If you like, you can also put parentheses around the select expression,
832 like <code>select (??expression??)</code>. Some developers familiar with
833 other programming languages might prefer this style. However if you want
834 to keep compatibility with KSP, you should not use parentheses for
835 select expressions.
836 </note>
837 <p>
838 The amount
839 of case conditions you add to such select-case blocks is completely up
840 to you. Just remember that the case conditions will be compared one by one,
841 from top to down. The latter can be important when you define a case line
842 that defines a value range. So for instance the following example will
843 not do what was probably intended.
844 </p>
845 <code>
846 on init
847 declare $numberOfNotes
848 end on
849
850 on note
851 $numberOfNotes := $numberOfNotes + 1
852
853 select $numberOfNotes
854 case 1 to 99
855 message("Less than 100 notes triggered so far")
856 exit
857 case 1
858 message("First note was triggered!") { Will never be printed ! }
859 exit
860 case 2
861 message("Second note was triggered!") { Will never be printed ! }
862 exit
863 case 3
864 message("Third note was triggered!") { Will never be printed ! }
865 exit
866 end select
867
868 message("Wow, already the " & $numberOfNotes & "th note triggered.")
869 end on
870 </code>
871 <p>
872 You probably get the idea what this script "should" do. For the 1st note
873 it should print <code>"First note was triggered!"</code>, for the 2nd
874 note it should print <code>"Second note was triggered!"</code>, for the 3rd
875 note it should print <code>"Third note was triggered!"</code>, for the 4th
876 up to 99th note it should print <code>"Less than 100 notes triggered so far"</code>,
877 and starting from the 100th note and all following ones, it should print
878 the precise note number according to line 23. However, it doesn't!
879 </p>
880 <p>
881 To correct this problem, you need to move the first case block to the end,
882 like follows.
883 </p>
884 <code>
885 on init
886 declare $numberOfNotes
887 end on
888
889 on note
890 $numberOfNotes := $numberOfNotes + 1
891
892 select $numberOfNotes
893 case 1
894 message("First note was triggered!")
895 exit
896 case 2
897 message("Second note was triggered!")
898 exit
899 case 3
900 message("Third note was triggered!")
901 exit
902 case 1 to 99
903 message("Less than 100 notes triggered so far")
904 exit
905 end select
906
907 message("Wow, already the " & $numberOfNotes & "th note triggered.")
908 end on
909 </code>
910 <p>
911 Or you could of course fix the questioned case range from <code>case 1 to 99</code>
912 to <code>case 4 to 99</code>. Both solutions will do.
913 </p>
914 <p>
915 We also used the <i>built-in function</i> <code>exit()</code> in the
916 previous example. You can use it to stop execution at that point of your
917 script. In the previous example it prevents multiple messages to be
918 printed to the terminal.
919 </p>
920 <note class="important">
921 The <code>exit()</code> function only stops execution of the <b>current</b>
922 event handler instance! It does <b>not</b> stop execution of other
923 instances of the same event handler, nor does it stop execution of other
924 handlers of other event types, and especially it does <b>not</b> stop or
925 prevent further or future execution of your entire script! In other words,
926 you should rather see this function as a return statement, in case you are
927 familiar with other programming languages already.
928 </note>
929
930 <h3>while Loops</h3>
931 <p>
932 Another fundamental control construct of program flow are loops.
933 You can use so called
934 <i title="Repeats a given list of instructions until the defined condition turns false.">
935 while loops
936 </i>
937 with NKSP.
938 </p>
939 <code>
940 while (??condition??)
941
942 ??statements??
943
944 end while
945 </code>
946 <p>
947 A while loop is entered if the provided <code>??condition??</code>
948 expression evaluates to <i>true</i> and will then continue to execute
949 the given list of <code>??statements??</code> down to the end of the statements
950 list. The <code>??condition??</code> is re-evaluated each time execution
951 reached the end of the <code>??statements??</code> list and according to
952 that latest evaluated <code>??condition??</code> value at that point, it
953 will or will not repeat executing the statements again. If the condition
954 turned <i>false</i> instead, it will leave the loop and continue executing
955 statements that follow after the while loop block.
956 </p>
957 <p>
958 The next example will print the same message three times in a row to the
959 terminal, right after the script had been loaded by the sampler.
960 </p>
961 <code>
962 on init
963 declare $i := 3
964
965 while ($i)
966 message("Print this three times.")
967 $i := $i - 1
968 end while
969 end on
970 </code>
971 <p>
972 When the while loop is reached for the first time in this example, the
973 condition value is <code>3</code>. And as we learned before, all integer
974 values that are not <code>0</code> are interpreted as being a <i>true</i> condition.
975 Accordingly the while loop is entered, the message is printed to the
976 terminal and the variable <code>$i</code> is reduced by one. We reached
977 the end of the loop's statements list, so it is now re-evaluating the
978 condition, which is now the value <code>2</code> and thus the loop
979 instructions are executed again. That is repeated until the loop was
980 executed for the third time. The variable <code>$i</code> is now
981 <code>0</code>, so the loop condition turned finally to <i>false</i> and the
982 loop is thus left at that point and the text message was printed
983 three times in total.
984 </p>
985
986 <h3>User Functions</h3>
987 <p>
988 We already came across various built-in functions, which you may call
989 by your scripts to perform certain tasks or behavior which is already
990 provided for you by the sampler. NKSP also allows you to write your
991 own functions, which you then may call from various places of your
992 script.
993 <p>
994 </p>
995 When working on larger scripts, you
996 may notice that you easily get to the point where you may have to
997 duplicate portions of your script code, since there are certain things
998 that you may have to do again and again in different parts of your script.
999 Software developers usually try to avoid such code duplications to
1000 keep the overall amount of code as small as possible, since the
1001 overall amount of code would bloat quickly and would
1002 make the software very hard to maintain. One way for you to avoid such
1003 script code duplications with NKSP is to write so called <i>User Functions</s>.
1004 </p>
1005 <p>
1006 Let's assume you wanted to create a simple stuttering effect. You may do so
1007 like in the following example.
1008 </p>
1009 <code>
1010 on note
1011 while (1)
1012 wait(200000)
1013 if (not (event_status($EVENT_ID) .and. $EVENT_STATUS_NOTE_QUEUE))
1014 exit()
1015 end if
1016 change_vol($EVENT_ID, -20000) { Reduce volume by 20 dB. }
1017 wait(200000)
1018 if (not (event_status($EVENT_ID) .and. $EVENT_STATUS_NOTE_QUEUE))
1019 exit()
1020 end if
1021 change_vol($EVENT_ID, 0) { Increase volume to 0 dB. }
1022 end while
1023 end on
1024 </code>
1025 <p>
1026 This script will run an endless loop for each note being triggered.
1027 Every <code lang="none">200ms</code> it will turn the volume alternatingly down and
1028 up to create the audible stuttering effect. After each <code lang="nksp">wait()</code>
1029 call it calls <code>event_status($EVENT_ID)</code> to check whether
1030 this note is still alive, and as soon as the note died, it will stop
1031 execution of the script instance by calling <code>exit()</code>. The latter
1032 is important in this example, because otherwise the script execution instances would
1033 continue to run in this endless loop forever, even after the respectives
1034 notes are gone. Which would let your CPU usage increase with every new note
1035 and would never decrease again.
1036 This behavior of the sampler is not a bug, it is intended, since there may
1037 also be cases where you want to do certain things by script even after the
1038 respective notes are dead and gone. However as you can see, that script is
1039 using the same portions of script code twice. To avoid that, you could also
1040 write the same script with a user function like this:
1041 </p>
1042 <code>
1043 function pauseMyScript
1044 wait(200000)
1045 if (not (event_status($EVENT_ID) .and. $EVENT_STATUS_NOTE_QUEUE))
1046 exit()
1047 end if
1048 end function
1049
1050 on note
1051 while (1)
1052 call pauseMyScript
1053 change_vol($EVENT_ID, -20000) { Reduce volume by 20 dB. }
1054 call pauseMyScript
1055 change_vol($EVENT_ID, 0) { Increase volume back to 0 dB. }
1056 end while
1057 end on
1058 </code>
1059 <p>
1060 The script became in this simple example only slightly smaller, but it also
1061 became easier to read and behaves identically to the previous solution.
1062 And in practice, with a more complex script, you can
1063 reduce the overall amount of script code a lot this way. You can choose any
1064 name for your own user functions, as long as the name is not already
1065 reserved by a built-in function. Note that for calling a user function,
1066 you must always precede the actual user function name with the
1067 <code>call</code> keyword. Likewise you may however not use the
1068 <code>call</code> keyword for calling any built-in function. So that
1069 substantially differs calling built-in functions from calling user functions.
1070 </p>
1071
1072 <h3>Synchronized Blocks</h3>
1073 <p>
1074 When we introduced the <a href="#polyphonic_variables">polyphonic keyword</a>
1075 previously, we learned that a script may automatically be suspended by
1076 the sampler at any time and then your script is thus sleeping for an
1077 arbitrary while. The sampler must do such auto suspensions under certain
1078 situations in cases where an instrument script may become a hazard for the
1079 sampler's overall real-time stability. If the sampler would not do so, then
1080 instrument scripts might easily cause audio dropouts, or at worst, buggy
1081 instrument scripts might even lock up the entire sampler in an endless
1082 loop. So auto suspension is an essential feature of the sampler's real-time
1083 instrument script engine.
1084 </p>
1085 <p>
1086 Now the problem as a script author is that you don't really know beforehand
1087 why and when your script might get auto suspended by the sampler. And when
1088 you are working on more complex, sophisticated scripts, you will notice
1089 that this might indeed be a big problem in certain sections of your scripts.
1090 Because in practice, a sophisticated script often has at least one certain
1091 consecutive portion of statements which must be executed in strict consecutive order
1092 by the sampler, which might otherwise cause concurrency issues and thus
1093 misbehavior of your script if that sensible code section was auto suspended
1094 in between. A typical example of such concurrency sensible code sections are
1095 statements which are reading and conditionally modifying global variables.
1096 If your script gets auto suspended in such a code section, another
1097 script handler instance might then interfere and change those global
1098 variables in between.
1099 </p>
1100 <p>
1101 To avoid that, you can place such a sensible code section at the very beginning
1102 of your event handler. For example consider you might be writing a custom
1103 <i title="A consecutive pitch glide from one note to another note.">glissando</i>
1104 script starting like this:
1105 </p>
1106 <code>
1107 on init
1108 declare $keysDown
1109 declare $firstNoteID
1110 declare $firstNoteNr
1111 declare $firstVelocity
1112 end on
1113
1114 on note
1115 { The concurrency sensible code section for the "first active" note. }
1116 inc($keysDown)
1117 if ($keysDown = 1 or event_status($firstNoteID) = $EVENT_STATUS_INACTIVE)
1118 $firstNoteID = $EVENT_ID
1119 $firstNoteNr = $EVENT_NOTE
1120 $firstVelocity = $EVENT_VELOCITY
1121 exit { return from event handler here }
1122 end if
1123
1124 { The non-sensible code for all other subsequent notes would go here. }
1125 end on
1126
1127 on release
1128 dec($keysDown)
1129 end on
1130 </code>
1131 <p>
1132 Because the earlier statements are executed in an event handler, the higher
1133 the chance that they will never get auto suspended. And with those couple of
1134 lines in the latter example you might even be lucky that it won't ever get
1135 suspended in that sensible code section at least. However when it comes to live
1136 concerts you don't really want to depend on luck, and in practice such a
1137 sensible code section might be bigger than this one.
1138 </p>
1139 <p>
1140 That's why we introduced <code>synchronized</code> code blocks for the
1141 NKSP language, which have the following form:
1142 </p>
1143 <code>
1144 synchronized
1145
1146 ??statements??
1147
1148 end synchronized
1149 </code>
1150 <p>
1151 All <code>??statements??</code> which you put into such a synchronized
1152 code block are guaranteed that they will never get auto suspended by
1153 the sampler.
1154 </p>
1155 <note>
1156 Such <code>synchronized</code> blocks are a language extension which
1157 is only available with NKSP. KSP does not support <code>synchronized</code> blocks.
1158 </note>
1159 <p>
1160 So to make our previous example concurrency safe, we would
1161 change it like this:
1162 </p>
1163 <code>
1164 on init
1165 declare $keysDown
1166 declare $firstNoteID
1167 declare $firstNoteNr
1168 declare $firstVelocity
1169 end on
1170
1171 on note
1172 { The concurrency sensible code section for the "first active" note. }
1173 synchronized
1174 inc($keysDown)
1175 if ($keysDown = 1 or event_status($firstNoteID) = $EVENT_STATUS_INACTIVE)
1176 $firstNoteID = $EVENT_ID
1177 $firstNoteNr = $EVENT_NOTE
1178 $firstVelocity = $EVENT_VELOCITY
1179 exit { return from event handler here }
1180 end if
1181 end synchronized
1182
1183 { The non-sensible code for all other subsequent notes would go here. }
1184 end on
1185
1186 on release
1187 dec($keysDown)
1188 end on
1189 </code>
1190 <p>
1191 If you are already familiar with some programming languages, then you
1192 might already have seen such synchronized code block concepts
1193 in languages like e.g. Java. This technique really provides an easy way
1194 to protect certain sections of your script against concurrency issues.
1195 </p>
1196 <note class="important">
1197 You <b>must</b> use such <code>synchronized</code> code blocks only with great
1198 care! If the amount of statements being executed in your synchronized block
1199 is too large, then you will get audio dropouts. If you even use loops in
1200 synchronized code blocks, then the entire sampler might even become
1201 unresponsive in case your script is buggy!
1202 </note>
1203
1204 <h2>Operators</h2>
1205 <p>
1206 A programming language provides so called <i>operators</i> to perform
1207 certain kinds of transformations of data placed next to the operators.
1208 These are the operators available with NKSP.
1209 </p>
1210
1211 <h3>Arithmetic Operators</h3>
1212 <p>
1213 These are the most basic mathematical operators, which allow to add,
1214 subtract, multiply and divide integer values with each other.
1215 </p>
1216 <code>
1217 on init
1218 message("4 + 3 is " & 4 + 3) { Add }
1219 message("4 - 3 is " & 4 - 3) { Subtract }
1220 message("4 * 3 is " & 4 * 3) { Multiply }
1221 message("35 / 5 is " & 35 / 5) { Divide }
1222 message("35 mod 5 is " & 35 mod 5) { Remainder of Division ("modulo") }
1223 end on
1224 </code>
1225 <p>
1226 You may either use direct integer literal numbers like used in the upper
1227 example, or you can use integer number variables or integer array variables.
1228 </p>
1229
1230 <h3>Boolean Operators</h3>
1231 <p>
1232 To perform logical transformations of <i>boolean</i> data, you may use the
1233 following logical operators:
1234 </p>
1235 <code>
1236 on init
1237 message("1 and 1 is " & 1 and 1) { logical "and" }
1238 message("1 and 0 is " & 1 and 0) { logical "and" }
1239 message("1 or 1 is " & 1 or 1) { logical "or" }
1240 message("1 or 0 is " & 1 or 0) { logical "or" }
1241 message("not 1 is " & not 1) { logical "not" }
1242 message("not 0 is " & not 0) { logical "not" }
1243 end on
1244 </code>
1245 <p>
1246 Keep in mind that with logical operators shown above,
1247 all integer values other than <code>0</code>
1248 are interpreted as boolean <i>true</i> while an integer value of
1249 precisely <code>0</code> is interpreted as being boolean <i>false</i>.
1250 </p>
1251 <p>
1252 So the logical operators shown above always look at numbers at a whole.
1253 Sometimes however you might rather need to process numbers bit by bit. For
1254 that purpose the following bitwise operators exist.
1255 </p>
1256 <code>
1257 on init
1258 message("1 .and. 1 is " & 1 .and. 1) { bitwise "and" }
1259 message("1 .and. 0 is " & 1 .and. 0) { bitwise "and" }
1260 message("1 .or. 1 is " & 1 .or. 1) { bitwise "or" }
1261 message("1 .or. 0 is " & 1 .or. 0) { bitwise "or" }
1262 message(".not. 1 is " & .not. 1) { bitwise "not" }
1263 message(".not. 0 is " & .not. 0) { bitwise "not" }
1264 end on
1265 </code>
1266 <p>
1267 Bitwise operators work essentially like logical operators, with the
1268 difference that bitwise operators compare each bit independently.
1269 So a bitwise <code>.and.</code> operator for instance takes the 1st bit
1270 of the left hand's side value, the 1st bit of the right hand's side value,
1271 compares the two bits logically and then stores that result as 1st bit of
1272 the final result value, then it takes the 2nd bit of the left hand's side value
1273 and the 2nd bit of the right hand's side value, compares those two bits logically
1274 and then stores that result as 2nd bit of the final result value, and so on.
1275 </p>
1276
1277
1278 <h3>Comparison Operators</h3>
1279 <p>
1280 For branches in your program flow, it is often required to compare data
1281 with each other. This is done by using comparison operators, enumerated
1282 below.
1283 </p>
1284 <code>
1285 on init
1286 message("Relation 3 < 4 -> " & 3 < 4) { "smaller than" comparison }
1287 message("Relation 3 > 4 -> " & 3 > 4) { "greater than" comparison }
1288 message("Relation 3 <= 4 -> " & 3 <= 4) { "smaller or equal than" comparison}
1289 message("Relation 3 >= 4 -> " & 3 >= 4) { "greater or equal than" comparison}
1290 message("Relation 3 # 4 -> " & 3 # 4) { "not equal to" comparison}
1291 message("Relation 3 = 4 -> " & 3 = 4) { "is equal to" comparison}
1292 end on
1293 </code>
1294 <p>
1295 All these operations yield in a <i>boolean</i> result which could then
1296 be used e.g. with <code>if</code> or <code>while</code> loop statements.
1297 </p>
1298
1299 <h3>String Operators</h3>
1300 <p>
1301 Last but not least, there is exactly one operator for text string data;
1302 the string concatenation operator <code>&</code>, which
1303 combines two text strings with each other.
1304 </p>
1305 <code>
1306 on init
1307 declare @s := "foo" & " bar"
1308 message(@s)
1309 end on
1310 </code>
1311 <p>
1312 We have used it now frequently in various examples before.
1313 </p>
1314
1315 <h2>Preprocessor Statements</h2>
1316 <p>
1317 Similar to low-level programming languages like C, C++, Objective C
1318 and the like, NKSP supports a set of so called preprocessor statements.
1319 These are essentially "instructions" which are "executed" or rather
1320 processed, before (and only before) the script is executed by the sampler,
1321 and even before the script is parsed by the actual NKSP language parser.
1322 You can think of a preprocessor as a very primitive parser, which is the
1323 first one getting in touch with your script, it modifies the script code
1324 if requested by your preprocessor statements in the script, and then
1325 passes the (probably) modified script to the actual NKSP language parser.
1326 </p>
1327 <p>
1328 When we discussed <a href="#comments">comments</a> in NKSP scripts before,
1329 it was suggested that you might comment out certain code parts to disable
1330 them for a while during development of scripts. It was also suggested
1331 during this language tour that you should not use string variables or use
1332 the <code>message()</code> function with your final production sounds.
1333 However those are very handy things during development of your instrument
1334 scripts. You might even have a bunch of additional code in your scripts
1335 which only satisfies the purpose to make debugging of your scripts more easy,
1336 which however wastes on the other hand precious CPU time. So what do you
1337 do? Like suggested, you could comment out the respective code sections as
1338 soon as development of your script is completed. But then one day you
1339 might continue to improve your scripts, and the debugging code would be
1340 handy, so you would uncomment all the relevant code sections to get them
1341 back. When you think about this, that might be quite some work each time.
1342 Fortunately there is an alternative by using preprocessor statements.
1343 </p>
1344
1345 <h3>Set a Condition</h3>
1346 <p>
1347 First you need to set a preprocessor condition in your script. You can do
1348 that like this:
1349 </p>
1350 <code>
1351 SET_CONDITION(??condition-name??)
1352 </code>
1353 <p>
1354 This preprocessor "condition" is just like some kind of
1355 <i title="A variable which can only have two states: i.e. true or false.">
1356 boolean variable
1357 </i>
1358 which is only available to the preprocessor and by using
1359 <code>SET_CONDITION(??condition-name??)</code>, this is like setting this
1360 preprocessor condition to <i>true</i>. Like with regular script
1361 variables, a preprocessor condition name can be chosen quite arbitrarily
1362 by you. But again, there are some pre-defined preprocessor conditions
1363 defined by the sampler for you. So you can only set a condition name here
1364 which is not already reserved by a built-in preprocessor condition. Also
1365 you shall not set a condition in your script again if you have already set it
1366 before somewhere in your script. The NKSP preprocessor will ignore setting
1367 a condition a 2nd time and will just print a warning when the script is
1368 loaded, but you should take care of it, because it might be a cause for
1369 some bug.
1370 </p>
1371
1372 <h3>Reset a Condition</h3>
1373 <p>
1374 To clear a condition in your script, you might reset the condition like so:
1375 </p>
1376 <code>
1377 RESET_CONDITION(??condition-name??)
1378 </code>
1379 <p>
1380 This is like setting that preprocessor condition back to <i>false</i> again.
1381 You should only reset a preprocessor condition that way if you did set it
1382 with <code>SET_CONDITION(??condition-name??)</code> before. Trying to
1383 reset a condition that has not been set before, or trying to reset a
1384 condition that has already been reset, will both be ignored by the sampler,
1385 but again you will get a warning, and you should take care about it.
1386 </p>
1387
1388 <h3>Conditionally Using Code</h3>
1389 <p>
1390 Now what do you actually do with such preprocessor conditions? You can use
1391 them for the NKSP language parser to either
1392 </p>
1393 <ul>
1394 <li>use certain parts of your code</i>
1395 <li><b>and</b> / <b>or</b> to ignore certain parts of your code</i>
1396 </ul>
1397 <p>
1398 You can achieve that by wrapping NKSP code parts into a pair of either
1399 </p>
1400 <code>
1401 USE_CODE_IF(??condition-name??)
1402
1403 ??some-NKSP-code-goes-here??
1404
1405 END_USE_CODE
1406 </code>
1407 <p>
1408 preprocessor statements, or between
1409 </p>
1410 <code>
1411 USE_CODE_IF_NOT(??condition-name??)
1412
1413 ??some-NKSP-code-goes-here??
1414
1415 END_USE_CODE
1416 </code>
1417 <p>
1418 statements. In the first case, the NKSP code portion is used by the NKSP
1419 language parser if the given preprocessor <code>??condition-name??</code> is set
1420 (that is if condition is <i>true</i>).
1421 If the condition is not set, the NKSP code portion in between is
1422 completely ignored by the NKSP language parser.
1423 </p>
1424 <p>
1425 In the second case, the NKSP code portion is used by the NKSP
1426 language parser if the given preprocessor <code>??condition-name??</code> is <b>not</b> set
1427 (or was reset)
1428 (that is if condition is <i>false</i>).
1429 If the condition is set, the NKSP code portion in between is
1430 completely ignored by the NKSP language parser.
1431 </p>
1432 <p>
1433 Let's look at an example how to use that to define conditional debugging
1434 code.
1435 </p>
1436 <code>
1437 SET_CONDITION(DEBUG_MODE)
1438
1439 on init
1440 declare const %primes[12] := ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 )
1441 declare $i
1442
1443 USE_CODE_IF(DEBUG_MODE)
1444 message("This script has just been loaded.")
1445
1446 $i := 0
1447 while ($i < num_elements(%primes))
1448 message("Prime " & $i & " is " & %primes[$i])
1449 $i := $i + 1
1450 end while
1451 END_USE_CODE
1452 end on
1453
1454 on note
1455 USE_CODE_IF(DEBUG_MODE)
1456 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
1457 END_USE_CODE
1458 end on
1459
1460 on release
1461 USE_CODE_IF(DEBUG_MODE)
1462 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
1463 END_USE_CODE
1464 end on
1465
1466 on controller
1467 USE_CODE_IF(DEBUG_MODE)
1468 message("MIDI Controller " & $CC_NUM " changed its value to " & %CC[$CC_NUM])
1469 END_USE_CODE
1470 end on
1471 </code>
1472 <p>
1473 The <i>built-in function</i> <code>num_elements()</code> used above, can
1474 be called to obtain the size of an array variable at runtime.
1475 As this script looks now, the debug messages will be printed out. However
1476 it requires you to just remove the first line, or to comment out the first
1477 line, in order to disable all debug code portions in just a second:
1478 </p>
1479 <code>
1480 { Setting the condition is commented out, so our DEBUG_MODE is disabled now. }
1481 { SET_CONDITION(DEBUG_MODE) }
1482
1483 on init
1484 declare const %primes[12] := ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 )
1485 declare $i
1486
1487 USE_CODE_IF(DEBUG_MODE) { Condition is not set, so this entire block will be ignored now. }
1488 message("This script has just been loaded.")
1489
1490 $i := 0
1491 while ($i < num_elements(%primes))
1492 message("Prime " & $i & " is " & %primes[$i])
1493 $i := $i + 1
1494 end while
1495 END_USE_CODE
1496 end on
1497
1498 on note
1499 USE_CODE_IF(DEBUG_MODE) { Condition is not set, no message will be printed. }
1500 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
1501 END_USE_CODE
1502 end on
1503
1504 on release
1505 USE_CODE_IF(DEBUG_MODE) { Condition is not set, no message will be printed. }
1506 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
1507 END_USE_CODE
1508 end on
1509
1510 on controller
1511 USE_CODE_IF(DEBUG_MODE) { Condition is not set, no message will be printed. }
1512 message("MIDI Controller " & $CC_NUM " changed its value to " & %CC[$CC_NUM])
1513 END_USE_CODE
1514 end on
1515 </code>
1516 <p>
1517 Now you might say, you could also achieve that by declaring and using
1518 a regular NKSP variable. That's correct, but there are two major
1519 advantages by using preprocessor statements.
1520 </p>
1521 <ol>
1522 <li>
1523 <b>Saving Resources</b> -
1524 The preprocessor conditions are only processed before the script is
1525 loaded into the NKSP parser. So in contrast to using NKSP variables,
1526 the preprocessor solution does not waste any CPU time or memory
1527 resources while executing the script. That also means that variable
1528 declarations can be disabled with the preprocessor this way
1529 and thus will also safe resources.
1530 </li>
1531 <li>
1532 <b>Cross Platform Support</b> -
1533 Since the code portions filtered out by the preprocessor never make it
1534 into the NKSP language parser, those filtered code portions might also
1535 contain code which would have lead to parser errors. For example you
1536 could use a built-in preprocessor condition to check whether your script
1537 was loaded into LinuxSampler or rather into another sampler. That way
1538 you could maintain one script for both platforms: NKSP and KSP.
1539 Accordingly you could
1540 also check a built-in variable to obtain the version of the sampler in
1541 order to enable or disable code portions of your script that might
1542 use some newer script features of the sampler which don't exist in older
1543 version of the sampler.
1544 </li>
1545 </ol>
1546 <p>
1547 As a rule of thumb: if there are things that you could move from your
1548 NKSP executed programming code out to the preprocessor, then you should
1549 use the preprocessor instead for such things. And like stated above,
1550 there are certain things which you can only achieve with the preprocessor.
1551 </p>
1552
1553 <h3>Disable Messages</h3>
1554 <p>
1555 Since it is quite common to switch a script between a development version
1556 and a production version, you actually don't need to wrap all your
1557 <code>message()</code> calls into preprocessor statements like in the
1558 previous example just to disable messages. There is actually a built-in
1559 preprocessor condition dedicated to perform that task much more conveniently for you.
1560 To disable all messages in your script, simply add <code>SET_CONDITION(NKSP_NO_MESSAGE)</code>
1561 e.g. at the very beginning of your script.
1562 So the previous example can be simplified to this:
1563 </p>
1564 <code>
1565 { Enable debug mode, so show all debug messages. }
1566 SET_CONDITION(DEBUG_MODE)
1567
1568 { If our user declared condition "DEBUG_MODE" is not set ... }
1569 USE_CODE_IF_NOT(DEBUG_MODE)
1570 { ... then enable this built-in condition to disable all message() calls. }
1571 SET_CONDITION(NKSP_NO_MESSAGE)
1572 END_USE_CODE
1573
1574 on init
1575 declare const %primes[12] := ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 )
1576 declare $i
1577
1578 message("This script has just been loaded.")
1579
1580 USE_CODE_IF(DEBUG_MODE)
1581 $i := 0
1582 while ($i < num_elements(%primes))
1583 message("Prime " & $i & " is " & %primes[$i])
1584 $i := $i + 1
1585 end while
1586 END_USE_CODE
1587 end on
1588
1589 on note
1590 message("Note " & $EVENT_NOTE & " was triggered with velocity " & $EVENT_VELOCITY)
1591 end on
1592
1593 on release
1594 message("Note " & $EVENT_NOTE & " was released with release velocity " & $EVENT_VELOCITY)
1595 end on
1596
1597 on controller
1598 message("MIDI Controller " & $CC_NUM " changed its value to " & %CC[$CC_NUM])
1599 end on
1600 </code>
1601 <p>
1602 You can then actually also add <code>RESET_CONDITION(NKSP_NO_MESSAGE)</code>
1603 at another section of your script, which will cause all subsequent
1604 <code>message()</code> calls to be processed again. So that way you can
1605 easily enable and disable <code>message()</code> calls of entire individual
1606 sections of your script, without having to wrap all <code>message()</code>
1607 calls into preprocessor statements.
1608 </p>
1609
1610 <h2>What Next?</h2>
1611 <p>
1612 You have completed the introduction of the NKSP real-time instrument
1613 script language at this point. You can now dive into the details of the
1614 NKSP language by moving on to the
1615 <a href="nksp_reference.html">NKSP reference documentation</a>.
1616 Which provides you an overview and quick access to the details of all
1617 built-in functions, built-in variables and more.
1618 </p>
1619 <p>
1620 You might also be interested to look at new <i>NKSP</i> core language
1621 features being added to the latest development version of the sampler:
1622 <a href="real_unit_final/01_nksp_real_unit_final.html">
1623 Real Numbers, Units and Finalness ...
1624 </a>
1625 </p>
1626
1627 </body>
1628 </html>

  ViewVC Help
Powered by ViewVC