c09890c8c38ba6318ebfc0de3c782120f1b75350
[feisty_meow.git] / huffware / huffotronic_scripts / jaunt_config_funcs_v2.9.txt
1 
2 // huffware script: jaunt config funcs, by fred huffhines, released under GPL license.
3 //
4 // this is the part of the jaunt wik rez ensemble that deals with configuration.
5 // it reads the configuration from notecards and passes it to the main script.
6 //
7 // this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
8 // do not use it in objects without fully realizing you are implicitly accepting that license.
9 //
10
11 //////////////
12
13 integer DEBUGGING = FALSE;
14     // make this true for noisy runtime diagnostics.
15
16 // defines the jaunt config funcs messaging API.
17 //////////////
18 // do not redefine these constants.
19 integer JAUNT_CONFIGURATION_HUFFWARE_ID = 10022;
20     // the unique id within the huffware system for this script's commands.
21     // it's used in llMessageLinked as the num parameter.
22 string HUFFWARE_PARM_SEPARATOR = "{~~~}";
23     // this pattern is an uncommon thing to see in text, so we use it to separate
24     // our commands in link messages.
25 string HUFFWARE_ITEM_SEPARATOR = "{|||}";
26     // used to separate lists of items from each other when stored inside a parameter.
27     // this allows lists to be passed as single string parameters if needed.
28 integer REPLY_DISTANCE = 100008;  // offset added to service's huffware id in reply IDs.
29 //////////////
30 // commands available from the jaunt config library:
31 string LOAD_ALL_CONFIGURATIONS = "#rdcfg#";
32     // this starts the process of loading jaunt destinations from the notecards and
33     // landmarks that we find in the object.  the parms are: private channel
34     // and conveyance mode.
35 string JAUNT_CFG_DATA_EVENT = "#yodata#";
36     // this event is generated from this script back to the caller.  when we have some
37     // landmark data or configuration information, it's passed back in chunks.  the
38     // deluge of pieces will continue until the JAUNT_CFG_EOF event is passed.  the
39     // parameters include packed destination name and vector pairs (which form 2 elements
40     // in the list) and packed config variable definitions (where config items start
41     // with a colon, and the definition is only one element in the list).
42 string JAUNT_CFG_EOF = "#done#";
43     // sent after all valid configuration items that we could find were processed.  there
44     // are no parameters for this command.
45 //
46 //////////////
47
48 // important constants used internally...  these should generally not be changed.
49
50 // indicates a reconnaissance command when found as a prefix on chat text
51 // on our official recon channel.
52 string RECON_TEXT = "#rcn";
53 string READY_TEXT = "-y";  // lets us know that a jaunter is ready to be filled.
54 string RETURN_WORD = "-b";  // used to signal a returning recong jaunter.
55
56 integer MAXIMUM_BLAST_SIZE = 6;  // maximum number of config items per blurt.
57
58 integer TIMEOUT_FOR_CONFIGURATION_PROCESS = 42;
59     // how long the notecard and lm reading processes are allowed to last.
60
61 integer TWO_WAY_TRIP = 1;
62 integer AUTOREZ_JAUNTER = 2;
63 integer ONE_WAY_TRIP = 3;
64 integer RECONNAISSANCE_TRIP = 4;
65
66 string DB_SEPARATOR = "``";  // separating items in lists.
67
68 //////////////
69
70 // global variables.
71
72 integer unused_private_chat_channel;  // where sub-jaunters communicate with root.
73
74 integer conveyance_mode;  //// = TWO_WAY_TRIP;
75     // default is a standard two way trip, there and back again.  note that the object
76     // will fail to return if any lands in between are blocking object entry.  those
77     // situations should use an auto-rez jaunter, which is specified by prefixing the
78     // target vectors with AR.
79
80 ////integer current_target_index;  // the location in the list that we would currently jaunt to.
81
82 list config_to_blast;  // what we will send to our client.
83
84 // notecard variables...
85 integer response_code;  // set to uniquely identify the notecard read in progress.
86 string leftover_parms;  // items leftover during config.
87
88 // lm variables...
89 integer current_lm;
90 key lm_data_req;  // this is the current landmark being served as data.
91
92 //////////////
93
94 // requires noteworthy library v5.4 or higher.
95 //////////////
96 // do not redefine these constants.
97 integer NOTEWORTHY_HUFFWARE_ID = 10010;
98     // the unique id within the huffware system for the noteworthy script to
99     // accept commands on.  this is used in llMessageLinked as the num parameter.
100 string BAD_NOTECARD_INDICATOR = "bad_notecard";
101     // indicates that the notecard reading process has failed to find an appropriate one.
102 //string BUSY_READING_INDICATOR = "busy_already";
103     // this return value indicates that the script is already in use by some other script.
104     // the calling script should try again later.
105 string NOTECARD_READ_CONTINUATION = "continue!";
106     // returned as first parameter if there is still more data to handle.
107 // commands available via the noteworthy library:
108 string READ_NOTECARD_COMMAND = "#read_note#";
109     // command used to tell the script to read notecards.  needs a signature to find
110     // in the card as the only parameter.  the signature can be empty or missing.
111     // the results will be fired back as the string value returned, which will have
112     // an embedded list that was read from the notecard.  this necessarily limits the
113     // size of the notecards that we can read and return.
114 //
115 //////////////
116
117 // begins getting configuration items from notecards and landmarks.
118 start_reading_configuration()
119 {
120     llSetTimerEvent(0.0);  // cancel any existing timers.
121
122     string JAUNT_SIGNATURE = "#jaunt";  // the expected first line of our notecards.
123
124     // a normal startup where we read notecards and stuff...
125     // see if we can load a notecard for destinations.
126     response_code = random_channel();
127     llMessageLinked(LINK_THIS, NOTEWORTHY_HUFFWARE_ID, READ_NOTECARD_COMMAND,
128          wrap_parameters([JAUNT_SIGNATURE, response_code]));
129     // we pick a private channel that fits in between our rez parm ranges.
130     // during a normal trip, we will make sure the notecard reading doesn't stall.
131     // the recon and one way jaunters don't need this; they're temporary.
132     // we allow this number of seconds before notecard reader is awol.
133
134     llSetTimerEvent(TIMEOUT_FOR_CONFIGURATION_PROCESS);
135 }
136
137 // main API implementor; answers requests to start reading config.
138 handle_config_request(string msg, string id)
139 {
140     if (msg != LOAD_ALL_CONFIGURATIONS) return;  // not for us.
141     list parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
142     // set our variables from the parameters we were given.
143     unused_private_chat_channel = llList2Integer(parms, 0);
144     conveyance_mode = llList2Integer(parms, 1);
145     if ( (conveyance_mode != RECONNAISSANCE_TRIP) && (conveyance_mode != ONE_WAY_TRIP) ) {
146         // setting up a root jaunter.
147         start_reading_configuration();
148     }
149 }
150
151 // sends out our current configuration perhaps.  if the check_length flag is true,
152 // then we'll only send if the list is already too fat.  if the flag is false, then
153 // we always just send our config (if it's non-empty).
154 send_config_blast(integer check_length)
155 {
156     if (!check_length || (llGetListLength(config_to_blast) > MAXIMUM_BLAST_SIZE) ) {
157         if (llGetListLength(config_to_blast) > 0) {
158             llMessageLinked(LINK_THIS, JAUNT_CONFIGURATION_HUFFWARE_ID + REPLY_DISTANCE,
159                 JAUNT_CFG_DATA_EVENT, wrap_parameters(config_to_blast));
160             config_to_blast = [];
161         }
162     }
163 }
164
165 // deals with responses from the notecard library.
166 process_notecard_lines(string msg, string id)
167 {
168     list parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
169     if (llList2Integer(parms, 1) != response_code) return;  // this isn't for us.
170
171     integer totally_done = TRUE;  // if left set to true, then notecard is done being consumed.
172     
173     string note_name = llList2String(parms, 0);
174     if (DEBUGGING) log_it("note name: " + note_name);
175     parms = llDeleteSubList(parms, 0, 1);
176     
177     // add in the leftovers.
178     if (leftover_parms != "") {
179         if (DEBUGGING) log_it("added leftover: " + leftover_parms);
180         parms = [ leftover_parms ] + parms;
181         leftover_parms = "";
182     }
183
184     if (note_name == NOTECARD_READ_CONTINUATION) {
185         totally_done = FALSE;
186         if (DEBUGGING) log_it("not totally done reading yet.");
187     }
188     if (note_name != BAD_NOTECARD_INDICATOR) {
189         integer indy;
190         for (indy = 0; indy < llGetListLength(parms); indy++) {
191             if (DEBUGGING) log_it("index: " + (string)indy);
192             string targ = llList2String(parms, indy);
193             if (DEBUGGING) log_it("targ: " + targ);
194             if (is_prefix(targ, ":")) {
195                 if (DEBUGGING) log_it("targ is special command.  just adding.");
196                 config_to_blast += [ targ ];
197             } else {
198                 if (indy < llGetListLength(parms) - 1) {
199                     if (DEBUGGING) log_it("decided we can steal two items.");
200                     // this looks like a normal pair of destination vector and name.
201                     string the_name = prune_name(llList2String(parms, indy + 1));
202                     config_to_blast += [ the_name, targ ];
203                     if (DEBUGGING) log_it("stole: " + the_name + " --> " + targ);
204                     indy++;  // skip an extra index since we stole two.
205                 } else {
206                     // save this tidbit for next config cycle.
207                     if (DEBUGGING) log_it("saving tidbit for next round: " + targ);
208                     leftover_parms = targ;
209                 }
210             }
211             send_config_blast(TRUE);
212         }
213     }
214
215     if (totally_done) {
216         // now that we've gotten our notecard read in, check the landmarks in
217         // the inventory to see if they're useful.
218         current_lm = 0;
219         if (current_lm < llGetInventoryNumber(INVENTORY_LANDMARK)) {
220             lm_data_req = llRequestInventoryData(
221                 llGetInventoryName(INVENTORY_LANDMARK, current_lm));
222         } else {
223             // kick out of this state and signal completion.
224             llSetTimerEvent(0.001);
225         }
226     }
227 }
228
229 // report our getting configured properly.
230 completed_configuration()
231 {
232     send_config_blast(FALSE);  // get last of config bits out to the client.
233     llMessageLinked(LINK_THIS, JAUNT_CONFIGURATION_HUFFWARE_ID + REPLY_DISTANCE,
234         JAUNT_CFG_EOF, NULL_KEY);
235 }
236
237 // fixes a location name so we don't get crushed on memory usage.
238 string prune_name(string to_prune)
239 {
240     integer MAX_DEST_NAME = 28;  // the longest name that we store.
241
242     // see if we can strip off the locational info.  comma is a common separator for stuff that's
243     // not part of the lm name.
244     integer indy = find_substring(to_prune, ",");
245     if (indy > 5) to_prune = llGetSubString(to_prune, 0, indy - 1);
246     // parentheses are another common way of adding extra stuff we don't need for the name.
247     indy = find_substring(to_prune, "(");
248     if (indy > 5) to_prune = llGetSubString(to_prune, 0, indy - 1);
249     // crop the name on general length issues too.
250     to_prune = llGetSubString(to_prune, 0, MAX_DEST_NAME);
251     return to_prune;
252 }
253
254 // called when dataserver brings us landmark info.
255 process_landmark_data(key id, string data)
256 {
257     if (id != lm_data_req) return;  // not for us.
258     lm_data_req = NULL_KEY;  // drop our prior key.
259     if (data != EOF) {
260         string dest = vector_chop((vector)data);
261         config_to_blast += [ prune_name(llGetInventoryName(INVENTORY_LANDMARK, current_lm)), dest ];
262         send_config_blast(TRUE);
263         current_lm++;
264         if (current_lm < llGetInventoryNumber(INVENTORY_LANDMARK)) {
265             lm_data_req = llRequestInventoryData(
266                 llGetInventoryName(INVENTORY_LANDMARK, current_lm));
267         }
268     }
269     // check our sentinel data key about being done.
270     if (lm_data_req == NULL_KEY) {
271         // looks like we got our destinations and are totally done now.
272         llSetTimerEvent(0.001);  // trigger state change very shortly.
273     }
274 }
275
276 //////////////
277
278 //////////////
279 // from hufflets...
280
281 integer debug_num = 0;
282
283 // a debugging output method.  can be disabled entirely in one place.
284 log_it(string to_say)
285 {
286     debug_num++;
287     // tell this to the owner.    
288     llOwnerSay(llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
289     // say this on open chat, but use an unusual channel.
290 //    llSay(108, (string)debug_num + "- " + to_say);
291 }
292
293 ///////////////
294
295 // returns TRUE if the value in "to_check" specifies a legal x or y value in a sim.
296 integer valid_sim_value(float to_check)
297 {
298     if (to_check < 0.0) return FALSE;
299     if (to_check >= 257.0) return FALSE;
300     return TRUE;
301 }
302
303 // returns TRUE if the "to_check" vector is a location outside of the current sim.
304 integer outside_of_sim(vector to_check)
305 {
306     return !valid_sim_value(to_check.x) || !valid_sim_value(to_check.y);
307 }
308
309 // returns text for a floating point number, but includes only
310 // three digits after the decimal point.
311 string float_chop(float to_show)
312 {
313     integer mant = llAbs(llRound(to_show * 1000.0) / 1000);
314     string neg_sign;
315     if (to_show < 0.0) neg_sign = "-";
316     string dec_s = (string)((llRound(to_show * 1000.0) - mant * 1000) / 1000.0);
317     dec_s = llGetSubString(llGetSubString(dec_s, find_substring(dec_s, ".") + 1, -1), 0, 2);
318     // strip off all trailing zeros.
319     while (llGetSubString(dec_s, -1, -1) == "0")
320         dec_s = llDeleteSubString(dec_s, -1, -1);
321     string to_return = neg_sign + (string)mant;
322     if (llStringLength(dec_s)) to_return += "." + dec_s;
323     return to_return;
324 }
325
326 // returns a prettier form for vector text, with chopped floats.
327 string vector_chop(vector to_show)
328 {
329     return "<" + float_chop(to_show.x) + ","
330         + float_chop(to_show.y) + ","
331         + float_chop(to_show.z) + ">";
332 }
333
334 // joins a list of parameters using the parameter sentinel for the library.
335 string wrap_parameters(list to_flatten)
336 { return llDumpList2String(to_flatten, HUFFWARE_PARM_SEPARATOR); }
337 //
338 // joins a list of sub-items using the item sentinel for the library.
339 string wrap_item_list(list to_wrap)
340 { return llDumpList2String(to_wrap, HUFFWARE_ITEM_SEPARATOR); }
341
342 integer random_channel() { return -(integer)(llFrand(40000) + 20000); }
343
344 // returns the portion of the list between start and end, but only if they are
345 // valid compared with the list length.  an attempt to use negative start or
346 // end values also returns a blank list.
347 list chop_list(list to_chop, integer start, integer end)
348 {
349     integer last_len = llGetListLength(to_chop) - 1;
350     if ( (start < 0) || (end < 0) || (start > last_len) || (end > last_len) ) return [];
351     return llList2List(to_chop, start, end);
352 }
353
354 // returns the index of the first occurrence of "pattern" inside
355 // the "full_string".  if it is not found, then a negative number is returned.
356 integer find_substring(string full_string, string pattern)
357 {
358     string full_lower = llToLower(full_string);
359     return llSubStringIndex(full_lower, pattern);
360 }
361
362 // returns TRUE if the "prefix" string is the first part of "compare_with".
363 integer is_prefix(string compare_with, string prefix)
364 { return find_substring(compare_with, prefix) == 0; }
365
366 //////////////
367 // huffware script: auto-retire, by fred huffhines, version 2.8.
368 // distributed under BSD-like license.
369 //   !!  keep in mind that this code must be *copied* into another
370 //   !!  script that you wish to add auto-retirement capability to.
371 // when a script has auto_retire in it, it can be dropped into an
372 // object and the most recent version of the script will destroy
373 // all older versions.
374 //
375 // the version numbers are embedded into the script names themselves.
376 // the notation for versions uses a letter 'v', followed by two numbers
377 // in the form "major.minor".
378 // major and minor versions are implicitly considered as a floating point
379 // number that increases with each newer version of the script.  thus,
380 // "hazmap v0.1" might be the first script in the "hazmap" script continuum,
381 // and "hazmap v3.2" is a more recent version.
382 //
383 // example usage of the auto-retirement script:
384 //     default {
385 //         state_entry() {
386 //            auto_retire();  // make sure newest addition is only version of script.
387 //        }
388 //     }
389 // this script is partly based on the self-upgrading scripts from markov brodsky
390 // and jippen faddoul.
391 //////////////
392 auto_retire() {
393     string self = llGetScriptName();  // the name of this script.
394     list split = compute_basename_and_version(self);
395     if (llGetListLength(split) != 2) return;  // nothing to do for this script.
396     string basename = llList2String(split, 0);  // script name with no version attached.
397     string version_string = llList2String(split, 1);  // the version found.
398     integer posn;
399     // find any scripts that match the basename.  they are variants of this script.
400     for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
401         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
402         if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
403             // found a basic match at least.
404             list inv_split = compute_basename_and_version(curr_script);
405             if (llGetListLength(inv_split) == 2) {
406                 // see if this script is more ancient.
407                 string inv_version_string = llList2String(inv_split, 1);  // the version found.
408                 // must make sure that the retiring script is completely the identical basename;
409                 // just matching in the front doesn't make it a relative.
410                 if ( (llList2String(inv_split, 0) == basename)
411                     && ((float)inv_version_string < (float)version_string) ) {
412                     // remove script with same name from inventory that has inferior version.
413                     llRemoveInventory(curr_script);
414                 }
415             }
416         }
417     }
418 }
419 //
420 // separates the base script name and version number.  used by auto_retire.
421 list compute_basename_and_version(string to_chop_up)
422 {
423     // minimum script name is 2 characters plus a version.
424     integer space_v_posn;
425     // find the last useful space and 'v' combo.
426     for (space_v_posn = llStringLength(to_chop_up) - 3;
427         (space_v_posn >= 2) && (llGetSubString(to_chop_up, space_v_posn, space_v_posn + 1) != " v");
428         space_v_posn--) {
429         // look for space and v but do nothing else.
430     }
431     if (space_v_posn < 2) return [];  // no space found.
432     // now we zoom through the stuff after our beloved v character and find any evil
433     // space characters, which are most likely from SL having found a duplicate item
434     // name and not so helpfully renamed it for us.
435     integer indy;
436     for (indy = llStringLength(to_chop_up) - 1; indy > space_v_posn; indy--) {
437         if (llGetSubString(to_chop_up, indy, indy) == " ") {
438             // found one; zap it.  since we're going backwards we don't need to
439             // adjust the loop at all.
440             to_chop_up = llDeleteSubString(to_chop_up, indy, indy);
441         }
442     }
443     string full_suffix = llGetSubString(to_chop_up, space_v_posn, -1);
444     // ditch the space character for our numerical check.
445     string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
446     // strip out a 'v' if there is one.
447     if (llGetSubString(chop_suffix, 0, 0) == "v")
448         chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
449     // if valid floating point number and greater than zero, that works for our version.
450     string basename = to_chop_up;  // script name with no version attached.
451     if ((float)chop_suffix > 0.0) {
452         // this is a big success right here.
453         basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
454         return [ basename, chop_suffix ];
455     }
456     // seems like we found nothing useful.
457     return [];
458 }
459 //
460 //////////////
461
462 //////////////
463
464 // default state scrounges for information in a notecard and looks for landmarks in
465 // inventory to add as destinations.
466 default
467 {
468     state_entry() { if (llSubStringIndex(llGetObjectName(),  "huffotronic") < 0) state real_default; }
469     on_rez(integer parm) { state rerun; }
470 }
471 state rerun { state_entry() { state default; } }
472
473 state real_default
474 {
475     state_entry() { auto_retire(); }
476
477     link_message(integer which, integer num, string msg, key id)
478     {
479         if (num == NOTEWORTHY_HUFFWARE_ID + REPLY_DISTANCE) {
480             process_notecard_lines(msg, id);
481         } else if (num == JAUNT_CONFIGURATION_HUFFWARE_ID) {
482             handle_config_request(msg, id);
483         }
484     }
485     
486     dataserver(key id, string data) { process_landmark_data(id, data); }
487
488     timer() {
489         // this is the only place we publish a result.
490         completed_configuration();
491         llSetTimerEvent(0.0);  // stop the timer again, until next request.
492     }
493 }
494