will take a list of files and go through them with eog as a viewer.
[feisty_meow.git] / huffware / huffotronic_eepaw_knowledge_v60.9 / huff-search_brainiac_v46.7.lsl
1 
2 // huffware script: huff-search brainiac, by fred huffhines
3 //
4 //    this script is one portion of a search system.  it is the brain for an object
5 // that can find nearby objects by a partial name match.  this script should be
6 // located in the root primitive.  it also requires an up-to-date jaunting library
7 // in the same primitive.  see the (hopefully) enclosed documentation for more details.
8 //    more implementation notes are stored at the back of the file.
9 //
10 // this script is licensed by the GPL v3 which is documented at: http://www.gnu.org/licenses/gpl.html
11 // do not use it in objects without fully realizing you are implicitly accepting that license.
12 //
13
14 // global settings that can be very useful to change...
15
16 integer MAX_MATCHES = 17;
17     // by default we try to match one object per rod so we can point at them.
18
19 float MAX_SPIRAL_RADIUS = 72.0;
20     // the farthest that the object will travel from its home while searching.
21     // this is an important factor in the searchbert's range of vision; the other is
22     // the sensor range, below.
23     // ensure that it has access to the lands within this range or it might get stuck.
24     // you can also set the TRAVERSE_LANDS flag to false to make for safer searches when
25     // surrounded by a lot of banned lands.
26
27 float SENSOR_MAX_RANGE = 96.0;
28     // the maximum range that we try to sense objects at.  this is distinct from the spiral
29     // radius because often the range of movement is constrained by land conditions, where
30     // one might still want a large sensor radius to see as many things as possible in range.
31     // note though that searches will keep matching the things nearest to them if neither
32     // the position nor the angle nor object positions have changed.
33
34 float SPIRAL_LOOPS = 7;
35     // how many loops there are in the spiral.  this is measured by how many times the
36     // spiral cuts across the positive x-axis (that is, the zero angle vector) from
37     // the center of the spiral to the radius (that is, from <0, 0, 0> to <radius, 0, 0>).
38
39 integer TOTAL_STEPS = 42;
40     // how many positions within the spiral will the object travel to?  the first step
41     // is step 0, which is the center of the spiral.  positions 1 through TOTAL_STEPS
42     // spiral outward from the zero position, where the distance from the center at
43     // TOTAL_STEPS should be MAX_SPIRAL_RADIUS or less.
44     
45 integer MAX_SPIRAL_TRAVERSALS = 1;
46     // how many different spirals are we allowed for the same search?  this will let the
47     // search engine cover more ground than with just one spiral, to allow different
48     // objects to be exposed.
49
50 integer HUFF_SEARCH_CHAT_CHANNEL = 0;
51     // the channel where the object listens for commands.  the default is to use open
52     // chat for this, but some people may want it more specific.
53
54 // this flag is important to keep as false for wright plaza and other areas with script traps
55 // (where the perms allow objects to enter, but then their scripts are stopped dead).
56 integer TRAVERSE_LANDS = FALSE;
57     // if this is false, then the searchbert will stick to the land owner's land where it started.
58     // but if it's true, then searchbert will cross into other people's lands too, but if there
59     // are some weird border or permission conditions about object re-entry or scripts being able
60     // to run, that can be quite problematic.
61
62 integer TRAVELLING_UPWARDS = FALSE;
63     // if this is true, the searchbert will climb in the vertical direction also.
64
65 float MAX_UPWARDS_DISTANCE = 30.0;
66     // the farthest away that the searchbert will fly during an upwards search.
67
68 float SEARCH_ROD_ANGULAR_SWEEP = PI_BY_TWO;
69     // angular arc of the sensor cone, placeholder.
70
71 //////////////
72
73 // constants that are not configurable in a notecard...
74
75 integer DEBUGGING = FALSE;  // set to true to make the script noisier.
76
77 //////////////
78
79 // global constants that aren't as useful to change...
80
81 float MINIMUM_HEIGHT_ABOVE_GROUND = 0.14;
82     // the closest we allow the searcher to get to the ground.  any lower and our search
83     // rods might be dragging around under ground.
84
85 float FAST_TIMER_INTERVAL = 0.12;
86     // the time between jumps when we're doing our search spiral.  this is the fastest
87     // the object can spin around its spiral trajectory, but it's more limited than by
88     // just this number; llSetPrimitiveParams is used for jaunting and it has a delay of
89     // 0.2 seconds built into it.
90
91 integer NORMAL_TIMER_INTERVAL = 14;
92     // how frequently we check for things to do, in seconds.
93
94 float STARTUP_TIME_ALLOWED = 50.0;  // number of seconds before declaring a timeout.
95
96 integer MAX_STEP_SNOOZES = 81;
97     // number of timer hits to allow before giving up on jaunt.
98
99 float SNOOZE_BEFORE_RESET = 300;
100     // number of seconds before a scan will automatically reset.  hopefully this is
101     // enough time for the user to follow the trail to the detected object.
102     
103 // imported interfaces below...
104
105 // huff-search pointer API:
106 //////////////
107 // do not redefine these constants.
108 integer HUFF_SEARCH_POINTER_HUFFWARE_ID = 10032;
109     // the unique id within the huffware system for this script.
110 string HUFFWARE_PARM_SEPARATOR = "{~~~}";
111     // this pattern is an uncommon thing to see in text, so we use it to separate
112     // our commands in link messages.
113 string HUFFWARE_ITEM_SEPARATOR = "{|||}";
114     // used to separate lists of items from each other when stored inside a parameter.
115     // this allows lists to be passed as single string parameters if needed.
116 integer REPLY_DISTANCE = 100008;  // offset added to service's huffware id in reply IDs.
117 //////////////
118 string HUFF_SEARCH_RESET = "#reset#";
119     // returns the script to its starting state.
120 string HUFF_SEARCH_POINT_PARTY = "#point_particles#";
121     // aim at an object and show a particle stream leading to it.
122 string HUFF_SEARCH_JUST_POINT = "#just_point#";
123     // aim at an object, but don't do any particles.
124 string HUFF_SEARCH_SENSEI = "#sensor#";
125     // set up a sensor request for a search pattern.  pings will cause
126     // the pattern to be sought in names of nearby objects.  the parameters are:
127     // (1) the maximum range for the sensor, (2) the arc angle to use in sensing,
128     // (3) the search pattern to look for in object names, (4) the maximum number
129     // of matches to look for.
130 string HUFF_SEARCH_STOP_SENSE = "#stop_sensor#";
131     // turn off the sensor but don't totally reset.
132 string HUFF_SEARCH_PING = "#ping#";
133     // cause the searcher to actively sensor ping the targets.
134 string HUFF_SEARCH_MATCH_EVENT = "#match#";
135     // fired at the root prim when matches are found for the search term.
136     // the payload is a list of matched item pairs [item key, location].
137 //////////////
138
139 // the armature button pushing API.
140 // (we have subclassed the simple button pushing API for searchbert armature.)
141 //////////////
142 integer BUTTON_PUSHER_HUFFWARE_ID = 10029;
143     // a unique ID within the huffware system for this script.
144 //////////////
145 string BUTTON_PUSHED_ALERT = "#btnp";
146     // this event is generated when the button is pushed.  the number parameter will be
147     // the huffware id plus the reply distance.  the id parameter in the link message will
148     // contain the name of the button that was pushed.
149 //////////////
150 string CHECK_ARMS_BUTTON_NAME = "^checkarms";
151     // this is the signal given to the armature script that it should check the
152     // number of arms present on searchbert.  if the number is fine, it will
153     // push the arms are good button back at the brainiac (using the button
154     // push api plus reply distance).
155 string ARMS_ARE_GOOD_BUTTON_NAME = "^goodarmz";
156     // the event sent back by the searchbert armature when all arms are ready
157     // to go.
158 string PROBLEM_WITH_MY_THUMBS_BUTTON_NAME = "^ouch";
159     // a problem was noticed with the number of arms and we could not fix it.
160     // the brain needs to try reconfiguring again.
161 //////////////
162
163 // searchbert menus API.
164 //////////////
165 // do not redefine these constants.
166 integer SEARCHBERT_MENUS_HUFFWARE_ID = 10034;
167     // the unique id within the huffware system for this script.
168 //////////////
169 string SM_CONFIGURE_INFO = "#sm-info#";
170     // sets important information this script will use, such as (1) the channel for listening.
171 string SM_POP_MAIN_MENU_UP = "#sm-main#";
172     // causes the main menu to be displayed.  this requires an avatar name and avatar key for the
173     // target of the menu.
174 //////////////
175 string SM_EVENT_MENU_CLICK = "#sm-clik#";
176     // the user has requested a particular menu item that this script cannot fulfill.  the
177     // event is generated back to the client of this script for handling.  it will include (1) the
178     // menu name in question, (2) the item clicked, (3) the avatar name, and (4) the avatar key.
179 //////////////
180
181 // card configurator link message API:
182 //////////////
183 // do not redefine these constants.
184 integer CARD_CONFIGURATOR_HUFFWARE_ID = 10042;
185     // the unique id within the huffware system for the card configurator script to
186     // accept commands on.  this is used in llMessageLinked as the num parameter.
187 //////////////
188 string BAD_NOTECARD_TEXT = "*badcrd*";
189     // the sign that we hated the notecards we found, or there were none.
190 string FINISHED_READING_NOTECARDS = "**finished**";
191     // the sign that we are done plowing through the card we found.
192 string BEGIN_READING_NOTECARD_COMMAND = "#read-cfg#";
193     // requests that the configurator find a good notecard and read its contents.
194     // it should send the contents via the alert below.  first parm is the signature and
195     // second is the wrapped list of valid item prefixes.
196 string READ_PARTICULAR_NOTECARD_COMMAND = "#read-note#";
197     // requests that the configurator find a good notecard and read its contents.
198     // it should send the contents via the alert below.  first two parms are the same as
199     // begin reading notecard, and the third parameter is the name of the specific notecard.
200 string CARD_CONFIG_RECEIVED_ALERT = "#cfg-event-upd#";
201     // this message is sent when the configurator has found some data updates or has finished
202     // reading the configuration file.
203 //////////////
204
205 // jaunting library API:
206 //////////////
207 // do not redefine these constants.
208 integer JAUNT_HUFFWARE_ID = 10008;
209     // the unique id within the huffware system for the jaunt script to
210     // accept commands on.  this is used in llMessageLinked as the num parameter.
211 //////////////
212 // commands available via the jaunting library:
213 string JAUNT_COMMAND = "#jaunt#";
214     // command used to tell jaunt script to move object.  pass a vector with the location.
215 //string FULL_STOP_COMMAND = "#fullstop#";
216     // command used to bring object to a halt.
217 //string REVERSE_VELOCITY_COMMAND = "#reverse#";
218     // makes the object reverse its velocity and travel back from whence it came.
219 //string SET_VELOCITY_COMMAND = "#setvelocity#";
220     // makes the velocity equal to the vector passed as the first parameter.
221 //string JAUNT_UP_COMMAND = "#jauntup#";
222 //string JAUNT_DOWN_COMMAND = "#jauntdown#";
223     // commands for height adjustment.  pass a float for number of meters to move.
224 //string JAUNT_LIST_COMMAND = "#jauntlist#";
225     // like regular jaunt, but expects a string in jaunt notecard format with vectors.
226     // the second parameter, if any, should be 1 for forwards traversal and 0 for backwards.
227 //
228 //////////////
229
230 // global variables used in the script.
231
232 // configuration variables...
233 integer all_setup_finished = FALSE;  // have we read our configuration yet?
234 integer configuration_pending = FALSE;  // true if the setup process (config and arms) is still going on.
235 integer listening_handle = 0;  // tracks our handle for listening to commands.
236
237 // matching variables...
238 string global_target_name = "";  // the name of the object being sought.
239
240 list global_matches_found;  // a list of keys that match the specified search terms.
241 list global_positions_found;  // matches list of positions for the detected objects.
242
243 // jaunting variables...
244
245 vector global_home_posn;  // the location where the search bot is located.
246 vector last_safe_target;  // the last place we jaunted to that was safe.
247
248 integer next_step_snoozes_left;  // pauses allowed before deciding jaunt will not respond.
249
250 integer jaunt_responses_awaited = 0;  // true when a jaunt is pending.
251 integer last_jaunt_was_success = FALSE;  // result of jaunting received by message.
252
253 vector current_rotation = <0.0, 0.0, 0.0>;
254   // the current rotation around each axis for object.
255
256 // spiral variables...
257
258 integer global_current_step = 0;  // the current position in the search spiral.
259 float spiral_start_angle = 0.0;  // how many radians to offset spiral by for this pass.
260 integer global_current_pass = 0;  // which spiral number are we working on?
261
262 integer tried_jump_homeward = FALSE;
263     // when retracing to home, this records if we already tried the jump home that should
264     // come in between the spiral jaunt.
265
266 integer retracing_steps = FALSE;
267     // this is true when we are trying to get back home after finishing our spirals.
268
269 // object maintenance variables...
270
271 integer reset_for_next_timer = FALSE;  // true when next timer hit should do a reset.
272
273 integer running_a_search = FALSE;  // true if the object is seeking matches.
274
275 //////////////
276
277 // constants that should not be messed with.
278
279 float MAX_SLACK_DISTANCE = 0.01;  // how close we need to be to a target.
280
281 integer ALL_SEEKER_ALERT = -1;  // communicates with all search rods.
282
283 integer last_time_ordered_stop_sensing = 0;
284     // tracks when we last tried to order the search rods to stop sensing matches.
285
286 // jaunting variables...
287
288 vector last_jaunt_target;
289     // where we're currently headed.  this variable is mostly for record keeping, so we want
290     // to update it whenever we jaunt someplace.
291
292 //////////////
293
294 // main functions for getting work done as the searchbert...
295
296 // pointing that doesn't use particles, but just aims a search rod.
297 aim_at_position(integer which_seeker, vector targetPosition) {
298     list paramList = [targetPosition];
299     request_from_seeker(which_seeker, llDumpList2String(paramList,
300         HUFFWARE_PARM_SEPARATOR), HUFF_SEARCH_JUST_POINT);
301 }
302
303 // tells the rod at "which_seeker" link to do a sensor scan.
304 start_sensing(integer which_seeker, float max_range, float arc_angle, string search_pattern,
305     integer matches_sought)
306 {
307     list paramList = [max_range, arc_angle, search_pattern, matches_sought];
308     request_from_seeker(which_seeker, llDumpList2String(paramList,
309         HUFFWARE_PARM_SEPARATOR), HUFF_SEARCH_SENSEI);
310 }
311
312 // tells all of the seeker search rods to stop sensing matches.
313 stop_sensing()
314 {
315     // make sure that we are not just blasting this order over and over.
316     if (llGetUnixTime() != last_time_ordered_stop_sensing) {
317         last_time_ordered_stop_sensing = llGetUnixTime();
318         request_from_seeker(ALL_SEEKER_ALERT, "", HUFF_SEARCH_STOP_SENSE);
319     }
320 }
321
322 // tell the seeker arms to find what we asked them about.
323 request_ping() { request_from_seeker(ALL_SEEKER_ALERT, "", HUFF_SEARCH_PING); }
324
325 //////////////
326
327 // teleports to the vector specified.  this invokes a method in the jaunting library
328 // which will return its result asynchronously.  thus we can't just expect that we
329 // have arrived at the target by the end of this function; we need to get back the
330 // IPC message in linked_message.
331 jaunt_to_target(vector target)
332 {
333     if (!TRAVERSE_LANDS) {
334         // this is an important restriction since we don't want to get trapped in weird
335         // land perm screwups, like not being able to re-enter the land where we started,
336         // if that parcel option is set.
337         if (llGetLandOwnerAt(llGetPos()) != llGetLandOwnerAt(target)) {
338             return;
339         }
340     }
341     
342     // reset our snoozer count, since we're doing a new jaunt now.
343     next_step_snoozes_left += MAX_STEP_SNOOZES;
344     jaunt_responses_awaited++;
345     // record the current target.
346     last_jaunt_target = target;
347
348     float minimum_rod_angle_addition = 0.2;
349     float maximum_rod_angle_addition = 10.8;
350     // add small random amounts to the current rotation to expose more matches.
351     current_rotation +=
352         <(minimum_rod_angle_addition + llFrand(maximum_rod_angle_addition)) * DEG_TO_RAD,
353         (minimum_rod_angle_addition + llFrand(maximum_rod_angle_addition)) * DEG_TO_RAD,
354         (minimum_rod_angle_addition + llFrand(maximum_rod_angle_addition)) * DEG_TO_RAD>;
355     rotation new_rot = llEuler2Rot(current_rotation);
356 //    log_it("new rot to " + (string)new_rot + " based on " + (string)current_rotation);
357     llMessageLinked(LINK_THIS, JAUNT_HUFFWARE_ID, JAUNT_COMMAND,
358         (string)target + HUFFWARE_PARM_SEPARATOR + (string)new_rot);
359 }
360
361 // provides the position on a spiral that has "loops" total loops (counted by
362 // how many times a line from the center to the outer "radius" is crossed).
363 // this provides an x and y offset from 0,0 for where the spiral should be if
364 // one were to walk it in "total_steps" (where the center is step 0).  this is
365 // given for the current "step" one is at.  the "start_angle" is the number of
366 // radians to start at for the spiral, to allow different areas to be traversed.
367 vector trace_spiral(float loops, float radius, integer total_steps, integer step,
368     float start_angle)
369 {
370     float total_radians = TWO_PI * loops;
371     float angle_per_step = total_radians / (float)total_steps;
372     float distance = radius / (float)total_steps * (float)step;
373     float current_angle = start_angle + angle_per_step * (float)step;
374     float current_z = 0;
375     if (TRAVELLING_UPWARDS) {
376         // add in the vertical distance for this step.
377         current_z = MAX_UPWARDS_DISTANCE / total_steps * step;
378     }
379     return <distance * llCos(-current_angle), distance * llSin(-current_angle), current_z>;
380 }
381
382 // this describes the list of matches in local chat.
383 chat_about_matches()
384 {
385     integer len = llGetListLength(global_matches_found);
386     if (!len) {
387         llSay(0, global_target_name + " not found within a distance of "
388             + (string) (SENSOR_MAX_RANGE + MAX_SPIRAL_RADIUS) + " meters from here.");
389         return;
390     }
391     string addition;
392     if (len != 1) addition = "es";
393     string match_description = (string)len + " match" + addition + " for search "
394         + "pattern \'" + global_target_name + "\':\n";
395     integer i;
396     // only show a maximum number of matches as we have seeker objects.
397     if (len > MAX_MATCHES) len = MAX_MATCHES;
398     for (i = 0; i < len; i++) {
399         if (llStringLength(match_description) > 350) {
400             llSay(0, "\n" + match_description);
401             match_description = "";
402         } else if (i != 0) match_description += "\n";
403         key targetKey = llList2Key(global_matches_found, i);
404         vector targetPos = llList2Vector(global_positions_found, i);
405         match_description += llKey2Name(targetKey)
406             + " @ " + vector_to_string(targetPos)
407             + " [" + (string) targetKey + "]";
408     }
409     llSay(0, "\n" + match_description);
410 }
411
412 // once we accumulate a set of matches, we want to show them off.
413 show_matches()
414 {
415     llSetRot(llEuler2Rot(ZERO_VECTOR));  // set the object to point at the zero vector.    
416     reset_rod(ALL_SEEKER_ALERT);  // clean up any current pointing first.
417     chat_about_matches();  // say where the matches are.
418     
419     integer i;
420     integer which_locater = 0;  // which pointer to use.
421     // only show a maximum number of matches as we have seeker objects.
422     integer len = llGetListLength(global_matches_found);
423     if (len > MAX_MATCHES) len = MAX_MATCHES;
424     for (i = 0; i < len; i++) {
425         key targetKey = llList2Key(global_matches_found, i);
426         vector targetPos = llList2Vector(global_positions_found, i);
427         point_at_with_particles(which_locater++, targetKey, targetPos);
428     }
429 }
430
431 // makes sure that a target we are given is above ground.  this used to do a
432 // lot more checking, but really being above ground is the most important thing
433 // for us to check at this level of the code.
434 vector clean_target(vector to_clean)
435 {
436     vector to_return = to_clean;
437     float ground_height = llGround(to_return - llGetPos());
438 //log_it("ground height here: " + (string)ground_height);
439
440     // we'll adjust the basic ground height by adding in the object's height.
441     list bounds = llGetBoundingBox(llGetKey());
442 //hmmm: we have found a bug in opensim in that the bounding box only covers the root prim.
443 // this needs to be reported.
444     vector min = llList2Vector(bounds, 0);
445     vector max = llList2Vector(bounds, 1);
446 //log_it("calcd: min=" + (string)min + " max=" + (string)max);
447
448 //real math    float distance_to_add = llVecDist(<0, 0, min.z>, <0, 0, max.z>) / 2.0;
449 //below is bogus math for opensim currently.
450     float distance_to_add = llVecDist(<0, 0, min.z>, <0, 0, max.z>) * 1.1;
451     
452 //log_it("distance_to_add: " + (string)distance_to_add);
453     if (to_return.z - MINIMUM_HEIGHT_ABOVE_GROUND <= ground_height + distance_to_add) {
454         // patch up the height to be above ground.
455         to_return.z = ground_height + distance_to_add + MINIMUM_HEIGHT_ABOVE_GROUND;
456     }
457     return to_return;
458 }
459
460 // shows all the matches by pointing our seekers at them and emitting a targeted
461 // trail of particles.  this method should only be called after the final jaunt
462 // back to home has occurred.
463 show_off_what_was_found()
464 {
465     // show the positions of what was found.
466     show_matches();
467     llSetTimerEvent(SNOOZE_BEFORE_RESET);
468     reset_for_next_timer = TRUE;
469 }
470
471 // stops the device from travelling around and asking for help from the search rods.
472 integer finish_spiral_traversal()
473 {
474 //log_it("got to finish spiral...");
475     stop_sensing();  // turn off all sensors.
476
477     // are we close enough to home to declare victory?
478     if (llVecDist(llGetPos(), global_home_posn) > MAX_SLACK_DISTANCE) {
479         if (!tried_jump_homeward) {
480             // there are enough here; we completed early.
481             tried_jump_homeward = TRUE;
482 //log_it("finish spiral sees us as too far from home, jaunting there.");
483             jaunt_to_target(global_home_posn);
484             return FALSE;
485         } else {
486             // we already tried a jump home.  dang, let's try spiraling.
487 //log_it("finish spiral failed jaunt home, continuing spiral.");
488             tried_jump_homeward = FALSE;  // reset that we tried this.
489             return TRUE;
490         }
491     }
492
493 //log_it("finish spiral success, showing off matches");
494     
495     // this object has done enough spiraling.
496     llSetTimerEvent(NORMAL_TIMER_INTERVAL);  // turn off jump timer.
497     running_a_search = FALSE;  // reset our state since the search is done.
498     show_off_what_was_found();
499     return FALSE;
500 }
501
502 // our timer handling function; this will move the search engine to the next place on
503 // the current spiral (or to the start of the next spiral) when it is called.
504 // if we're not currently running a search, then it will just periodically update the
505 // sub-prims to make sure they have the latest versions.
506 handle_timer()
507 {
508     if (!all_setup_finished) {
509         complain_about_config(!configuration_pending);
510         return;  // should not get here.
511     }
512     
513     if (reset_for_next_timer) {
514         // this timer intends a reset so we don't just keep pointing forever.
515         llSay(0, "Timed Out: resetting matches now.");
516         reset_search();
517         return;
518     }
519
520     if (!running_a_search) {
521 //log_it("exiting timer since not searching.");
522         return;
523     }
524
525 //llSay(0, "next search move!");
526             
527     // make sure we don't allow too many pauses while awaiting a jaunt completion.
528     if (next_step_snoozes_left-- <= 0) {
529         log_it("waiting to arrive failed!  ran out of snoozes trying to get to "
530             + (string)last_jaunt_target);
531     } else if (jaunt_responses_awaited) {
532         // not ready to do next step yet.
533         return;
534     }
535     if (next_step_snoozes_left < 0) {
536 //log_it("got below zero in next step snoozes!");
537         next_step_snoozes_left = 0;
538     }
539     
540     if (llGetListLength(global_matches_found) < MAX_MATCHES) {
541         // tell the sensor arms to look for stuff right here.
542         request_ping();
543     }
544
545     // make sure we're not already done finding enough objects.
546     if (llGetListLength(global_matches_found) >= MAX_MATCHES) retracing_steps = TRUE;
547     
548     // check whether we're trying to get home again, rather than moving forward.
549     if (retracing_steps) {
550 //log_it("retrace steps in timed move.");
551         integer keep_going = finish_spiral_traversal();
552         if (!keep_going) return;
553     }
554
555     // see if the object has reached the end of its tether and should report
556     // home with results.  we do this by taking a spiral pass outwards from home
557     // and a return pass to get back to home.  if we've used up all our spiral
558     // traversals, then it's time to stay home and show the matches.
559     integer done_with_this_spiral = FALSE;
560     if (global_current_pass % 2 == 0) {
561         // even passes are outward bound ones.  we're done when we've gotten to TOTAL_STEPS.
562         if (global_current_step++ > TOTAL_STEPS) done_with_this_spiral = TRUE;
563     } else {
564         // odd passes are for returning to home.  those are done when they hit zero.
565         if (global_current_step-- <= 0) done_with_this_spiral = TRUE;
566     }
567     
568     if (done_with_this_spiral) {
569         // now evaluate whether we're totally done or just need to move to next spiral,
570         // whether inward or outward.
571         if (++global_current_pass < 2 * MAX_SPIRAL_TRAVERSALS) {
572             // just step to the next spiral.
573 //log_it("moving to next spiral");
574             if (global_current_pass % 2 == 0) {
575                 // even passes are outward bound ones.
576                 global_current_step = 0;
577                 // add some different angular rotation to get more matches for this spiral.
578                 spiral_start_angle += TWO_PI / (MAX_SPIRAL_TRAVERSALS + 1);
579             } else {
580                 // odd passes are for returning to home.
581                 global_current_step = TOTAL_STEPS;
582             }
583 //hmmm: not currently resetting that angle for next search.
584         } else {
585 //log_it("done with spiral mode, now retracing steps.");
586             // we finished the search pattern.
587             retracing_steps = TRUE;
588             global_current_pass--;  // try spiraling back.
589             global_current_step = TOTAL_STEPS;
590             return;
591         }
592     }        
593
594     // normal activity here--pick the next place on the spiral to look for objects.        
595     vector new_posn = trace_spiral(SPIRAL_LOOPS, MAX_SPIRAL_RADIUS,
596         TOTAL_STEPS, global_current_step, spiral_start_angle);
597 //log_it("next step " + (string)global_current_step + " to " + (string)new_posn);        
598     // go to that location now, or rather, when the jaunting library gets the message.
599     vector new_target = clean_target(new_posn + global_home_posn);
600     jaunt_to_target(new_target);
601 }
602
603 // makes sure we are ready to run.  TRUE is returned if we're good.
604 integer test_health()
605 {
606     if (!configuration_pending && !all_setup_finished) {
607         llSay(0, "Configuration is not good yet; retrying.");
608         return FALSE;
609     }
610     return TRUE;
611 }
612
613 // deals with the jaunter telling us about a completed jump.
614 process_jaunt_response(string str)
615 {
616     jaunt_responses_awaited--;  // one less response being awaited.
617     if (jaunt_responses_awaited < 0) {
618         if (DEBUGGING)
619             log_it("erroneously went below zero for jaunt responses!");
620         jaunt_responses_awaited = 0;
621     }
622     // unpack the reply.
623     list parms = llParseString2List(str, [HUFFWARE_PARM_SEPARATOR], []);
624     last_jaunt_was_success = (integer)llList2String(parms, 0);
625     vector posn = (vector)llList2String(parms, 1);
626 //log_it("got a reply for a jaunt request, success=" + (string)last_jaunt_was_success + " posn=" + (string)posn);
627     if (last_jaunt_was_success) {
628         last_safe_target = posn;
629     } else {
630         // we had a problem getting to the expected destination, so go to the last place we were
631         // completely safely able to reach.  we should have no problem returning there, since that's
632         // where we should have been coming from when we failed to reach the intended destination.
633 //log_it("bkwd retracing to " + (string)last_safe_target);
634         jaunt_to_target(last_safe_target);
635     }
636 }
637
638 reset_search()
639 {
640     reset_for_next_timer = FALSE;
641
642     llSetTimerEvent(NORMAL_TIMER_INTERVAL);  // back to slow timer hits.
643     reset_rod(ALL_SEEKER_ALERT);  // reset the pointers to camber position.
644     llSetRot(llEuler2Rot(ZERO_VECTOR));  // set the object to point at the zero vector.
645
646     // set the home position to wherever we happen to be right now.
647     global_home_posn = clean_target(llGetPos());
648     llSetPos(global_home_posn);  // get us off the ground.
649     last_safe_target = global_home_posn;
650
651     global_current_step = 0;
652     global_current_pass = 0;
653     global_matches_found = [];
654     global_positions_found = [];
655     next_step_snoozes_left = 4;  // reset to small num, since this is additive.
656     reset_for_next_timer = FALSE;
657     running_a_search = FALSE;
658     tried_jump_homeward = FALSE;
659     retracing_steps = FALSE;
660     jaunt_responses_awaited = 0;
661     current_rotation = <0.0, 0.0, 0.0>;
662     // fix a global 'constant' that can't be pre-initiatlized in LSL.
663     SEARCH_ROD_ANGULAR_SWEEP = (PI_BY_TWO / 4.0);
664         // PI_BY_TWO / 4 is 22.25 degrees, which when turned into a sensor cone
665         // will be a range of 45 degrees around the zero vector.
666     
667 }
668
669 initialize()
670 {
671     llSay(0, "Initializing... this may take a few seconds.");
672     auto_retire();
673     llSleep(0.2);  // we ensure part of the claim above by waiting for sub-scripts to start.
674     request_configuration("");
675 }
676
677 // complete the initialization once we know our configuration.
678 finish_initializing()
679 {
680     all_setup_finished = TRUE;  // cancel the time-out checker.
681     configuration_pending = FALSE;
682
683     // in case we already have some arms, clean up their pointing states.
684     reset_search();
685     // set the position of rotation back to zero.
686     llSetRot(<0.0, 0.0, 0.0, 1.0>);
687     // listen for commands from our chat channel.
688     listening_handle = llListen(HUFF_SEARCH_CHAT_CHANNEL, "", NULL_KEY, "");
689
690     llSay(0, "Running and ready to search.  Touch for more instructions.");
691
692     llSetTimerEvent(NORMAL_TIMER_INTERVAL);    
693 }
694
695 // this points the rods at all angles we possibly can to get the best coverage.
696 // if show_particles is true, then a demo mode is used that points at the positions
697 // that the rods are aiming at.
698 skew_rod_angles(integer show_particles)
699 {
700     reset_rod(ALL_SEEKER_ALERT);
701         // point everyone straight up for the moment.        
702     float radius = 4.0;  // arbitrary distance of target we're aiming at.
703     integer which_child;
704     integer total_searchers = llGetNumberOfPrims() - 1;
705     float angle_per_step = TWO_PI / (float)total_searchers;
706     // use a circle for the x and y coordinates.
707     for (which_child = 0; which_child < total_searchers; which_child++) {
708         vector spinner = <
709             radius * llCos((float)which_child * angle_per_step),
710             radius * llSin((float)which_child * angle_per_step),
711             radius * llCos((float)which_child * angle_per_step / 2.0)>;
712         vector target_location = llGetPos() + spinner;
713         if (!show_particles) {
714             aim_at_position(which_child, target_location);
715         } else {
716             point_at_with_particles(which_child, NULL_KEY, target_location);
717         }
718     }
719 }
720
721 // if "noisy" is true, this says out loud that the searchbert is busy.
722 integer check_if_search_pending(integer noisy)
723 {
724     if (running_a_search) {
725         if (noisy) llSay(0, "A search is still pending.  Please wait for that to finish.");
726         return TRUE;  // still working on a search.
727     }
728     return FALSE;  // not busy.
729 }
730
731 // processes a message coming back from a search rod or from the jaunter library.
732 handle_link_message(integer which, integer num, string msg, key id)
733 {
734     if ( (num == CARD_CONFIGURATOR_HUFFWARE_ID + REPLY_DISTANCE)
735             && (msg == CARD_CONFIG_RECEIVED_ALERT) ) {
736         // the first element of the list will still be the notecard name.
737         consume_configuration(llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []));
738         return;
739     }
740     
741     if ( (num == BUTTON_PUSHER_HUFFWARE_ID +  REPLY_DISTANCE)
742             && (msg == BUTTON_PUSHED_ALERT) ) {
743         if (id == ARMS_ARE_GOOD_BUTTON_NAME) {
744             finish_initializing();
745         } else if (id == PROBLEM_WITH_MY_THUMBS_BUTTON_NAME) {
746             complain_about_config(TRUE);
747         }
748         return;
749     }
750     
751     if (num == JAUNT_HUFFWARE_ID + REPLY_DISTANCE) {
752         if (msg == JAUNT_COMMAND) {
753             process_jaunt_response(id);
754         }
755         return;
756     }
757     
758     list parms;
759     
760     if ( (num == SEARCHBERT_MENUS_HUFFWARE_ID + REPLY_DISTANCE) && (msg == SM_EVENT_MENU_CLICK) ) {
761         parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
762         process_menu_choice(llList2String(parms, 0), llList2String(parms, 2), llList2String(parms, 3),
763             llList2String(parms, 1));
764         return;
765     }
766     
767     if (num != HUFF_SEARCH_POINTER_HUFFWARE_ID + REPLY_DISTANCE) return;  // not for us.
768     if (msg != HUFF_SEARCH_MATCH_EVENT) return;  // also not for us.
769         
770     // make sure this is not already redundant, before doing a costly list search.
771     if (llGetListLength(global_matches_found) >= MAX_MATCHES) {
772         // we have enough already.
773         stop_sensing();
774         return;
775     }
776 //hmmm: searchbert arms are still backwards.
777     
778 //log_it("unpacking " + (string)llStringLength(id) + " byte string.");
779     // fluff out the list back from the encoded string.
780     parms = llParseString2List(id, [HUFFWARE_PARM_SEPARATOR], []);
781 //log_it("received " + (string)llGetListLength(parms) + " element list from string.");
782
783     while (llGetListLength(parms) > 1) {
784         // unpack the match that one of our seekers found for us.
785         key found = (string)llList2String(parms, 0);
786         if (find_in_list(global_matches_found, found) < 0) {
787             vector posn = (vector)llList2String(parms, 1);
788             // that key wasn't already listed, so we can drop it in the list.
789             global_matches_found += found;
790             global_positions_found += posn;
791         }
792         // truncate the list by removing those two pieces we already handled.
793         parms = llDeleteSubList(parms, 0, 1);
794         if (llGetListLength(global_matches_found) >= MAX_MATCHES) {
795             // we can bail out of the list processing now; we have enough already.
796             parms = [];
797         }
798     }
799 }
800
801 // uses the configuration item as the value of one of our variables, if we can figure out
802 // the name involved.
803 apply_variable_definition(string var, string value)
804 {
805 //log_it("[" + var + "=" + value + "]");
806     if (var == "max_matches") {
807         MAX_MATCHES = (integer)value;
808     } else if (var == "max_spiral_radius") {
809         MAX_SPIRAL_RADIUS = (float)value;
810     } else if (var == "sensor_max_range") {
811         SENSOR_MAX_RANGE = (float)value;
812     } else if (var == "huff_search_chat_channel") {
813         // we have to hook up our ears to the new channel here.
814         if (listening_handle) llListenRemove(listening_handle);
815         HUFF_SEARCH_CHAT_CHANNEL = (integer)value;
816         listening_handle = llListen(HUFF_SEARCH_CHAT_CHANNEL, "", NULL_KEY, "");
817     } else if (var == "traverse_lands") {
818         TRAVERSE_LANDS = (integer)value;
819     } else if (var == "spiral_loops") {
820         SPIRAL_LOOPS = (integer)value;
821     } else if (var == "total_steps") {
822         TOTAL_STEPS = (integer)value;
823     } else if (var == "max_spiral_traversals") {
824         MAX_SPIRAL_TRAVERSALS = (integer)value;
825     } else if (var == "search_rod_angular_sweep") {
826         SEARCH_ROD_ANGULAR_SWEEP = (float)value;
827     } else if (var == "travelling_upwards") {
828         TRAVELLING_UPWARDS = (integer)value;
829     } else if (var == "max_upwards_distance") {
830         MAX_UPWARDS_DISTANCE = (float)value;
831     } else {
832         if (DEBUGGING)
833             log_it("unknown variable '" + var + "' tried to define value = " + value);
834     }
835 }
836
837 // we have to consume the configuration in digestible chunks, since the pieces may
838 // be too large for sending in link messages.
839 consume_configuration(list config_chunk)
840 {
841     string notecard_name = llList2String(config_chunk, 0);
842     if (notecard_name == BAD_NOTECARD_TEXT) {
843         complain_about_config(FALSE);
844         return;
845     } else if (notecard_name == FINISHED_READING_NOTECARDS) {
846         // we're ready to make use of our new configuration now.
847         if (DEBUGGING)
848             log_it("Configuration has been read, need validation of limbs.");
849         configuration_pending = FALSE;  // no longer waiting for notecard config.
850         // configure the menu system to know what channel to talk about.
851         llMessageLinked(LINK_THIS, SEARCHBERT_MENUS_HUFFWARE_ID, SM_CONFIGURE_INFO,
852             wrap_parameters([HUFF_SEARCH_CHAT_CHANNEL]));
853         // now check our arms to make sure they're all ready.
854         llMessageLinked(LINK_THIS, BUTTON_PUSHER_HUFFWARE_ID, BUTTON_PUSHED_ALERT, CHECK_ARMS_BUTTON_NAME);
855         return;
856     }
857     
858     integer sandy;
859     // scan the configuration items two at a time, but skip the notecard name at slot zero.
860     for (sandy = 1; sandy < llGetListLength(config_chunk); sandy += 2) {
861         string var = llList2String(config_chunk, sandy);
862         string value = llList2String(config_chunk, sandy + 1);
863         apply_variable_definition(var, value);
864     }
865     // clear the list out now that we've eaten its contents.
866     config_chunk = [];
867 }
868
869 //////////////
870
871 // sends a message to the "which_seeker" search object.  the "parameters" should be a
872 // string-ized list of parameters.  the "command" is the specific action requested.
873 request_from_seeker(integer which_seeker, string parameters, string command)
874 {
875     integer linkNumber = which_seeker + 2;
876     if (which_seeker == ALL_SEEKER_ALERT) linkNumber = LINK_ALL_OTHERS;
877     llMessageLinked(linkNumber, HUFF_SEARCH_POINTER_HUFFWARE_ID, command, parameters);
878 }
879
880 // aim the specified seeker rod at the object with the key and position.
881 point_at_with_particles(integer which_seeker, key targetId, vector targetPosition)
882 {
883     list paramList = [targetId, targetPosition];
884     request_from_seeker(which_seeker, llDumpList2String(paramList, HUFFWARE_PARM_SEPARATOR),
885         HUFF_SEARCH_POINT_PARTY);
886 }
887
888 // stop the particle stream running at the specified search rod.
889 reset_rod(integer which_seeker) { request_from_seeker(which_seeker, "", HUFF_SEARCH_RESET); }
890
891 // support for reading configuration from notecards...
892
893 string CARD_CONFIGURATOR_SIGNATURE = "#searchbert";
894     // the notecard signature we use for our configuration.
895
896 // tries to load a searchbert configuration notecard with the name specified.  if it's blank,
897 // then any config notecard will do.
898 request_configuration(string notecard_name)
899 {
900     if (DEBUGGING) log_it("have hit request_configuration.");
901     all_setup_finished = FALSE;
902     configuration_pending = TRUE;
903     // figure out whether we have a pre-chosen configuration or not.
904     if (llStringLength(notecard_name) == 0) {
905         // start reading the configuration from whatever card.
906         llMessageLinked(LINK_THIS, CARD_CONFIGURATOR_HUFFWARE_ID,
907             BEGIN_READING_NOTECARD_COMMAND, CARD_CONFIGURATOR_SIGNATURE + HUFFWARE_PARM_SEPARATOR
908             + wrap_item_list([]));
909     } else {
910         // get the specific one they wanted.
911         if (DEBUGGING) log_it("Reading configuration from notecard: " + notecard_name);
912         llMessageLinked(LINK_THIS, CARD_CONFIGURATOR_HUFFWARE_ID,
913             READ_PARTICULAR_NOTECARD_COMMAND, CARD_CONFIGURATOR_SIGNATURE + HUFFWARE_PARM_SEPARATOR
914             + wrap_item_list([]) + HUFFWARE_PARM_SEPARATOR
915             + notecard_name);
916     }
917
918     // make sure we complete this in time.
919     llSetTimerEvent(STARTUP_TIME_ALLOWED);
920 }
921
922 // this is used when we've totally failed to start up properly.
923 // if "arms_problem" is true, then the issue is considered to be that the seeker arms
924 // are missing.
925 complain_about_config(integer arms_problem)
926 {
927     configuration_pending = FALSE;  // it's failed, so we no longer pause for it.
928     string explanation = "something prevented me from putting my seeker arms back on";
929     if (!arms_problem) explanation = "either no notecard had the prefix '"
930         + CARD_CONFIGURATOR_SIGNATURE + "'\n"
931         + "or this sim is very busy and timed out";
932     // we hated the notecards we found, or there were none, or our arms are still ripped off.
933     llOwnerSay("Sorry...  " + explanation + ".\nI will restart now to try again.");
934     llSleep(4);
935     llResetScript();
936 }
937
938 // handles when a menu has been clicked on.
939 process_menu_choice(string menu_name, string av_name, string av_key, string which_choice)
940 {
941     if (menu_name == "main") {
942         if (which_choice == "Matches") {
943             // if there are any current matches, describe them again.
944             if (llGetListLength(global_matches_found)) show_off_what_was_found();
945             else llSay(0, "There are no current matches.");
946             return;
947         } else if (which_choice == "Reset") {
948             carefully_reset_search_list(av_key);
949             return;
950         }
951     }
952 //other things will come...    
953     
954     if (DEBUGGING)
955         log_it("non-implemented menu: " + menu_name + "/" + which_choice + " for " + av_name);
956 }
957
958 // reset the search list and get ready for a new search.
959 carefully_reset_search_list(key id)
960 {
961     if (check_if_search_pending(FALSE)) {
962         // only allow reset while running if it's the owner.
963         if (id != llGetOwner()) {
964             check_if_search_pending(TRUE);  // be noisy now.
965             return;  // we're busy.
966         }
967         llOwnerSay("Stopping active search.");
968         retracing_steps = TRUE;
969         return;
970     }
971     llSay(0, "Resetting matches.");
972     reset_search();
973 }
974
975 //////////////
976 // from hufflets...
977
978 //////////////
979 // huffware script: auto-retire, by fred huffhines, version 2.8.
980 // distributed under BSD-like license.
981 //   !!  keep in mind that this code must be *copied* into another
982 //   !!  script that you wish to add auto-retirement capability to.
983 // when a script has auto_retire in it, it can be dropped into an
984 // object and the most recent version of the script will destroy
985 // all older versions.
986 //
987 // the version numbers are embedded into the script names themselves.
988 // the notation for versions uses a letter 'v', followed by two numbers
989 // in the form "major.minor".
990 // major and minor versions are implicitly considered as a floating point
991 // number that increases with each newer version of the script.  thus,
992 // "hazmap v0.1" might be the first script in the "hazmap" script continuum,
993 // and "hazmap v3.2" is a more recent version.
994 //
995 // example usage of the auto-retirement script:
996 //     default {
997 //         state_entry() {
998 //            auto_retire();  // make sure newest addition is only version of script.
999 //        }
1000 //     }
1001 // this script is partly based on the self-upgrading scripts from markov brodsky
1002 // and jippen faddoul.
1003 //////////////
1004 auto_retire() {
1005     string self = llGetScriptName();  // the name of this script.
1006     list split = compute_basename_and_version(self);
1007     if (llGetListLength(split) != 2) return;  // nothing to do for this script.
1008     string basename = llList2String(split, 0);  // script name with no version attached.
1009     string version_string = llList2String(split, 1);  // the version found.
1010     integer posn;
1011     // find any scripts that match the basename.  they are variants of this script.
1012     for (posn = llGetInventoryNumber(INVENTORY_SCRIPT) - 1; posn >= 0; posn--) {
1013         string curr_script = llGetInventoryName(INVENTORY_SCRIPT, posn);
1014         if ( (curr_script != self) && (llSubStringIndex(curr_script, basename) == 0) ) {
1015             // found a basic match at least.
1016             list inv_split = compute_basename_and_version(curr_script);
1017             if (llGetListLength(inv_split) == 2) {
1018                 // see if this script is more ancient.
1019                 string inv_version_string = llList2String(inv_split, 1);  // the version found.
1020                 // must make sure that the retiring script is completely the identical basename;
1021                 // just matching in the front doesn't make it a relative.
1022                 if ( (llList2String(inv_split, 0) == basename)
1023                     && ((float)inv_version_string < (float)version_string) ) {
1024                     // remove script with same name from inventory that has inferior version.
1025                     llRemoveInventory(curr_script);
1026                 }
1027             }
1028         }
1029     }
1030 }
1031 //
1032 // separates the base script name and version number.  used by auto_retire.
1033 list compute_basename_and_version(string to_chop_up)
1034 {
1035     // minimum script name is 2 characters plus a version.
1036     integer space_v_posn;
1037     // find the last useful space and 'v' combo.
1038     for (space_v_posn = llStringLength(to_chop_up) - 3;
1039         (space_v_posn >= 2) && (llGetSubString(to_chop_up, space_v_posn, space_v_posn + 1) != " v");
1040         space_v_posn--) {
1041         // look for space and v but do nothing else.
1042     }
1043     if (space_v_posn < 2) return [];  // no space found.
1044     // now we zoom through the stuff after our beloved v character and find any evil
1045     // space characters, which are most likely from SL having found a duplicate item
1046     // name and not so helpfully renamed it for us.
1047     integer indy;
1048     for (indy = llStringLength(to_chop_up) - 1; indy > space_v_posn; indy--) {
1049         if (llGetSubString(to_chop_up, indy, indy) == " ") {
1050             // found one; zap it.  since we're going backwards we don't need to
1051             // adjust the loop at all.
1052             to_chop_up = llDeleteSubString(to_chop_up, indy, indy);
1053         }
1054     }
1055     string full_suffix = llGetSubString(to_chop_up, space_v_posn, -1);
1056     // ditch the space character for our numerical check.
1057     string chop_suffix = llGetSubString(full_suffix, 1, llStringLength(full_suffix) - 1);
1058     // strip out a 'v' if there is one.
1059     if (llGetSubString(chop_suffix, 0, 0) == "v")
1060         chop_suffix = llGetSubString(chop_suffix, 1, llStringLength(chop_suffix) - 1);
1061     // if valid floating point number and greater than zero, that works for our version.
1062     string basename = to_chop_up;  // script name with no version attached.
1063     if ((float)chop_suffix > 0.0) {
1064         // this is a big success right here.
1065         basename = llGetSubString(to_chop_up, 0, -llStringLength(full_suffix) - 1);
1066         return [ basename, chop_suffix ];
1067     }
1068     // seems like we found nothing useful.
1069     return [];
1070 }
1071 //
1072 //////////////
1073
1074 integer debug_num = 0;
1075 // a debugging output method.  can be disabled entirely in one place.
1076 log_it(string to_say)
1077 {
1078     debug_num++;
1079     // tell this to the owner.    
1080     llWhisper(0, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
1081     // say this on an unusual channel for chat if it's not intended for general public.
1082 //    llSay(108, llGetScriptName() + "[" + (string)debug_num + "] " + to_say);
1083     // say this on open chat that anyone can hear.  we take off the bling for this one.
1084 //    llSay(0, to_say);
1085 }
1086
1087 // joins a list of parameters using the parameter sentinel for the library.
1088 string wrap_parameters(list to_flatten)
1089 { return llDumpList2String(to_flatten, HUFFWARE_PARM_SEPARATOR); }
1090
1091 string wrap_item_list(list to_wrap)
1092 { return llDumpList2String(to_wrap, HUFFWARE_ITEM_SEPARATOR); }
1093
1094 // returns the index of the first occurrence of "pattern" inside
1095 // the "full_string".  if it is not found, then a negative number is returned.
1096 integer find_substring(string full_string, string pattern)
1097 { return llSubStringIndex(llToLower(full_string), llToLower(pattern)); }
1098
1099 // returns TRUE if the "prefix" string is the first part of "compare_with".
1100 integer is_prefix(string compare_with, string prefix)
1101 { return find_substring(compare_with, prefix) == 0; }
1102
1103 // encases a list of vectors in the expected character for the jaunting library.
1104 string wrap_vector_list(list to_wrap)
1105 {
1106     integer len = llGetListLength(to_wrap);
1107     integer i;
1108     string to_return;
1109     for (i = 0; i < len; i++) {
1110         if (i > 0) to_return += "|";
1111         to_return += llList2String(to_wrap, i);
1112     }
1113     return to_return;
1114 }
1115
1116 // locates the string "text" in the list to "search_in".
1117 integer find_in_list(list search_in, string text)
1118
1119     integer len = llGetListLength(search_in);
1120     integer i; 
1121     for (i = 0; i < len; i++) { 
1122         if (llList2String(search_in, i) == text) 
1123             return i; 
1124     } 
1125     return -1;
1126 }
1127
1128 integer float_precision = 2;  // number of digits used when printing floats.
1129
1130 //hmmm: in hufflets yet???
1131 string float_to_string(float to_print)
1132 {
1133     string to_return = (string)to_print;
1134     // find out where the decimal point is in the string.
1135     integer decimal_point_posn = llSubStringIndex(to_return, ".");
1136     if (decimal_point_posn < 0) return to_return;
1137     return llGetSubString(to_return, 0, decimal_point_posn + float_precision);
1138 }
1139
1140 //hmmm: in hufflets yet???
1141 string vector_to_string(vector to_print)
1142 {
1143     string to_return = "<";
1144     to_return += float_to_string(to_print.x);
1145     to_return += ", ";
1146     to_return += float_to_string(to_print.y);
1147     to_return += ", ";
1148     to_return += float_to_string(to_print.z);
1149     to_return += ">";
1150     return to_return;
1151 }
1152
1153 // end hufflets.
1154 //////////////
1155
1156 default {
1157     state_entry() { if (llSubStringIndex(llGetObjectName(), "huffotronic") < 0) state real_default; }
1158     on_rez(integer parm) { state rerun; }
1159 }
1160 state rerun { state_entry() { state default; } }
1161
1162 state real_default {
1163     state_entry() { initialize(); }
1164     
1165     state_exit() { llSetTimerEvent(0); }
1166     
1167     on_rez(integer parm) { state default; }
1168     
1169     timer() { handle_timer(); }
1170
1171     link_message(integer which, integer num, string str, key id)
1172     { handle_link_message(which, num, str, id); }
1173
1174     changed(integer change) {
1175         if (change & CHANGED_INVENTORY) {
1176             llSleep(1.4);  // snooze to allow other things to react first.
1177             request_configuration("");  // see if there's a card update.
1178         }
1179     }
1180
1181     listen(integer chan, string name, key id, string msg) {
1182         if (msg == "#reset") {
1183             carefully_reset_search_list(id);
1184         } else if (is_prefix(msg, "#find ")) {
1185             // needs arms for this trick.
1186             if (!test_health()) state default;
1187             // try to locate the object the user has specified.
1188             if (check_if_search_pending(TRUE)) return;  // we're busy.
1189             reset_search();  // clean out prior state.
1190             global_target_name = llDeleteSubString(msg, 0, 5);  // Delete "#find " from msg
1191             running_a_search = TRUE;  // record that we're searching.
1192             // point all the rods in as many different directions as we can.
1193             skew_rod_angles(FALSE);
1194             // look for any objects near each seeker and in the direction it's pointing.
1195             // we double the arc we might need to try to get more matches.
1196             start_sensing(ALL_SEEKER_ALERT, SENSOR_MAX_RANGE,
1197                 SEARCH_ROD_ANGULAR_SWEEP, global_target_name, MAX_MATCHES);
1198             // start stepping through our search spirals.
1199             llSetTimerEvent(FAST_TIMER_INTERVAL);
1200             llSay(0, "Searching for " + global_target_name);
1201         } else if (is_prefix(msg, "#initialize")) {
1202             llResetScript();
1203         } else if (is_prefix(msg, "#skew")) {
1204             llSetTimerEvent(SNOOZE_BEFORE_RESET);
1205             reset_for_next_timer = TRUE;
1206             skew_rod_angles(TRUE);
1207         } else if (is_prefix(msg, "#channel")) {
1208             HUFF_SEARCH_CHAT_CHANNEL = (integer)llDeleteSubString(msg, 0, 7);
1209             llSay(0, "Changed listening channel to " + (string)HUFF_SEARCH_CHAT_CHANNEL + ".");
1210             llMessageLinked(LINK_THIS, SEARCHBERT_MENUS_HUFFWARE_ID, SM_CONFIGURE_INFO,
1211                 wrap_parameters([HUFF_SEARCH_CHAT_CHANNEL]));
1212             apply_variable_definition("huff_search_chat_channel", (string)HUFF_SEARCH_CHAT_CHANNEL);
1213         }
1214     }
1215     
1216     touch_start(integer num) {
1217         // make sure we have already been set up.
1218         if (!test_health()) state default;
1219
1220         if (check_if_search_pending(TRUE)) return;
1221         
1222         // send a request to the menu script for the users' clicks...
1223         integer indy;
1224         for (indy = 0; indy < num; indy++) {
1225             // request new menu popup for each av that clicked.
1226             llMessageLinked(LINK_THIS, SEARCHBERT_MENUS_HUFFWARE_ID, SM_POP_MAIN_MENU_UP, 
1227                 wrap_parameters([llDetectedName(indy), llDetectedKey(indy)]));
1228         }
1229     }
1230 }
1231
1232 /////////
1233 // original attributions:
1234 // Special Particle Sensor "Brain" Script
1235 // Written by Christopher Omega
1236 // Tasks: Listen to the owner, Parse the owner's message, Signal individual locators
1237 // to reset, Or point at a certain object within 96 meters of the apparatus.
1238 /////////
1239
1240 // note by fred huffhines:
1241 //   much of this script was originally written by the attributed authors above.  however,
1242 //   i have spent a ton of time improving this pair of scripts...  (the brain and the
1243 //   search pointer).  i've added pattern matching (rather than needing to know exact
1244 //   names), added the spiral search traversal method to improve search behavior and
1245 //   get more results, improved the particle streams, and other bits.  i just recently added
1246 //   configurability from notecards for searchbert options and a menuing system to provide
1247 //   help and runtime control over some of the options.  wheeee, it's been a lot of fun.
1248 //      --fred.