7a5b6cd27e7b610cdedae20f217c360697b65326
[feisty_meow.git] / huffware / huffotronic_scripts / inventory_exchanger_v3.7.txt
1 
2 // huffware script: inventory exchanger, by fred huffhines.
3 //
4 // manages inventory between a root prim and its children.  this script should be placed in
5 // all prims that need to exchange contents.  the root prim drives the exchange process based
6 // on a registered set of assets that it is told to synchronize in each child.  all the child
7 // prims that have this script will ensure they are up to date with respect to those assets.
8 //
9 // this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
10 // do not use it in objects without fully realizing you are implicitly accepting that license.
11 //
12
13 // inventory exchanger link message API...
14 //////////////
15 // do not redefine these constants.
16 integer INVENTORY_EXCHANGER_HUFFWARE_ID = 10021;
17     // the unique id within the huffware system for the jaunt script to
18     // accept commands on.  this is used in llMessageLinked as the num parameter.
19 string HUFFWARE_PARM_SEPARATOR = "{~~~}";
20     // this pattern is an uncommon thing to see in text, so we use it to separate
21     // our commands in link messages.
22 //string HUFFWARE_ITEM_SEPARATOR = "{|||}";
23     // used to separate lists of items from each other when stored inside a parameter.
24     // this allows lists to be passed as single string parameters if needed.
25 integer REPLY_DISTANCE = 100008;  // offset added to service's huffware id in reply IDs.
26 // commands available via the library:
27 string REGISTER_ASSETS_COMMAND = "#regis#";
28     // makes the root prim's inventory exchanger track a set of items which each participating
29     // child prim should have.  this command is only available to the root prim; child prims
30     // cannot register any assets but instead can get updates on the assets.  the parameter
31     // required is a list of asset definitions, wrapped by the huffware parm separator.  each
32     // asset definition is in turn a two part list wrapped with the asset field separator.
33 string ASSET_FIELD_SEPARATOR = "&&";  // separates the type from the name in our list.
34 string WILDCARD_INVENTORY_NAME = "ALL";
35     // this keyword can be used to register all of the inventory items available of the
36     // specified type.  this should be passed as the inventory item name in the second half of
37     // an asset definition list.
38 string WHACK_INVENTORY_SIGNAL = "DEL*";
39     // ensures that the child prim doesn't maintain *any* of the inventory of the type specified.
40 string AVAILABLE_ASSETS_EVENT = "#gotz#";
41     // the root prim publishes this event to list out what items it has available.  the child
42     // prims need to ask for anything that they're currently missing.  the included parameters
43     // are in the same format as the register assets command, but no wildcards will be present;
44     // all asset names will be fully expanded.
45 string REQUEST_UPDATES = "#nupd#";
46     // used by the child prim to request an updated version of an asset or assets.  the parameters
47     // should follow the register assets command.
48 string FINISHED_UPDATING = "#donq#";
49     // a signal sent from the root prim to the child prim when the root has finished updating
50     // the assets requested.  this lets the child know that it can clean out any outdated versions
51     // of items which got an update.  there are no parameters to this, because the child prim
52     // should have at most one update outstanding at a time.
53 //////////////
54
55 // constants...
56
57 integer TIMER_PERIOD = 600;  // the rate at which the root sends out updates (in seconds).
58
59 integer INVEXCH_SCRIPT_PIN = -343781294;  // used to slam scripts into the target prim.
60
61 // global variables...
62
63 list assets_available;
64     // the set of items that we will provide on demand.  this list has items wrapped with the
65     // asset separator, where the unwrapped entries each provide the type (integer) and the
66     // name of the item.
67
68 // gives out items that are asked for in "requested_assets".  these go from the
69 // root prim into the kids.
70 populate_child_prim(integer link_num, list requested_assets)
71 {
72     key asking_child = llGetLinkKey(link_num);  // the kid that needs the update.
73     // look at the assets one by one and pass them over.
74     integer undy;
75     for (undy = 0; undy < llGetListLength(requested_assets); undy++) {
76         // unwrap the next asset definition from the requests.
77         list asset_def = llParseString2List(llList2String(requested_assets, undy),
78             [ASSET_FIELD_SEPARATOR], []);
79         integer type = llList2Integer(asset_def, 0);
80         string name = llList2String(asset_def, 1);
81 //log_it("root is giving link " + (string)link_num + " item " + name);
82         // fork over the item itself.
83         if (type != INVENTORY_SCRIPT) {
84             llGiveInventory(asking_child, name);            
85         } else {
86             llRemoteLoadScriptPin(asking_child, name, INVEXCH_SCRIPT_PIN, TRUE, 0);
87         }
88     }
89
90     // we send this event when done updating the kid.     
91     llMessageLinked(link_num, INVENTORY_EXCHANGER_HUFFWARE_ID, FINISHED_UPDATING, NULL_KEY);
92 }
93
94 // changes the run state of all the scripts besides this one.
95 knock_around_other_scripts(integer running_state)
96 {
97     // we won't start anything if we're running inside the updater object.
98     if (find_substring(llGetObjectName(), "huffotronic") >= 0) return;
99     
100     integer indy;
101     string self_script = llGetScriptName();
102     // we set all other scripts to the running state requested.
103     for (indy = 0; indy < llGetInventoryNumber(INVENTORY_SCRIPT); indy++) {
104         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, indy);
105         if (curr_script != self_script) {
106             // this one seems ripe for being set to the state requested.
107             llSetScriptState(curr_script, running_state);
108         }
109     }
110 }
111
112 // kicks forward the periodic activities of the exchange process.
113 handle_timer()
114 {
115     if (llGetLinkNumber() != 1) {
116         // child prim activities only.
117 //        knock_around_other_scripts(TRUE);
118         return;
119     } else {
120         // the rest are root prim timer activities.
121         if (llGetListLength(assets_available) == 0) return;  // nothing to do here.
122         // the root needs to send out link messages telling kids what good stuff its got.
123         llMessageLinked(LINK_ALL_CHILDREN, INVENTORY_EXCHANGER_HUFFWARE_ID,
124             AVAILABLE_ASSETS_EVENT, wrap_parameters(assets_available));
125     }
126
127 }
128
129 // given a packed up list of items, this breaks out each asset definition and
130 // begins using the set as our full list of available items.
131 consume_asset_registration(string packed_assets)
132 {
133     assets_available = llParseString2List(packed_assets, [HUFFWARE_PARM_SEPARATOR], []);
134 //hmmm: future enhancement might be to allow multiple clients of the root exchanger.
135 //      currently we only support one script inside the root prim listing assets for inv exch.
136 //      that's shown just above where we're just replacing the entire registered assets list.
137
138     integer indy;
139     for (indy = 0; indy < llGetListLength(assets_available); indy++) {
140         list asset_def = llParseString2List(llList2String(assets_available, indy),
141             [ASSET_FIELD_SEPARATOR], []);
142         integer type = llList2Integer(asset_def, 0);
143         string name = llList2String(asset_def, 1);
144         if (name == WILDCARD_INVENTORY_NAME) {
145             // argh, we need to patch up the list for a wildcard option.
146             // first, whack the item with the wildcard in it.
147             assets_available = llDeleteSubList(assets_available, indy, indy);
148             // now revert the list index for the missing item.
149             indy--;
150             // and finally add all the items of that type.  if one of them is named
151             // after the wildcard character, well, we disallow that craziness.
152             integer inv_pos;
153             for (inv_pos = 0; inv_pos < llGetInventoryNumber(type); inv_pos++) {
154                 string inv_name = llGetInventoryName(type, inv_pos);
155                 if (inv_name != WILDCARD_INVENTORY_NAME) {
156 //log_it("added wild: " + inv_name);
157                     assets_available += [ llDumpList2String([type, inv_name], ASSET_FIELD_SEPARATOR) ];
158                 }
159             }
160             
161         }
162     }
163     
164     // make sure we get this new set out to the interested parties.
165     handle_timer();    
166 }
167
168 // note that this new, lower memory version, depends on the inventory functions returning
169 // items in alphabetical order.
170 scrub_items_by_type(string this_guy, integer inventory_type)
171 {
172     list removal_list;
173     integer outer;
174     for (outer = 0; outer < llGetInventoryNumber(inventory_type); outer++) {
175         string curr = llGetInventoryName(inventory_type, outer);
176         list split = compute_basename_and_version(curr);
177         // make sure there was a comparable version number in this name.
178         if ( (curr != this_guy) && llGetListLength(split)) {
179             string curr_base = llList2String(split, 0);
180             float curr_ver = (float)llList2String(split, 1);
181 //log_it("outer: " + curr_base + " / " + (string)curr_ver);
182             integer inner;
183             for (inner = outer + 1; inner < llGetInventoryNumber(inventory_type); inner++) {
184                 string next_guy = llGetInventoryName(inventory_type, inner);
185                 list comp_split = compute_basename_and_version(next_guy);
186                 if (llGetListLength(comp_split)) {
187                     string comp_base = llList2String(comp_split, 0);
188                     float comp_ver = (float)llList2String(comp_split, 1);
189                     // okay, now we can actually compare.
190                     if (curr_base != comp_base) {
191                         // break out of inner loop.  we are past where the names can matter.
192                         inner = 2 * llGetInventoryNumber(inventory_type);
193                     } else {
194 //log_it("inner: " + comp_base + " / " + (string)comp_ver);
195                         if (curr_ver <= comp_ver) {
196                             // the script at inner index is comparable or better than
197                             // the script at the outer index.
198                             removal_list += curr;
199                         } else {
200                             // this inner script must be inferior to the outer one,
201                             // somehow, which defies our expectation of alphabetical ordering.
202                             removal_list += next_guy;
203                         }
204                     }
205                 }
206             }
207         }
208     }
209
210     // now actually do the deletions.
211     for (outer = 0; outer < llGetListLength(removal_list); outer++) {
212         string to_whack = llList2String(removal_list, outer);
213 log_it("removing older asset: " + to_whack);
214         llRemoveInventory(to_whack);
215     }
216 }
217
218 // ensures that only the latest version of any script or object is kept in our inventory.
219 // has been called destroy_older_versions in other scripts.
220 clean_outdated_items()
221 {
222     scrub_items_by_type(llGetScriptName(), INVENTORY_ALL);
223     // after cleaning up, make sure everything's running.
224     knock_around_other_scripts(TRUE);    
225 }
226
227 // locates the index of a specified type of inventory item with a particular name,
228 // or returns a negative number.
229 integer find_inventory(integer type, string name)
230 {
231     integer indy;
232     for (indy = 0; indy < llGetInventoryNumber(type); indy++) {
233         if (name == llGetInventoryName(type, indy)) return indy;
234     }
235     return -1;
236 }
237
238 // called on child prims to make sure they have everything the root does.
239 examine_inventory_freshness(string packed_assets)
240 {
241     list missing_goods;  // fill this with the things we don't have in this prim.
242     list provisions = llParseString2List(packed_assets, [HUFFWARE_PARM_SEPARATOR], []);
243     integer indy;
244     // scan through all the items that are available and make sure we have each of them.
245     for (indy = 0; indy < llGetListLength(provisions); indy++) {
246         string prov = llList2String(provisions, indy);
247         list fields = llParseString2List(prov, [ASSET_FIELD_SEPARATOR], []);
248 //log_it("checking: " + llList2String(fields, 1) + " type=" + (string)llList2Integer(fields, 0));
249         // look for the type and name specified.
250         integer type = llList2Integer(fields, 0);
251         string name = llList2String(fields, 1);
252         if (name == WHACK_INVENTORY_SIGNAL) {
253             // we see our special signifier, so remove all items of the type specified.
254             // yes, this is dangerous.
255             integer delo;
256             for (delo = llGetInventoryNumber(type) - 1; delo >= 0; delo--) {
257                 llRemoveInventory(llGetInventoryName(type, delo));
258             }
259         } else {
260             integer found = find_inventory(type, name);
261             if (found < 0) {
262 //log_it("found " + llList2String(fields, 1) + " was missing!");
263                 // well, we are out of this one.  tell the root we want it.
264                 missing_goods += [ prov ];
265             }
266         }
267     }
268     if (llGetListLength(missing_goods) > 0) {
269         // well we found some things that we're supposed to have, but do not.  we will
270         // get the root prim to fix us up.
271         llMessageLinked(LINK_ROOT, INVENTORY_EXCHANGER_HUFFWARE_ID,
272             REQUEST_UPDATES, wrap_parameters(missing_goods));
273     }
274 }
275
276 //hmmm: this is not such a good model?  why do the root and
277 //  the child both need to be running this check on a timer?
278
279 // processes inventory exchange commands in the root prim.  this is where assets must
280 // be present so they can be distributed to the child prims.
281 process_root_msg(integer link_num, integer service, string cmd, key parms)
282 {
283     if (service != INVENTORY_EXCHANGER_HUFFWARE_ID) return;  // not for us.
284 //string name="root";
285 //if (llGetLinkNumber() != 1) name="child";
286 //log_it(name + " got request " + cmd);
287     if (link_num == 1) {
288         // this request is also from the root prim, where this script lives currently.
289         if (cmd == REGISTER_ASSETS_COMMAND) {
290             // root prim accepts a list of assets to provide to the kids.
291             consume_asset_registration(parms);
292         }
293     } else {
294         // a request is coming from a child prim.
295         if (cmd == REQUEST_UPDATES) {
296             // the root prim responds to update requests by handing out presents.
297             populate_child_prim(link_num, llParseString2List(parms, [HUFFWARE_PARM_SEPARATOR], []));
298         }
299     }
300 }
301
302 // implements the child API, mainly to track missing assets and clean out outdated items.
303 process_child_msg(integer link_num, integer service, string cmd, key parms)
304 {
305     if (service != INVENTORY_EXCHANGER_HUFFWARE_ID) return;  // not for us.
306     if (link_num != 1) return;  // we don't listen to any chatter from other children.
307     if (cmd == AVAILABLE_ASSETS_EVENT) {
308         examine_inventory_freshness(parms);
309     } else if (cmd == FINISHED_UPDATING) {
310         clean_outdated_items();
311     }
312 }
313
314 // main processing function for the link messge API.
315 handle_link_message(integer link_num, integer service, string cmd, key parms)
316 {
317     if (llGetLinkNumber() == 1) process_root_msg(link_num, service, cmd, parms);
318     else process_child_msg(link_num, service, cmd, parms);
319 }
320
321 //////////////
322 // beginning of hufflets...
323 //////////////
324
325 // diagnostic hufflets...
326
327 integer debug_num = 0;
328
329 // a debugging output method.  can be disabled entirely in one place.
330 log_it(string to_say)
331 {
332     debug_num++;
333     // tell this to the owner.    
334     llOwnerSay(llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
335     // say this on an unusual channel for chat if it's not intended for general public.
336 //    llSay(108, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
337     // say this on open chat that anyone can hear.  we take off the bling for this one.
338 //    llSay(0, to_say);
339 }
340
341 // joins a list of parameters using the parameter sentinel for the library.
342 string wrap_parameters(list to_flatten)
343 { return llDumpList2String(to_flatten, HUFFWARE_PARM_SEPARATOR); }
344
345 // joins a list of sub-items using the item sentinel for the library.
346 //string wrap_item_list(list to_wrap)
347 //{ return llDumpList2String(to_wrap, HUFFWARE_ITEM_SEPARATOR); }
348
349 // returns the index of the first occurrence of "pattern" inside
350 // the "full_string".  if it is not found, then a negative number is returned.
351 integer find_substring(string full_string, string pattern)
352 { return llSubStringIndex(llToLower(full_string), llToLower(pattern)); }
353
354 // returns TRUE if the "prefix" string is the first part of "compare_with".
355 integer is_prefix(string compare_with, string prefix)
356 { return find_substring(compare_with, prefix) == 0; }
357
358 //////////////
359 // huffware script: auto-retire, by fred huffhines, version 2.5.
360 // distributed under BSD-like license.
361 //   !!  keep in mind that this code must be *copied* into another
362 //   !!  script that you wish to add auto-retirement capability to.
363 // when a script has auto_retire in it, it can be dropped into an
364 // object and the most recent version of the script will destroy
365 // all older versions.
366 //
367 // the version numbers are embedded into the script names themselves.
368 // the notation for versions uses a letter 'v', followed by two numbers
369 // in the form "major.minor".
370 // major and minor versions are implicitly considered as a floating point
371 // number that increases with each newer version of the script.  thus,
372 // "hazmap v0.1" might be the first script in the "hazmap" script continuum,
373 // and "hazmap v3.2" is a more recent version.
374 //
375 // example usage of the auto-retirement script:
376 //     default {
377 //         state_entry() {
378 //            auto_retire();  // make sure newest addition is only version of script.
379 //        }
380 //     }
381 // this script is partly based on the self-upgrading scripts from markov brodsky
382 // and jippen faddoul.
383 //////////////
384 auto_retire() {
385     string self = llGetScriptName();  // the name of this script.
386     list split = compute_basename_and_version(self);
387     if (llGetListLength(split) != 2) return;  // nothing to do for this script.
388     string basename = llList2String(split, 0);  // script name with no version attached.
389     string version_string = llList2String(split, 1);  // the version found.
390     integer posn;
391     // find any scripts that match the basename.  they are variants of this script.
392     for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
393         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
394         if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
395             // found a basic match at least.
396             list inv_split = compute_basename_and_version(curr_script);
397             if (llGetListLength(inv_split) == 2) {
398                 // see if this script is more ancient.
399                 string inv_version_string = llList2String(inv_split, 1);  // the version found.
400                 // must make sure that the retiring script is completely the identical basename;
401                 // just matching in the front doesn't make it a relative.
402                 if ( (llList2String(inv_split, 0) == basename)
403                     && ((float)inv_version_string < (float)version_string) ) {
404                     // remove script with same name from inventory that has inferior version.
405                     llRemoveInventory(curr_script);
406                 }
407             }
408         }
409     }
410 }
411 //
412 // separates the base script name and version number.  used by auto_retire.
413 list compute_basename_and_version(string to_chop_up)
414 {
415     // minimum script name is 2 characters plus a version.
416     integer space_v_posn;
417     // find the last useful space and 'v' combo.
418     for (space_v_posn = llStringLength(to_chop_up) - 3;
419         (space_v_posn >= 2) && (llGetSubString(to_chop_up, space_v_posn, space_v_posn + 1) != " v");
420         space_v_posn--) {
421         // look for space and v but do nothing else.
422     }
423     if (space_v_posn < 2) return [];  // no space found.
424     // now we zoom through the stuff after our beloved v character and find any evil
425     // space characters, which are most likely from SL having found a duplicate item
426     // name and not so helpfully renamed it for us.
427     integer indy;
428     for (indy = llStringLength(to_chop_up) - 1; indy > space_v_posn; indy--) {
429         if (llGetSubString(to_chop_up, indy, indy) == " ") {
430             // found one; zap it.  since we're going backwards we don't need to
431             // adjust the loop at all.
432             to_chop_up = llDeleteSubString(to_chop_up, indy, indy);
433         }
434     }
435     string full_suffix = llGetSubString(to_chop_up, space_v_posn, -1);
436     // ditch the space character for our numerical check.
437     string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
438     // strip out a 'v' if there is one.
439     if (llGetSubString(chop_suffix, 0, 0) == "v")
440         chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
441     // if valid floating point number and greater than zero, that works for our version.
442     string basename = to_chop_up;  // script name with no version attached.
443     if ((float)chop_suffix > 0.0) {
444         // this is a big success right here.
445         basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
446         return [ basename, chop_suffix ];
447     }
448     // seems like we found nothing useful.
449     return [];
450 }
451 //
452 // end hufflets
453 //////////////
454
455 default
456 {
457     state_entry() { if (llSubStringIndex(llGetObjectName(),  "huffotronic") < 0) state real_default; }
458     on_rez(integer parm) { state rerun; }
459 }
460 state rerun { state_entry() { state default; } }
461
462 state real_default
463 {
464     state_entry()
465     {
466         auto_retire();
467 ///log_it("\n\n\n\n\n\n\n\n\n** starting now............................");
468         // register child prims for script replacement.
469         if (llGetLinkNumber() != 1) llSetRemoteScriptAccessPin(INVEXCH_SCRIPT_PIN);
470         //new idea; only allow timers to run in root prim.
471         if (llGetLinkNumber() == 1) llSetTimerEvent(TIMER_PERIOD);
472         knock_around_other_scripts(TRUE);
473         // first run happens right at startup.
474         if (llGetLinkNumber() == 1) handle_timer();
475     }
476
477     timer() {
478         llSetTimerEvent(0);  // stop timer.
479         handle_timer();
480         llSetTimerEvent(TIMER_PERIOD);  // start timer.
481     }
482
483     link_message(integer link_num, integer service, string cmd, key parms) {
484         handle_link_message(link_num, service, cmd, parms);
485     }
486 }
487
488