ViewVC logotype

Contents of /doc/docbase/instrument_scripts/nksp/real_unit_final/01_nksp_real_unit_final.html

Parent Directory Parent Directory | Revision Log Revision Log

Revision 3599 - (show annotations) (download) (as text)
Sun Sep 15 20:39:58 2019 UTC (13 months ago) by schoenebeck
File MIME type: text/html
File size: 50468 byte(s)
* Draft: NKSP Real Numbers, Units and Finalness.

1 <html>
2 <head>
3 <meta name="author" content="Christian Schoenebeck">
4 <title>Real Numbers, Units and Finalness</title>
5 <urlpath>Real_Numbers_Units_and_Finalness</urlpath>
6 <meta name="description" content="NKSP Development News: Support for real numbers, standard measuring units and finalness.">
7 <link rel="stylesheet" href="http://doc.linuxsampler.org/css/preview.css">
8 <script type="text/javascript" src="http://doc.linuxsampler.org/js/preview.js"></script>
9 </head>
10 <body>
11 <p>
12 As you might have seen from our change log, I've been recently working on
13 a bunch of new core features for our <a href="01_nksp.html">NKSP</a>
14 real-time instrument script engine, with the goal to make instrument
15 scripting more intuitive and less error prone, especially from a
16 musician's point of view.
17 </p>
18 <p>
19 The changes are quite substantial, so here is
20 a more detailed description of what's new, how to use those new
21 features, what's the motivation behind them, and also a discourse
22 about some of the associated language design (and implementation) aspects.
23 </p>
24 <note class="important">
25 Features described in this article refer to LinuxSampler version <b>2.1.1.svn16</b> (or higher).
26 So these features are not available in older versions of the sampler.
27 And since these are new development features, they still might be subject to change.
28 </note>
30 <h2>64-Bit Integers</h2>
31 <p>
32 First of all, integers, i.e. integer number literals (as e.g. <code lang="nksp">4294967295</code>), integer
33 variables (like <code lang="nksp">declare $foo := 4294967295</code>), or
34 integer array variables (like <code>declare %bar[3] := ( 1, 2, 3 ) </code>),
35 and all their arithmetics like
36 <code lang="nksp">($foo + 1024) / 24</code> and all built-in functions (as e.g.
37 <code>min()</code>), are now all 64 bit with <a href="01_nksp.html">NKSP</a>.<br>
38 <br>
39 I hear your "<i>Yaaawn</i>" at this point. You might be surprised though about the amount of
40 <a href="https://en.wikipedia.org/wiki/Diff">diff</a> involved
41 and how often people stumbled over undesired 32-bit truncation with their
42 scripts before. So that change alone reduced error-proneness tremendously.
43 But let's get on.
44 </p>
46 <h2>Real Numbers</h2>
47 <p>
48 You are finally no longer limited to integer math with <a href="01_nksp.html">NKSP</a>.
49 You can now also use floating point arithmetics which will make calculations,
50 that is mathematical formulas in your scripts much easier than before.
51 Sounds a bit more interesting, doesn't it?<br>
52 </p>
54 <h3>Variables</h3>
55 <p>
56 We call those floating point numbers
57 <i title="One of the most important classes of numbers in mathematics where each <b>real number</b> represents a continous quantity qualified for reflecting a distance on a line, and hence real numbers are commonly used for the numerical value of measurements of physical quantities like e.g. length, temperature, mass, velocity.">
58 real numbers
59 </i> from now on and you can
60 write them like you probably already expected; in simple dotted notation like
61 <code>2.98</code>. Likewise there are new variable types for real numbers as well.
62 The syntax to declare a real number variable is:
63 </p>
64 <p>
65 <code lang="nksp">
66 declare ~??real-variable-name?? := ??initial-value??
67 </code>
68 </p>
69 <p>
70 Like e.g.:
71 </p>
72 <p>
73 <code lang="nksp">
74 declare ~foo := 3.14159265
75 </code>
76 </p>
77 <p>
78 So it looks pretty much the same as with integer variables, just that you use
79 "~" as prefix in front of the variable name instead of "$" that you would
80 use for integer variables <b>and</b> the values <b>must always</b> contain a dot so that the parser
81 can distinguish them clearly from integer numbers.
82 Moreover there is now also a real number array variable type which you can
83 declare like this:
84 </p>
85 <p>
86 <code lang="nksp">
87 declare ???real-array-variable-name??[??amount-of-elements??] := ( ??initial-values?? )
88 </code>
89 </p>
90 <p>
91 Like e.g.:
92 </p>
93 <p>
94 <code lang="nksp">
95 declare ?foo[4] := ( 0.1, 2.0, 46.238, 104.97 )
96 </code>
97 </p>
98 <p>
99 Once again, the only differences to integer array variables are that you use
100 "?" as prefix in front of the array variable name instead of "%" that you
101 would use for integer array variables, <b>and</b> that you <b>must always</b> use a
102 dot for each value being assigned.
103 And as with integer variables, if you omit to assign initial value(s) for
104 your real number variables or real array variables then they are automatically
105 initialized with zero value(s) (that is <code>0.0</code> actually).
106 </p>
107 <note class="remark">
108 I actually already had plans for implementing floating point support in <i>NKSP</i>
109 much earlier, but I somehow had the feeling that <i>KSP</i> would add it as well.
110 And I though before "inventing" again some kind of new syntax set for this feature
111 and then having to somehow merge and maintain cross-compatibility between <i>KSP</i> syntax
112 and <i>NKSP</i> syntax, I decided to wait a bit, and it
113 eventually appeared now on <i>KSP</i> side, so it was a good point to finally fill
114 this gap in <i>NKSP</i>.
115 </note>
117 <h3>Type Casting</h3>
118 <p>
119 Like <i>KSP</i> we are (currently) quite strict about your obligation to distinguish
120 clearly between integer numbers and real numbers with <i>NKSP</i>. That means blindly
121 mixing integers and real numbers e.g. in formulas, will currently cause a parser error
122 like in this example:
123 </p>
124 <p>
125 <code>~foo := (~bar + 1.9) / 24 { WRONG! }</code>
126 </p>
127 <p>
128 In this example you would simply use <code>24.0</code> instead of <code>24</code> to
129 fix the parser error:
130 </p>
131 <p>
132 <code>~foo := (~bar + 1.9) / 24.0 { correct }</code>
133 </p>
134 <p>
135 That's because, when you are mixing integer numbers and real numbers in mathematical
136 operations, like the division in the latter example, what was your intended data type that you
137 expected of the result of that division; a real number or an integer result? Because it
138 would not only mean a different data type, it might certainly also mean a completely
139 different result value accordingly.
140 </p>
141 <p>
142 That does not mean you were not allowed to mix real numbers with integers, it is just
143 that you have to make your point clear to the parser what your intention is. For that
144 purpose there are now 2 new built-in functions <code>int_to_real()</code> and
145 <code>real_to_int()</code> which you may use for required type casts (data type conversions).
146 So let's say you have a mathematical formula where you want to mix that formula with
147 a real number variable and an integer variable, then you might e.g. type cast the
148 integer variable like this:
149 </p>
150 <p>
151 <code>~bla := ~foo / int_to_real($bar)</code>
152 </p>
153 <p>
154 And since this is a very common thing to do, we also have 2 short-hand forms of these
155 2 built-in functions in <i>NKSP</i> which are simply <code>real()</code> and <code>int()</code>:
156 </p>
157 <p>
158 <code>~bla := ~foo / real($bar) { same as above, just shorter } </code>
159 </p>
160 <note>
161 The short-hand functions <code>real()</code> and <code>int()</code> only exist in
162 <i>NKSP</i>. They don't exist with <i>KSP</i>.
163 </note>
164 <note class="remark">
165 In future we might certainly lift this data type strictness and do it like many other
166 programming languages handle this: just showing a parser warning (not an error) on mixed
167 integer vs. real number expressions, and at the same time performing always an implied type cast
168 of the respective integer to a real number type automatically by the compiler.
169 </note>
171 <h3>Built-in Functions</h3>
172 <p>
173 What about real numbers and existing built-in functions? When you check our latest reference
174 documentation of <a href="01_nksp_reference.html">NKSP built-in functions</a>,
175 you will notice that most of them accept now both, integers and real numbers as arguments
176 to their function calls. You should be aware though that the precise acceptance of data
177 types and the resulting behaviour change, varies between the individual built-in functions,
178 which is due to the difference in purpose of all those numerous built-in functions.
179 </p>
180 <p>
181 For instance the data type of the result returned by <code>min()</code> and <code>max()</code>
182 function calls depends now on the data type being passed to those functions. That is
183 if you pass real numbers to those 2 functions then you'll get a real number as result;
184 if you pass integers instead then you'll get an integer as result instead.
185 </p>
186 <p>
187 Then there are functions, like e.g. the new functions <code>sin()</code>, <code>cos()</code>,
188 <code>tan()</code>, <code>sqrt()</code>, which only accept real numbers as arguments (and
189 always return a real number as result). Trying to pass integers will cause a parser error,
190 because those particular functions are not really useful on integers at all.
191 </p>
192 <p>
193 Likewise the previously already existing functions <code>fade_in()</code> and <code>fade_out()</code>
194 accept now both integers and real numbers for their 2nd argument (<code>??duration-us??</code>),
195 but do not allow real numbers for their 1st argument (<code>??note-id??</code>), because for
196 a duration real numbers make sense, whereas for a <code>??note-id??</code>
197 real numbers would not make any sense and such an attempt is usually a result of some
198 programming error, hence you will get a parser error when trying to pass a real number
199 to the 1st argument of those 2 built-in functions.
200 </p>
201 <p>
202 There might also be differences how built-in functions handle mixed usage of integers
203 and real numbers as arguments, simultaniously for the same function call that is.
204 For instance
205 the <code>min()</code> and <code>max()</code> functions are very permissive and allow you to mix
206 an integer argument with a real number argument. In such mixed cases those 2 functions
207 will simply handle the integer argument as if it was a real number and hence the
208 result's data type would be a real number. So this would be Ok:
209 </p>
210 <p>
211 <code>
212 min(0.3, 300) { OK for this function: mixed real and integer arguments }
213 </code>
214 </p>
215 <p>
217 Yet other functions,
218 like the <code>search()</code>
219 function, are very strict regarding data type. So if you are passing an integer array as 1st argument to
220 the <code>search()</code> function then it only accepts an integer (scalar) as
221 2nd argument, and likewise if you are passing a real number array as 1st argument
222 then it only accepts a real number (scalar) as 2nd argument. Attempts passing
223 different types, or in a different way to that function, will cause a parser error.
224 </p>
225 <note>
226 Use common sense! The accepted data types of arguments and correspending
227 result's data type of built-in functions usually match with your intuition,
228 and if it does not for some reason, then
229 you always get a clear parser error message immediately when trying to pass a wrong data
230 type while typing your scripts (e.g. in Gigedit's script editor). And on doubt you can
231 always refer to the <a href="01_nksp_reference.html">reference documentation</a> for
232 details of course.
233 </note>
235 <h3>Comparing for Equalness</h3>
236 <p>
237 If you are also writing <i>KSP</i> scripts, then you probably already knew most of the things that I
238 described above about real numbers. But here comes an important difference that we
239 have when dealing with real numbers in <i>NKSP</i>: real number value comparison for equalness and unequalness.
240 </p>
241 <p>
242 In our automated NKSP core language test cases you find an example that looks
243 like this (slightly changed here for simplicity):
244 </p>
245 <p>
246 <code>
247 on init
248 declare ~a := 0.165
249 declare ~b := 0.185
250 declare ~x := 0.1
251 declare ~y := 0.25
253 if (~a + ~b = ~x + ~y)
254 message("Test succeeded")
255 else
256 message("Test failed")
257 end if
259 end on
260 </code>
261 </p>
262 <p>
263 When you add the values of those variables from this example in your head, you will see that the actual
264 test in that example theoretically boils down to comparing <code>if (0.35 = 0.35)</code>.
265 Hence this test should always succeed. At least
266 that's what one would expect if one would do the calculations above manually by humans
267 in the real world.
268 In practice though, when this script is executed on a computer, the numbers on both sides would
269 slightly deviate from <code>0.35</code>. These differences to the expected value are
270 actually extremely little, that is very tiny fractions of several digits behind the decimal point,
271 but the final consequence would still be nevertheless different values on both sides and this test "would" hence fail.
272 These small errors are due to the technical way
273 <a href="https://en.wikipedia.org/wiki/Floating-point_arithmetic">floating point numbers are encoded</a>
274 on any modern <i>CPU</i> which causes small calculation errors with these summations for instance.
275 Due to that very well known circumstance of floating point arithmetics on
276 CPUs, it is commonly discouraged with system programming languages like C/C++
277 to directly compare floating point numbers for equalness, nor for unequalness for that exact reason.
278 </p>
279 <p>
280 However the use case for the NKSP language is completely different from
281 system level programming languages like C/C++. We don't need to be so
282 conservative in many aspects those languages need to be. The musical context of
283 <i>NKSP</i> simply has different requirements. Simplicity and high level
284 handling is more important for <i>NKSP</i> than revealing bit by bit
285 of the actual CPU registers bare-bone directly to users of instrument scripts.
286 So I decided to implement
287 real number equal (<code>=</code> operator) and unequal comparison
288 (<code>#</code> operator) to automatically take the expected floating
289 point tolerances of the underlying CPU into account.
290 </p>
291 <p>
292 So in short: the
293 <u>test case example above does <b>not</b> fail with our <i>NKSP</i> implementation</u>!
294 </p>
295 <p>
296 That does not mean you can simply switch off your head when doing
297 real number arithmetics and subsequent comparisons of those calculations.
298 Because with every calculation you do, the total amount of calculation
299 error (caused by the utilized floating point processing hardware) increases,
300 so after a certain amount of subsequent calculations
301 our equal/unequal comparisons would fail as well after a certain point.
302 But most of the time you will have formulas which end up with a very
303 limited amount of floating point calculations before you eventually
304 do your comparisons, so in most cases you should just be fine. But keep
305 this issue in mind when doing e.g. numeric (large amount of subsequent)
306 calculations e.g. in <code>while</code> loops.
307 </p>
308 <p>
309 What about the other comparison operators like <code>&lt;</code>,
310 <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>? Well,
311 those other comparison operators all behave as with system level
312 programming languages. So these comparison operators currently
313 do <b>not</b> take the mentioned floating point tolerances into
314 account and hence they behave differently than the <code>=</code>
315 and <code>#</code> operators with <i>NKSP</i>.
316 The idea was that those other
317 comparison operators are typically used for what mathematicians
318 call "transitivity". So they are used e.g. for sorting tasks
319 where there should always be a clear determinism of the
320 comparison results, and where execution speed is an issue as well.
321 Because the truth is also that our floating point tolerance
322 aware "equal" / "unequal" comparisons come with the price of
323 requiring execution of additional calculations on the underlying CPU.
324 </p>
326 <note class="remark">
327 You might wonder now, isn't this still sort of a hack? Wouldn't
328 there be a better way to implement real numbers in <i>NKSP</i> so that
329 all calculations would behave exactly as we would expect them from
330 theoretical math? The short answer is both <b>yes</b> and <b>no</b>.<br>
331 <br>
332 <b>Yes</b>, we could implement support for real numbers as so called
333 <a href="https://en.wikipedia.org/wiki/Computer_algebra_system">algebraic system</a>,
334 which would accomplish that real number calculations would always exactly
335 result as you would expect them to do from traditional mathematics,
336 like certain mathematical software applications use to do it
337 (e.g. <a href="https://en.wikipedia.org/wiki/Maple_(software)">Maple</a>).
338 However to achieve that we could no longer utilize hardware acceleration
339 of the CPU's floating point unit, because it is limited to floating point
340 values of fixed precision (e.g. either 32 bit and/or 64 bit).
341 Hence we would need to execute a huge amount of instructions on the CPU
342 instead for every single real number calculation in scripts, so there would
343 be a severe performance penalty.<br>
344 <br>
345 And <b>no</b>, we actually cannot do that in <i>NKSP</i> at all, because this kind of
346 complex real number implementation would require memory allocations at
347 runtime, which in turn would violate a key feature of <i>NKSP</i>
348 scripting: its guaranteed real-time stability and runtime determinism.
349 </note>
351 <h2>Standard Measuring Units</h2>
352 <p>
353 If you are coming from <i>KSP</i> then you are eventually going to think next
354 "WTF? What is this all about?". But hang with me, no matter how often you
355 wrote instrument scripts before, you will most
356 certainly regularly come into a situation like described next and we
357 have a convenient fix for that.
358 <p>
360 <h3>Unit Literals</h3>
361 <p>
362 Let's consider you wanted to pause your script at a certain point for let's say
363 1 second. Ok, you remember from the back of your head that you need to use the
364 built-in <code>wait()</code> function for that, but which value do you need to
365 pass exactly to achieve that 1 second break?
366 Would it be <code>wait(1000)</code>
367 or probably <code>wait(1000000)</code>? Of course now you reach out for the
368 reference documentation at this point and eventually find out that it
369 would actually be <code>wait(1000000)</code>. Not very intuitive. And
370 the large amount of zeros required does not help to make your code necessarily
371 more readable either, right?
372 </p>
373 <p>
374 So what about actually writing what we had in mind at first place:
375 </p>
376 <p>
377 <code>
378 wait(1s)
379 </code>
380 </p>
381 <p>
382 It couldn't be much clearer.
383 </p>
384 <p>
385 Or you want a break of 23 milliseconds instead? Then let's just write that!
386 </p>
387 <p>
388 <code>
389 wait(23ms)
390 </code>
391 </p>
392 <p>
393 Now let's consider another example: Say you wanted to reduce volume of some voices by 3.5 decibel.
394 You remember that was something like <code>change_vol(??note??, ??volume??)</code>,
395 but what would <code>??volume??</code> be exactly? Digging out the docs yet again you
396 find out the correct call was <code>change_vol($EVENT_ID, -3500)</code>.<br>
397 <br>
398 We can do better than that:
399 </p>
400 <p>
401 <code>
402 change_vol($EVENT_ID, -3.5dB)
403 </code>
404 </p>
405 <p>
406 You rather want a slight volume increase by just 56 milli dB instead?
407 </p>
408 <p>
409 <code>
410 change_vol($EVENT_ID, +56mdB)
411 </code>
412 </p>
413 <p>
414 Or let's lower the tuning of a note by -24 Cents:
415 </p>
416 <p>
417 <code>
418 change_tune($EVENT_ID, -24c)
419 </code>
420 </p>
421 <p>
422 I'm sure you got the point. We are naturally using standard measuring
423 units in our daily life without noticing their importance, but they actually help us a
424 lot to give some otherwise purely abstract numbers an intuitive meaning to us.
425 Hence it just made sense to add measuring units as core feature of the NKSP
426 language, their built-in functions, variables and whatever you do with them.
427 </p>
429 <h3>Calculating with Units</h3>
430 <p>
431 Having said that, these examples above were just meant as warm up scenarios.
432 Of course you can do much more with this feature than just passing them
433 literally to some built-in function call as we did above so far.
434 You can assign them to variables, too, like:
435 </p>
436 <p>
437 <code>
438 declare ~pitchLfoFrequency := 1.2kHz
439 </code>
440 </p>
441 <p>
442 You can use them in combinations with integers or real numbers, and of course
443 you can do all mathematical calculations and comparisons that you would
444 naturally be able to do in real life. For instance the following example
445 </p>
446 <code>
447 on init
448 declare $a := 1s
449 declare $b := 12ms
450 declare $result := $a - $b
451 message("Result of calculation is " &amp; $result)
452 end on
453 </code>
454 </p>
455 <p>
456 would print the text <code>"Result of calculation is 988ms"</code> to the terminal
457 (notice that <code>$a</code> and <code>$b</code> actually used different units here).<br>
458 <br>
459 Or the following example
460 </p>
461 <code>
462 on init
463 declare ~a := 2.0mdB
464 declare ~b := 3.2mdB
465 message( 4.0 * ( ~a + ~b ) / 2.0 + 0.1mdB )
466 end on
467 </code>
468 </p>
469 <p>
470 would print the text <code>"10.5mdB"</code> to the terminal.<br>
471 <br>
472 Or let's make this little value comparison check:
473 </p>
474 <p>
475 <code>
476 on init
477 declare ~foo := 999ms
478 declare ~bar := 1s
479 if (~foo &lt; ~bar)
480 message("Test succeeded")
481 else
482 message("Test failed")
483 end fi
484 end on
485 </code>
486 </p>
487 <p>
488 which will succeed of course
489 (notice again that <code>~foo</code> and <code>~bar</code> used different units here as well).<br>
490 <br>
491 So as you can see the units are not just eye candy for your code, they
492 are actually interpreted actively by the script engine appropriately such that all your
493 calculations, comparisons and function calls behave as
494 you would expect them to do from your real-life experience.
495 </p>
497 <h3>Unit Components</h3>
498 <p>
499 In the examples above you might have noticed that the units' components
500 were shown in different colors. That's not a glitch of the website,
501 that's intentional and in fact NKSP code on this website is in general,
502 automatically displayed in the same way as with e.g. Gigedit's instrument
503 script editor. So what's the deal?
504 </p>
505 <p>
506 If you take the value <code>6.8mdB</code> as an example, you have in front
507 the <code>??numeric component?? = 6.8</code> of course, followed
508 by the <code>??metric prefix?? = <span class="up">md</span></code> for
509 "milli deci" (which is always simply some kind of multiplication factor)
510 and finally the fundamental <code>??unit type?? = <span class="ut">B</span></code> for "Bel" (which actually gives the number its final meaning).
511 </p>
512 <p>
513 So here's where language design comes into play. From language point of view both
514 the <code>??numeric component??</code> and the optional <code>??metric prefix??</code>
515 are runtime features which may change at any time,
516 whereas the optional <code>??unit type??</code> is always
517 a constant, "sticky", parse-time feature that you may never change at runtime.
518 That means if you define a variable like e.g. <code>declare $foo := 1s</code>
519 that variable <code>$foo</code> is now firmly tied to the unit type "seconds" for your entire script.
520 You may change the variable's numeric component and metric prefix later on at any time like e.g.
521 <code>$foo := 8ms</code>, but you must not change the variable ever to a different
522 unit type later on like <code>$foo := 8Hz</code>. Trying to switch
523 the variable to a different unit type that way will cause a parser error.
524 </p>
525 <note class="remark">
526 What may look like a lousy limitation of the technical implementation
527 is in fact an intentional language design decision and is actually a feature,
528 called <i>determinism</i>.
529 The price of this limitation of forcing unit types to be a constant parse time
530 feature of variables and expressions comes with the profit of buying substantial
531 error checks at parse time, and that in turn helps you to write more
532 reliable instrument scripts in a shorter amount of time. For instance no
533 matter how complex your mathematical formulas are in your scripts, the parser
534 will always be able to check already at parse-time whether the
535 final, evaluated results of your formulas and overall code that you pass to
536 built-in functions, will finally be of correct unit type expected by the
537 respective function that you are going to call with them as function arguments.
538 Or in other words: the parser is able to check the correct meaning of your formulas at parse-time.
539 So the parser will stop you immediately
540 from doing such and similar mistakes by raising a parser error immediately while you are typing
541 your script code. So you neither
542 have to load the script into the sampler, nor do you have to run and test the
543 code just to spot such kind of mistakes. You will always see them instantly
544 in the code editor.
545 </note>
546 <p>
547 So getting back and proceed with an early example, this code would be fine:
548 </p>
549 <p>
550 <code>
551 on note
552 declare ~reduction := -3.5dB { correct unit type }
553 change_vol($EVENT_ID, ~reduction)
554 end note
555 </code>
556 </p>
557 <p>
558 Whereas the following would immediately raise a parser error:
559 </p>
560 <p>
561 <code>
562 on note
563 declare ~reduction := -3.5kHz { WRONG unit type for change_vol() call! }
564 change_vol($EVENT_ID, ~reduction)
565 end note
566 </code>
567 </p>
568 <p>
569 That's because using the unit type Hertz for changing volume with the
570 built-in function <code>change_vol()</code> does not make any sense,
571 that built-in function expects a unit type suitable for volume changes,
572 not a unit type for frequencies, and hence it is clearly a
573 programming mistake. So getting this error in
574 practice, you may have simply picked a wrong variable by accident for
575 a certain function call for instance and the parser will immediately
576 point you on that undesired circumstance.
577 </p>
578 <p>
579 As another example, you may now also use units with the built-in random number
580 generating function like e.g. <code>random(100Hz, 5kHz)</code>. The function
581 would then return an arbitrary value between <code>100Hz</code> and <code>5kHz</code>
582 each time you call it that way, so that makes sense. But trying e.g. <code>random(100Hz, 5s)</code>
583 would not make any sense and consequently you would immediately get a parser
584 error that you are attempting to pass two different unit types to the <code>random()</code> function,
585 which is not accepted by this particular built-in function.
586 And these kinds of parse-time errors are always detected,
587 no matter whether you are literally passing constant
588 values like in the simple example here, but also through every other means like
589 variables and complex mathematical expressions.
590 </p>
591 <p>
592 The following tables list the unit types and metric prefixes currently supported by <i>NKSP</i>.
593 </p>
594 <p>
595 <table>
596 <tr>
597 <th>Unit Type</th> <th>Description</th> <th>Purpose</th>
598 </tr>
599 <tr>
600 <td><code>s</code></td>
601 <td>short for "seconds"</td>
602 <td>May be used for time durations.</td>
603 </tr>
604 <tr>
605 <td><code>Hz</code></td>
606 <td>short for "Hertz"</td>
607 <td>May be used for frequencies.</td>
608 </tr>
609 <tr>
610 <td><code>B</code></td>
611 <td>short for "Bel"</td>
612 <td>May be used for volume changes.</td>
613 </tr>
614 </table>
616 <table>
617 <tr>
618 <th>Metric Prefix</th> <th>Description</th> <th>Equivalent Factor</th>
619 </tr>
620 <tr>
621 <td><code>u</code></td>
622 <td>short for "micro"</td>
623 <td>10<sup>-6</sup>&nbsp;&nbsp;=&nbsp;&nbsp;0.000001</td>
624 </tr>
625 <tr>
626 <td><code>m</code></td>
627 <td>short for "milli"</td>
628 <td>10<sup>-3</sup>&nbsp;&nbsp;=&nbsp;&nbsp;0.001</td>
629 </tr>
630 <tr>
631 <td><code>c</code></td>
632 <td>short for "centi"</td>
633 <td>10<sup>-2</sup>&nbsp;&nbsp;=&nbsp;&nbsp;0.01</td>
634 </tr>
635 <tr>
636 <td><code>d</code></td>
637 <td>short for "deci"</td>
638 <td>10<sup>-1</sup>&nbsp;&nbsp;=&nbsp;&nbsp;0.1</td>
639 </tr>
640 <tr>
641 <td><code>da</code></td>
642 <td>short for "deca"</td>
643 <td>10<sup>1</sup>&nbsp;&nbsp;=&nbsp;&nbsp;10</td>
644 </tr>
645 <tr>
646 <td><code>h</code></td>
647 <td>short for "hecto"</td>
648 <td>10<sup>2</sup>&nbsp;&nbsp;=&nbsp;&nbsp;100</td>
649 </tr>
650 <tr>
651 <td><code>k</code></td>
652 <td>short for "kilo"</td>
653 <td>10<sup>3</sup>&nbsp;&nbsp;=&nbsp;&nbsp;1000</td>
654 </tr>
655 </table>
656 </p>
657 <p>
658 Of course there are much more standard unit types and metric prefixes than
659 those, but currently we only support those listed above. Simply because
660 I found these listed ones to be actually useful for instrument scripts.
661 </p>
662 <note class="important">
663 When changing tuning, which is commonly expected by musicians in "Cents",
664 like e.g.: <code>change_tune($EVENT_ID, -24c)</code>, you might have noticed
665 already from the markup color here, that this is actually not handled as a unit
666 type by the <i>NKSP</i> language and that's why it is not listed as
667 a unit type in the table above. So tuning changes in "Cents" is actually just a value
668 with metric prefix "centi" and without any unit type, since tuning changes
669 in "Cents" is really just a relative multiplication factor for changing the pitch of
670 a note depending on the current base frequency of the note.<br>
671 <br>
672 This might look a bit odd to you, it is semantically however absolutely correct
673 to handle tuning changes in "Cents" that way by the language. You can still also use expressions like
674 "milli Cents", e.g.: <code>change_tune($EVENT_ID, +324mc)</code>, which is also
675 valid since we (currently) allow a combination of up to 2 metric prefixes with <i>NKSP</i>.<br>
676 <br>
677 The obvious advantage of not making "Cents" a dedicated unit type is that we can
678 just use the character "c" in scripts both for tuning changes, as well as for conventional
679 "centi" metric usage like <code>1cs</code> ("one centi second").
680 The downside of this design decision (that is "Cents" being defined as metric prefix) on the other hand
681 means that we loose the previously described parse-time stickyness feature that we
682 would have with "real" unit types, and hence also loose some of the described
683 error detection mechanisms that we have with "real" unit types at parse time.<br>
684 <br>
685 <u>In practice that means:</u> you need to be a bit more cautious when doing calculations
686 with tuning values in "Cents" compared to other tasks like volume changes, because with every
687 calculation you do in your scripts, you might accidentally drop the "Cents" from your unit, which
688 eventually will cause e.g. the <code>change_tune()</code> function to
689 behave completely differently (since a value without any metric prefix
690 will then be interpreted by <code>change_tune()</code> to be a value in "milli cents",
691 exactly like this function did before introduction of units feature in <i>NKSP</i>).
692 </note>
694 <h3>Unit Conversion</h3>
695 <p>
696 Even though you are not allowed to change the unit type of a variable itself
697 by assignment at runtime, that does not mean there was no way to get rid of
698 units or that you were unable to convert values from one unit type to a
699 different unit type. You can do that very easily actually with <i>NKSP</i>,
700 exactly as you learned in school; i.e. by multiplications and divisions.
701 </p>
702 <p>
703 Let's say you have a variable <code>$someFrequency</code> that you
704 use for controlling some LFO's frequency by script, and for some reason you really
705 want to use the same value of that variable (for what reason ever)
706 to change some volume with <code>change_vol()</code>, then all you have
707 to do is dividing the existing unit type away, and multiplying it
708 with the new unit type:
709 </p>
710 <p>
711 <code>
712 on note
713 declare $someFrequency := 100Hz
714 change_vol($EVENT_ID, $someFrequency / 1Hz * 1mdB)
715 end note
716 </code>
717 </p>
718 <p>
719 Which would convert the variable's original value <code>100Hz</code>
720 to <code>100mdB</code> before passing it to the <code>change_vol()</code>
721 function. So this actually did 3 things:
722 </p>
723 <p>
724 <ol>
725 <li>the divsion (by <code>/ 1Hz</code>) dropped the old unit type (Hertz),</li>
726 <li>the multiplication (by <code>* 1mdB</code>) added the new unit type (Bel)</li>
727 <li>and that multiplication also changed the metric prefix (to milli deci) before the result is finally passed to the <code>change_vol()</code> function.</li>
728 </ol>
729 </p>
730 <p>
731 And since <code>change_vol()</code> would now receive the value
732 in correct unit type, this overall solution is hence legal and accepted by the parser without any complaint.
733 And this type of unit conversion does not break any parse-time determinism
734 and error detection features either, since it is not touching the variable's
735 unit type directly (only the temporary value eventually being passed to the <code>change_vol()</code> function here),
736 and so the result of the unit conversion expressions above
737 can always reliably be evaluated by the parser at parse-time.
738 </p>
739 <note class="important">
740 There are some intended limitations when performing unit type conversions though.
741 For instance you are never allowed to multiply some unit type with another unit type
742 in <i>NKSP</i>, neither different unit types like e.g. <code>100Hz * 1B</code>, nor
743 with the same unit type like e.g. <code>4s * 8s</code>. That's because we don't have
744 any practical usage for e.g. "square seconds" or other kinds of mixed unit types
745 in instrument scripts.
746 So trying to create a number or variable with more than one unit type will always
747 raise a parser error. So keep that in mind and use common sense when writing
748 calculations with units. And like always: the parser will always point you on
749 misusage immediately.
750 </note>
752 <h3>Array Variables</h3>
753 <p>
754 And as we are at limitations regarding units:
755 Currently <b>unit types</b> are not accepted for array variables yet. <b>Metric prefixes</b>
756 are allowed though!
757 </p>
758 <p>
759 <code>
760 declare %foo[4] := ( 800, 1m, 14c, 43) { OK - metric prefixes, but no unit types }
761 declare %bar[4] := ( 800s, 1ms, 14kHz, 43mdB) { WRONG - unit types not allowed for arrays yet }
762 </code>
763 </p>
764 <p>
765 Main reason for that current limitation is that unlike with scalar variables,
766 accessing array variables at runtime with an index by yet another (runtime changeable)
767 variable might break the previously described parse-time determinism of unit types.
768 That means if we just take the array variable <code>%bar[]</code> declared above
769 and would access it in our scripts with another variable like:
770 </p>
771 <p>
772 <code>
773 %bar[$someVar]
774 </code>
775 </p>
776 <p>
777 then what would that unit type of that array access be? Notice that the array variable
778 <code>%bar[]</code> was initialized with 3 different unit types for its individual elements.
779 So the unit type of the array access would obviously depend on the precise
780 value of variable <code>$someVar</code>, which most probably will change at runtime and
781 hence the compiler would not know at parse-time yet.
782 </p>
783 <note class="remark">
784 This limitation will most probably be lifted later on by allowing exactly one unit type
785 for an array variable, so that the array would be initialized with exactly the same unit
786 type for all its elements to retain the parse-time determinism that we were talking about.
787 </note>
789 <h2>Finalness</h2>
790 <p>
791 Here comes another new core language feature of <i>NKSP</i> that you certainly don't
792 know from <i>KSP</i> (as it does not exist there), and which definitely requires an
793 elaborate explanation of what it is about: "finalizing" some value.
794 </p>
796 <h3>Default Relativity</h3>
797 <p>
798 When changing synthesis parameters, these are commonly <i>relative</i> changes, depending
799 on other modulation sources. For instance let's say you are using <code>change_vol()</code>
800 in your script to change the volume of voices of a note, then the actual, final volume
801 value being applied to the voices is not just the value that you passed to <code>change_vol()</code>,
802 but rather a combination of that value and values of other modulation sources of volume
803 like a constant volume factor stored with the instrument patch, as well as a continuously
804 changing value coming from an amplitude LFO
805 that you might be using in your instrument patch, and you might most certainly also use
806 an amplitude envelope generator which will also have its impact on the final volume of course.
807 All these individual values are multiplied with each other in real-time by the sampler's engine core
808 to eventually calculate the actual, final volume to be applied to the voices, like illustrated in the following
809 schematic figure.
810 </p>
811 <img src="nksp_multi_mods_rel.png" caption="Relative Modulation (Default Behaviour)">
812 <p>
813 This <i>relative</i> handling of synthesis parameters is a good thing, because multiple
814 modulation sources combined make up a vivid sound. However there are situations where this
815 combined behaviour for synthesis parameters is not what you want. Sometimes you want to be
816 able to just say in your script e.g. "Make the volume of those voices exactly -6dB. Period. I mean it!".
817 And that's exactly what the newly introduced "final" operator <code>!</code> does.
818 </p>
820 <h3>Final Operator</h3>
821 <p>
822 <code>
823 on note
824 declare $volume := -6dB
825 change_vol($EVENT_ID, !$volume) { '!' makes value read from variable $volume to become 'final' }
826 end note
827 </code>
828 </p>
829 <p>
830 By prepending an exclamation mark <code>!</code> in front of an expression as shown in the code above,
831 you mark that value of that expression to be "final",
832 wich means the value will bypass the values of all other modulation sources, so the
833 sampler will ignore all other modulation sources that may exist, and
834 will simply use your script's value exclusively for that synthesis parameter,
835 as illustrated in the following figure:
836 </p>
837 <img src="nksp_multi_mods_fin.png" caption="Force 'Finalness' by Script">
838 <p>
839 You can of course revert back at any time to let the sampler process that synthesis parameter
840 relatively again by calling <code>change_vol()</code> and just passing
841 a value for volume without "finalness" (i.e. without <code>!</code> operator) this time.
842 </p>
843 <p>
844 In the previous code example, the "finalness" was applied to the temporary value
845 being passed to the <code>change_vol()</code> function, it did not change
846 the information stored in variable <code>$volume</code> at all though. So this is different
847 from:
848 </p>
849 <p>
850 <code>
851 on note
852 declare $volume := !-6dB { store 'finalness' directly to variable $volume }
853 change_vol($EVENT_ID, $volume)
854 end note
855 </code>
856 </p>
857 <p>
858 In the latter code example the actual "finalness" is stored directly now
859 to the <code>$volume</code> variable instead. Both approaches
860 make sense depending on the actual use case. For instance if you only
861 need "finalness" in rare situations, then you might use the prior
862 solution by using the "final" operator just with the respective function call,
863 whereas in use cases where you would always apply the
864 <code>$volume</code> "finally" and probably need to pass it to several
865 <code>change_vol()</code> function calls at several places in your script,
866 then you might store the "finalness" directly to the variable instead.
867 </p>
868 <note class="remark">
869 <i>KSP</i> is also using the exclamation mark in front of variable names of string arrays.
870 Our usage of the exclamation mark character for this "finalness" feature
871 does not cause a language conflict with
872 that aspect though, because variable names (i.e. containing exclamation mark) are
873 resolved by the language before our unary <code>!</code> "final" operator is resolved in
874 expressions.
875 </note>
877 <h3>Mixed Finalness</h3>
878 <p>
879 Like with the other new language features described previously above, we also
880 have some potential ambiguities that we need to deal with when applying "finalness".
881 For instance consider this code:
882 </p>
883 <p>
884 <code>
885 on note
886 declare $volume := !-6dB { store 'finalness' directly to variable $volume }
887 change_vol($EVENT_ID, $volume + 2dB) { raises parser warning here ! }
888 end note
889 </code>
890 </p>
891 <p>
892 Should the resulting, expected volume change of <code>-4dB</code> be applied as
893 "final" value or as <i>relative</i> value instead?
894 Because the problem here is that <code>!-6dB</code> obviously means "final",
895 whereas </code>+ 2dB</code> is actually a <i>relative</i> value to be added.
896 </p>
897 <p>
898 In the current version of the sampler the value to be applied in this case would be "final", so you will not get a parser error,
899 however you will get a parser warning to make you aware about this ambiguity.
900 So to fix the example above, that is to to get rid of that parser warning, you can simply add an exclamation
901 mark in front of the other number as well like:
902 </p>
903 <p>
904 <code>
905 on note
906 declare $volume := !-6dB { store 'finalness' directly to variable $volume }
907 change_vol($EVENT_ID, $volume + !2dB) { '!' fixes parser warning }
908 end note
909 </code>
910 </p>
911 <p>
912 Also built-in functions will behave similarly as described above. Certain built-in functions
913 accept <i>finalness</i> for all of their arguments, some functions accept <i>finalness</i> for only certain
914 arguments and some functions won't accept <i>finalness</i> at all. Like with the other new core language
915 features always use common sense and quickly think about whether it would make sense if a
916 certain function would accept <i>finalness</i> for its argument(s). Most of the time your guess will be
917 right, and if not, then the parser will tell you immediately with either an error or warning, and the
918 <a href="01_nksp_reference.html">NKSP built-in functions reference</a> will help you out with
919 details in such rare cases where things might not be clear to you immediately.
920 </p>
922 <h3>Implied Finalness</h3>
923 <p>
924 Here comes the point where the feature circle of this article closes: the unit type "Bel" used
925 in the examples for the "final" operator above is somewhat special, since the unit type "Bel" is
926 in general used for <i>relative</i> quantities like i.e. volume changes. Tuning changes (i.e. in "Cents") are
927 also relative quantities.
928 </p>
929 <p>
930 However other unit types like "seconds" or "Hertz" are <i>absolute</i>
931 quantities. That means if you are using unit types "Hertz" or "seconds" in your scripts, then their
932 values are automatically applied as <i>implied</i> "final" values, as if you were using the <code>!</code>
933 operator for them in your code. The parser will raise a parser warning though to point you on that
934 circumstance.
935 </p>
936 <p>
937 The following table outlines this issue for the currently supported unit types.
938 </p>
939 <p>
940 <table>
941 <tr>
942 <th>Unit Type</th> <th>Relative</th> <th>Final</th> <th>Reason</th>
943 </tr>
944 <tr>
945 <td>None</td>
946 <td>Yes, by default.</td>
947 <td>Yes, if <code>!</code> is used.</td>
948 <td>If no unit type is used (which includes if <b>only</b> a metric prefix is used like e.g. <code>change_tune($EVENT_ID, -23c)</code>) then such values can be used both for relative, as well as for 'final' changes.</td>
949 </tr>
950 <tr>
951 <td><code>s</code></td>
952 <td>No, never.</td>
953 <td>Yes, always.</td>
954 <td>This unit type is naturally for absolute values only, which implies its value to be always 'final'.</td>
955 </tr>
956 <tr>
957 <td><code>Hz</code></td>
958 <td>No, never.</td>
959 <td>Yes, always.</td>
960 <td>This unit type is naturally for absolute values only, which implies its value to be always 'final'.</td>
961 </tr>
962 <tr>
963 <td><code>B</code></td>
964 <td>Yes, by default.</td>
965 <td>Yes, if <code>!</code> is used.</td>
966 <td>This unit type is naturally for relative changes. So this unit type can be used both for relative, as well as for 'final' changes.</td>
967 </tr>
968 </table>
969 </p>
970 <note class="remark">
971 Since unit types like <i>seconds</i> and <i>Hertz</i> are naturally always used for absolute values
972 in real life,
973 it might be considerable to drop the mentioned parser warnings which currently occur
974 if those units are used in scripts without having used the <code>!</code> operator.
975 </note>
977 <h3>Array Variables</h3>
978 <p>
979 As with unit types, the same current restriction applies to "finalness" in conjunction with
980 array variables at the moment: you may currently <b>not</b> apply "finalness" to the elements of array variables yet.
981 </p>
982 <p>
983 <code>
984 declare %foo[3] := ( !-6dB, -8dB, !2dB ) { WRONG - finalness not allowed for arrays (yet) ! }
985 </code>
986 </p>
987 <p>
988 The reason is also exactly the same, because <i>finalness</i> is a parse-time required information
989 and an array access by using yet another variable like e.g. <script>%foo[%someVar]</script> might
990 break that parse-time awareness of "finalness" for the compiler.
991 </p>
992 <note class="remark">
993 Likewise we might certainly lift that restriction later on by
994 allowing <i>finalness</i> to be applied to arrays by initializing <b>all</b> members of an array to be all "final".
995 </note>
997 <h2>Backward Compatibility</h2>
998 <p>
999 You might be asking, what do those new features mean to your existing instrument scripts,
1000 do they break your old scripts?
1001 </p>
1002 <p>
1003 The clear and short answer is:&nbsp;&nbsp;&nbsp;<b>No</b>, of course <u>they do <b>not</b> break your existing scripts</u>!
1004 </p>
1005 <p>
1006 Our goal was always to preserve constant behaviour for existing sounds,
1007 so that even ancient sound files in GigaSampler v1 format still would sound
1008 exactly as you heard them originally for the 1st time many years ago (probably with GigaSampler at that time).
1009 And that means the same policy applies to instrument scripts as well of course.
1010 </p>
1011 <p>
1012 You can also arbitrarily mix your existing instrument scripts by just partly using the new
1013 features described in this article at some sections of your scripts, while
1014 at the same time preserving your old code at other sections. So these features
1015 are designed that they won't break anything existing, and that they always
1016 collaborate correctly in a mixed way with old <i>NKSP</i> code.
1017 </p>
1019 <h2>Status Quo</h2>
1020 <p>
1021 That's it! For now ...
1022 </p>
1023 <p>
1024 This is the current development state regarding these new <a href="01_nksp.html">NKSP</a>
1025 core language features. It might not be the final word though. I am aware certain
1026 aspects that I decided can be argued about (or maybe even entire features).
1027 And that's actually one of the reasons why I decided to write this (even for my habits)
1028 quite long and detailed article, describing also the reasons for individual language design
1029 decisions that I took.
1030 </p>
1031 <p>
1032 You can however share your thoughts and arguments about these new features with us
1033 on the <a href="https://sourceforge.net/projects/linuxsampler/lists/linuxsampler-devel">mailing list</a>
1034 of course!
1035 </p>
1036 <note class="important">
1037 Keep in mind, the earlier you come up with suggestions for changes, the higher the chance
1038 that it might actually become changed and vice versa!&nbsp;&nbsp;&nbsp;(See "Backward Compatibility" above)
1039 </note>
1040 </body>
1041 </html>

  ViewVC Help
Powered by ViewVC