# KSP Math Library Update



## Big Bob (Apr 24, 2015)

Hi Scripters,

V700 of the KSP Math Library has been updated to V701.

There is a new bi-directional engine converter *epDlyTime* which converts send FX delay time T in the range from 5.00 to 2500.00 msec to/from the equivalent engine parameter.

There are also 6 new conditional predicates:

pGT(a,b)	for a > b
pGTE(a,b)	for a >= b
pEQ(a,b)	for a = b
pLT(a,b) for a < b
pLTE(a,b)	for a <= b
pNEQ(a,b)	for a # b

All these are one-line functions and therefore the KSE allows you to use them inline like native KSP functions. Each predicate returns a value of 1 if the condition is true and a value of 0 if the condition is false. 

V701 is available from my website here:

http://www.bigbobsmusicworld.com/kontak ... th-library

Rejoice,

Bob


----------



## d.healey (Apr 25, 2015)

Thanks Bob!


----------



## FrozenPlain (Apr 25, 2015)

Great stuff, thanks Bob!


----------



## d.healey (Apr 25, 2015)

Is there a function similar to VR_to_mdb but for tuning. I want to perform, for want of a better phrase, a pitch crossfade. This I can do linearly using a loop and change_tune but I'd like to do it following the values produced by your EP_XFade function.

I want to provide a tuning value in millicents and tune one note to that tuning value from 0 and tune the second note from 0 to the opposite of the tuning value.

Example:

If I provide my desired function with a tuning value of 10000 the following should occur as the value provided to EP_XFade swings from 0-1000.

Note A's tuning goes from 0 to 10000mc and note B from -10000mc to 0.

If I give a negative value such as -10000 then
Note A's tuning goes from 0 to -10000mc and note B from 10000mc to 0.


----------



## Big Bob (Apr 25, 2015)

Hi David,

I need a little more info before I can respond to this.

1. When you say you want it to follow my EP_XFade function do you mean that literally or that you just want to use sine/cosine shaping? For example, do you also want to retain the morphing control?

2. Next you need to define what you mean by 'follow'. What is the desired functional relationship you want between VR and tuning?

For example, using the sine function. When the control parameter is 0, 500, or 1000, the values of VR will be 0, 7071, or 10000 (with no morphing). If your tuning range is 0 to 10000mc, what do you want the tuning to be when the cosine is at 0.70711 (the 500 control input point)? 

If you just literally want some kind of a VR_to_mc converter, you first need to specify the transfer function mathematically in some way.

Rejoice,

Bob


----------



## d.healey (Apr 25, 2015)

Thanks for the quick response Bob. Yes I would like to make use of the morphing values, but if it's easier to just use the sine/cosine functions than the xfade to achieve this I'm happy to do it that way.

If I was doing it linearly at the half way point (500 control input) one of the notes would be tuned at 5000mc and the other at -5000mc.

Let me show you what I've been working on - the magic_maths_function() is the piece I'm stuck with - the maths bit 


```
function nc.pitch_crossfade(value, mv, note_ids, pitch)

    declare $i
    declare val[2]

    EP_XFade(value, mv, val[1], val[0])

    for $i := 0 to num_elements(val)-1
        val[$i] := magic_maths_function(val[$i], pitch) {Convert the XFade value to a change_tune value}
        change_tune(note_ids[$i], val[$i], 0)
    end for

end function
```



> If you just literally want some kind of a VR_to_mc converter, you first need to specify the transfer function mathematically in some way.


If I can skip the VR stage that would be good, I'm just using it because of the convenience of your xfade function


----------



## Big Bob (Apr 25, 2015)

Hi David,

Your requirement is still a little unclear to me * but, it sounds like you want the tuning values to be proportional the the VR values? For example if *pitch* is specified as 6000mc, the following tables would describe the situation?

```
VR1       VR2     Tune_A   Tune_B
     0      10000          0      -6000
  5000     8666       3000      -5196
  7071     7071       4242      -4242
 10000        0        6000          0
```

BTW the above VR values are what EP_XFade would output with xv = 0, 333, 500, and 1000 respectively with morphing off.


If that's what you want, you can compute Tune_A and Tune_B as follows:

Tune_A := VR1*pitch/10000
Tune_B := -VR2*pitch/10000

If this isn't what you are after, perhaps you could explain the function you want using a crude table of values like the above to convey your thoughts?

* calling it a magic_maths_function didn't help too much :D 

Rejoice,

Bob


----------



## d.healey (Apr 25, 2015)

Thanks Bob that looks like it should do the trick. I'll try it out soon and post an update. What I'm using it for is a legato type function, not dissimilar to the one you discuss in the SIPS manual.

Update:
I just tried it out and seems to be working perfectly. Thanks again!


----------



## mk282 (May 1, 2015)

There's a bug in v700 and v701 of math lib.

In M.DefMathConst macro, IllegalAng90 array is declared wrongly:


```
if Ang90 # 1000 and Ang90 # 10000 and Ang90 # 900 and Ang90 # 9000
    declare IllegalAng90[0]  { report illegal angular unit }
    IllegalAng90[1] := Ang90 { only 900, 1000, 9000, and 10000 are valid }
  end if
```

This makes math lib fail to compile because an array cannot be declared with size 0!


Not sure how you guys managed to compile it, I couldn't unless I changed the array size from 0 to 1 (at least - it should probably be size 2, no?).


----------



## d.healey (May 1, 2015)

Good catch. I haven't tried the latest version yet so haven't experienced the error


----------



## Big Bob (May 1, 2015)

> There's a bug in v700 and v701 of math lib.



*I don't think this is a bug*.

As I recall, it was written this way intentionally to avoid creating illegal Angle constants due to entering illegal Angle unit requests in SetMathMode. The array size of zero was a tricky way to get Kontakt to flag the error with a message including some finger-pointing text. However, if you are getting this error, it must be because you are either entering an illegal value unit in SetMathMode or you don't have 'Optimize compiled code' enabled in the KSE.

But, my memory of exactly how this works is a little hazy, so let me look into it and I'll post about this again.

to be continued ...

Bob


----------



## Big Bob (May 1, 2015)

*OK. It's definitely not a bug.  *

When you specify the desired angular unit with *SetMathMode* you are supposed to use one of the symbolic constants DG, CG, DD, or CD. But, since DG is the legacy angular unit, for convenience, I arranged it so that using 0 is equivalent to using DG. But internally, these specifiers are converted to the corresponding legal *Ang90* values of 1000, 10000, 900 and 9000 respectively.

However, if you enter some arbitrary value besides 0 or one of the 4 symbolic constants, for example something like *SetMathMode(0,45)*, I have to flag it some way or pandomonium may result at runtime. Since the library is an import module I have no convenient access to your host script control panel. So, if I detect an illegal entry with SetMathMode, about the only thing I could do is report it as a status line message. But those are often not seen or overwritten by later-occuring messages.

So, I used the code you are questioning to flag the problem when you try to compile your F5'ed script in Kontakt. When Kontakt highlights the illegal array size specifier, you get to see the name of the array '*IllegalAng90*' which should tell you what you did wrong. :lol: 

If your angle specifier is actually OK, then the KSE will eliminate the code line that tries to compile the zero-size array before it ever gets to Kontakt. If it doesn't, then you must have the 'Optimize compiled code' option turned off which is a no-no with the Math Library (see the *Extremely Important* Red-Box text on page 3 of the User Guide). :roll: 

Rejoice,

Bob


----------



## mk282 (May 2, 2015)

Well, I don't use "Optimize compiled code" option because it messes with some other stuff in my scripts... I guess that means completely not using math lib from now on, or simply disregarding this IllegalAng90 thing and removing that check completely, since I'm not that stupid to use a wrong angle identifier.


----------



## Big Bob (May 2, 2015)

> I guess that means completely not using math lib from now on



I guess that's what it means all right. The library takes full advantages of conditional compilation and many other things provided by code optimization. I wouldn't even want to guess at all the things that won't work correctly with this option disabled (let alone all the bloated code that will be generated).


----------



## mk282 (May 2, 2015)

Well, in all honesty, I don't do a ton of things that necessitate the math lib. If I do, I usually get away with generating the necessary data in a lookup array and go with that.

Good to know that I need to have to use Optimize compiled code switch (not sure how I missed that in the manual - and I usually do read them!). Oops. 


For the time being, I'm going to disregard this illegal ang unit thing.


----------



## Big Bob (May 2, 2015)

> Good to know that I need to have to use Optimize compiled code switch (not sure how I missed that in the manual - and I usually do read them!). Oops.



Sorry about that, but this has been a requirement of using the math library for years now, ever since Nils added code optimization to the KSE. And, I don't know how I can make it any more obvious in the User Guide :? 



> Well, in all honesty, I don't do a ton of things that necessitate the math lib. If I do, I usually get away with generating the necessary data in a lookup array and go with that.



Different strokes for different folks. If you want to use a tool, you have to play by the rules of using that tool or else do it some other way (without the tool) and it sounds like that route is well-traveled for you. :D


----------



## mk282 (May 3, 2015)

Scratch that, I'm an idiot. Compiling stuff that uses math lib over here does work nicely even with OCC switch.

It only barfs on some scripts when I enable Extra syntax checks. So I leave that off. I confused the two options somehow. ~o) 


So, looks like I can freely continue to use the math lib when necessary


----------



## Big Bob (May 3, 2015)

> Compiling stuff that uses math lib over here does work nicely even with OCC switch.



Mario, most things should compile without OCC but, many things may be compromised in their runtime behavior. The most notable thing of course will be bloated code but there are other things. Because, like all my code, the library is written with the assumption that OCC will be enabled.

Apart from the Math Library, I think you should seriously reconsider turning off OCC. While it is true that it sometiimes tidies up things a little too agressively, such that it may undo something you were trying to do with the way you coded it, these situations are truly rare and there are always easy work-arounds for them.

On the other hand, the OCC does so many wonderful things that I wouldn't want to give it up. Just the conditional compilation feature alone is worth its weight in gold. Why carry 'dead' if clauses and such into your runtime code? If anything can be done at compile time, why burden the runtime code with it?

The Math library provides many user options but once you choose which ones you want, why burden the runtime code with all the code for the unused options?

When OCC was first added, I too ran into a few areas where something I coded would be countermanded by the OCC machinery. But, rather than give up all the wonderful new services of the OCC, I just changed some of my coding habits. Then, I cultivated new habits to take advantage of the OCC rather than fight it.

LIke I said, different strokes for different folks but I personally never run without it.



> It only barfs on some scripts when I enable Extra syntax checks. So I leave that off.



Yes, this option can also interfere with some of my coding intents at times. But, currently *OCC can't be enabled if ESC is disabled*. So again, I've learned to work-around the few situations that occasionally arise.



> It only barfs on some scripts when I enable Extra syntax checks. So I leave that off.



I'm glad you feel you can still get some benefit from the library but I think you had better take a quick look at the compiled code when you use it without OCC. And then, travel at 
your own risk :lol:

Rejoice,

Bob


----------



## polypx (May 3, 2015)

I have to keep ESC off as well, because some commands for Kontakt 5 won't compile if it's on. (eg. the mf_set_export_area example in the KSP guide complains about non integer value) 

Luckily up till now I haven't had to use the Math Library and those few prolematic commands in the same script. But I suppose you could always compile different parts of the script and join them together using "import".


----------



## Big Bob (May 3, 2015)

Hi Dan,



> I have to keep ESC off as well, because some commands for Kontakt 5 won't compile if it's on. (eg. the mf_set_export_area example in the KSP guide complains about non integer value)



Sorry to hear that. Unfortunately, I'm stuck back at K5.1 because I'm still on XP so I don't know anything about some of the newer K5 stuff. But, I've decided I'm too old to move forward with another OS this late in life :lol: 



> Luckily up till now I haven't had to use the Math Library and those few prolematic commands in the same script. But I suppose you could always compile different parts of the script and join them together using "import".



Yes, that probably would work but its unfortunate that one should have to go through that extra work.

*I wonder if Nils knows about these problems and may have a fix for them?*

Rejoice,

Bob


----------



## mk282 (May 3, 2015)

In SublimeKSP, OCC can be enabled separately from ESC (I don't use KSE anymore, SublimeKSP is so much better).

And I have OCC enabled now for good. Works just fine. Sorry for the false alarm. :oops:


----------



## Big Bob (May 3, 2015)

> In SublimeKSP, OCC can be enabled separately from ESC (I don't use KSE anymore, SublimeKSP is so much better).



Hey Mario, I didn't know that, and that's great news :mrgreen: . I have long wished that these two would be decoupled. Now I may finally have a good reason to switch to the Sublime KSE. 



> And I have OCC enabled now for good. Works just fine. Sorry for the false alarm



Maybe it's a good thing you did, otherwise I might not have found out about the OCC and ESC de-coupling in Sublime KSE. 8) 

*And Dan*, your problem with mf_set_export_area also sounds more like its caused by the ESC (extra syntax checks) option. If so, can't you also just turn ESC off to work around it?

I'm pretty sure you must be using the Sublime KSE since you are on a Mac, no?

Rejoice,

Bob


----------



## Big Bob (May 3, 2015)

Hey Mario,

I just fired up the Sublime KSE and ran a quick check. While it does allow me to turn off ESC and still leave OCC enabled, it doesn't function properly. Since I have what is probably an early version, I downloaded V1.1 from Nils' site. But the readme file has a .md extension and I have no idea how to read it.

Can you shed any light on this?

Rejoice,

Bob


----------



## mk282 (May 3, 2015)

It opens in Notepad just fine.


----------



## Big Bob (May 4, 2015)

> It opens in Notepad just fine.


 Oops! Never even tried :oops: 

But, I've got bad news!

The Sublime KSE is no different than V1.52. If you turn off ESC, it also disables OCC (even though it doesn't indicate it). At least that's what it does for me here.

Try this easy test. Compile this simple script with both ESC and OCC enabled and you'll get about 68 lines of code in the clipboard. Then turn off ESC and recompile it and the code bloats to about 342 lines. This is the same as with the OCC disabled so I conclude that OCC is not active unless ESC is active. And, that's how V152 works.

*import* "KSPMathV700.ksp"

*on init*
``message('')
``set_script_title('Offset Method')
``SetMathMode(0,DG)
``*declare* ui_value_edit SyncTime(0,100000,1000) _{ 0 .. 100.000 sec }_
````SyncTime->width := 130
````move_control_px(SyncTime,100,0)
````set_text(SyncTime,'Sync Time (secs)')
````SyncTime := 10000
``*declare* hi_key := 72
``*declare* bias _{ SS offset time in usec }_
``*declare* F.XH _{ F.X / F.H }_
``make_persistent(SyncTime)
*end on*

*on note*
``ignore_event(EVENT_ID)
``F.XH := F(EVENT_NOTE,hi_key)
``bias := (10000 - F.XH)*SyncTime/10``_{ offset = (1 - F.XH)*S }_
_{ message(bias) }_
``play_note(EVENT_NOTE,EVENT_VELOCITY,bias,-1) 
*end on*

_{-------------------- support functions ---------------------}_
*function* F(n1,n2)->result``_{ ratio of F.1/F.2 for notes n1 and n2 }_
``result := Exp2(250000*(n1-n2)/3 + 13287712)``_{ scaled by 10^4 }_
*end* *function*


I guess the only difference between the Sublime version and V152 is Sublime doesn't 'indicate' that OCC is disabled while V152 grays out the option.

If you get something different when performing this test, please let me know. I may be using Sublime incorrectly.

Rejoice,

Bob


----------



## polypx (May 4, 2015)

I have the same result, turning of ESC bloats the output to 342 lines. In Sublime Text.

And yes, the mf_set_export_area is caused by the ESC I believe. So I *usually* leave it off now unless I'm using the Math Library.

cheers
Dan


----------



## Big Bob (May 4, 2015)

Thanks for the confirmation Dan. 

I've sent an email to Nils to see if he can do anything about decoupling the ESC from the OCC or changing the ESC so it will not get in the way of some of these newer constructs.

But, knowing how busy he is, I guess we shouldn't hold our breath :lol: 

Rejoice,

Bob


----------



## gh (May 4, 2015)

Dan, you can easily fix this by changing the ksp_builtins_data.py to mf_set_export_area(<name>,<start-pos>,<end-pos>,<start-track>,<end-track>):integer

On a PC you find this file in C:\Users\user-name\AppData\Roaming\Sublime Text 3\Packages\SublimeKSP\ksp_compiler3

The return value is also missing on some other functions.


----------



## Big Bob (May 4, 2015)

Hi Gunter, 

I don't have a late enough version of K5 to try this but, do I presume correctly that when you add the missing stuff to the built-ins, you can then enable ESC (along with OCC) again without problems?

If so, maybe doing this sort of thing would fix Mario's problems with the ESC also?

Anyway, thanks for sharing.

Rejoice,

Bob


----------



## gh (May 4, 2015)

Hi Bob!
Yes, if you add the missing stuff to the built-ins you can use ESC and OCC without problems.

Günter


----------



## polypx (May 4, 2015)

Gunter,

Ah ha... I vaguely knew about that, but I thought I'd tried and it didn't work. Will try again, thanks!

cheers, Dan


----------



## kotori (May 4, 2015)

polypx @ Mon May 04 said:


> I have the same result, turning of ESC bloats the output to 342 lines. In Sublime Text.
> 
> And yes, the mf_set_export_area is caused by the ESC I believe. So I *usually* leave it off now unless I'm using the Math Library.
> 
> ...



Perhaps the function signature is simply wrong for mf_set_export_area. If you use the SublimeKSP plugin, select the menu item Preferences -> Browse Packages. Open the folder SublimeKSP and then the subfolder ksp_compiler3. Then open ksp_builtins_data.py in some text editor (eg. Sublime Text) and search for mf_set_export_area. If you rely on the return value you may have to add ":integer" (without the quotes) at the end of that line. Then save and restart Sublime Text.

cheers,
Nils


----------



## polypx (May 5, 2015)

Thanks Nils!


----------

