Debian Codegraph @

Descent3/OsirisLoadandBind.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /*
2 * Descent 3
3 * Copyright (C) 2024 Parallax Software
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 --- HISTORICAL COMMENTS FOLLOW ---
19
20 * $Logfile: /DescentIII/main/OsirisLoadandBind.cpp $
21 * $Revision: 116 $
22 * $Date: 4/04/00 12:40p $
23 * $Author: Matt $
24 *
25 * OSIRIS functions to load a script DLL and bind to objects
26 *
27 * $Log: /DescentIII/main/OsirisLoadandBind.cpp $
28 *
29 * 116 4/04/00 12:40p Matt
30 * Fixed mem leak in debugging code
31 *
32 * 115 10/25/99 11:57a Jeff
33 * ifdef'd some Macintosh pragmas
34 *
35 * 114 10/22/99 11:33a Matt
36 * Mac merge
37 *
38 * 113 9/29/99 8:04a Kevin
39 * Demo playback fixes
40 *
41 * 112 5/19/99 3:54p Jeff
42 * error is scripts are being bound to an object more than once
43 *
44 * 111 5/19/99 11:26a Matt
45 * Added multisafe functions & Dallas actions for showing a timer on the
46 * screen and adding custom HUD messages.
47 *
48 * 110 5/12/99 2:24p Jeff
49 * Descent3 now has a setable temp directory for all temp files
50 *
51 * 109 5/10/99 11:55a 3dsmax
52 * removed an int3
53 *
54 * 108 5/08/99 6:45p Chris
55 * safety precausion to unload modules if they are not already
56 *
57 * 107 5/08/99 4:31a Jeff
58 * don't int3 on multiplayer modules
59 *
60 * 106 5/07/99 8:27p Jeff
61 * trying to hunt down why some modules hang around after they are done
62 *
63 * 105 5/02/99 6:41a Jeff
64 * created 'test/temp' function to force unload all osiris modules
65 *
66 * 104 5/01/99 1:40a Jeff
67 * put in hack to keep levelscripts from even being attempted to be called
68 * by a client during disconnect
69 *
70 * 103 4/24/99 12:09a Jeff
71 * added path value functions
72 *
73 * 102 4/20/99 8:56p Chris
74 * Fixed problem with robots not being able to open locked doors that a
75 * player has the key for.
76 *
77 * 101 4/20/99 12:59p Jeff
78 * fixed loading script bug
79 *
80 * 100 4/20/99 12:02a Jeff
81 * made linux filename friendly
82 *
83 * 99 4/16/99 12:19a Jeff
84 * linux wants stdcall modifiers before parens, unlike windows
85 *
86 * 98 4/14/99 4:19a Jeff
87 * more case mismatch fixes in #includes
88 *
89 * 97 4/14/99 3:57a Jeff
90 * fixed case mismatch in #includes
91 *
92 * 96 3/17/99 11:48a Jeff
93 * exported function to get what language we are using
94 *
95 * 95 3/11/99 9:10p Jeff
96 * int3 only when restore system state if not playing back demo (because
97 * scripts are not really used in demos)
98 *
99 * 94 3/10/99 6:44p Jeff
100 * fixed exported game cinematic function for canned cinematics, so it's
101 * prototype doesn't change (oem patch friendly)
102 *
103 * 93 3/10/99 6:21p Jeff
104 * many fixes to demo system. Fixed IGC so cameras move...fixed osiris to
105 * be restored correctly, and it handles errors on restore
106 *
107 * 92 3/09/99 12:34p Jeff
108 * extract scripts to custom\cache
109 *
110 * 91 3/05/99 5:25p Jeff
111 * fixed saving demos in multiplayer...required adding a parameter to
112 * Osiris_LoadMissionModule() to pass in the name of the d3m file (for
113 * storage)
114 *
115 * 90 3/03/99 5:13a Jeff
116 * fix bug loading dlls from hog files (wouldn't load..comparing something
117 * like aigame to aigame.dll)
118 *
119 * 89 3/03/99 3:01a Chris
120 * Exported the difficulty stuff to OSIRIS
121 *
122 * 88 3/03/99 12:12a Chris
123 *
124 * 87 3/03/99 12:07a Chris
125 * Added the two new OSIRIS predefs for AI path finding
126 *
127 * 86 3/01/99 3:45p Jeff
128 * fixed up save and restore a little bit
129 *
130 * 85 3/01/99 11:50a Jeff
131 * call EVT_SAVESTATE and EVT_RESTORESTATE for levels
132 *
133 * 84 2/28/99 11:30p Chris
134 * FindObjOfType and OSIRIS controllable deaths
135 *
136 * 83 2/28/99 8:52p Jeff
137 * added functions to enable/disable creation events
138 *
139 * 82 2/23/99 12:54p Matt
140 * Removed Int3() (Jeff on MattT's machine)
141 *
142 * 81 2/22/99 8:17p Chris
143 * Added the LGoal_Value() function to OSIRIS
144 *
145 * 80 2/21/99 8:36p Jeff
146 * misc changes to handle new matcen and path types of dallas
147 *
148 * 79 2/21/99 8:04p Jeff
149 * better handling of out-of-sync scripts
150 *
151 * 78 2/21/99 5:51p Chris
152 * FIxed a bug with OBJV_C_TYPE (It should have been OBJV_I_TYPE). Added
153 * Obj_FindType()
154 *
155 * 77 2/18/99 4:28p Jeff
156 * added lookup functions for matcen, paths, level goals
157 *
158 * 76 2/18/99 11:06a Jeff
159 * added event masks (so you can enable/disable object/trigger/level
160 * events)
161 *
162 * 75 2/17/99 3:27a Jeff
163 * added game checksum function to handle out-of-sync dlls
164 *
165 * 74 2/15/99 11:38a Jeff
166 * debug mprintfs when extracting dlls
167 *
168 * 73 2/14/99 1:16a Jeff
169 * exported canned cinematic
170 *
171 * 72 2/13/99 6:11p Jeff
172 * fixed bug when extracting scripts for the second+ time
173 *
174 * 71 2/12/99 6:24p Kevin
175 *
176 * 70 2/12/99 6:22p Kevin
177 * Fixed a thingy for Jeffy
178 *
179 * 69 2/11/99 2:56a Jeff
180 * improvements to introcam
181 *
182 * 68 2/10/99 7:12p Jeff
183 * oops...OpenLibrary returns 0 not -1
184 *
185 * 67 2/10/99 6:56p Jeff
186 * handle invalid libraries when extracting scripts
187 *
188 * 66 2/10/99 3:41p Jeff
189 * removed unneeded assert
190 *
191 * 65 2/10/99 3:29p Jeff
192 * extracted dll manager knows the difference between game hogs and
193 * mission hogs
194 *
195 * 64 2/10/99 1:47p Matt
196 * Changed object handle symbolic constants
197 *
198 * 63 2/08/99 2:51p Jeff
199 * removed dead evt_ain events that were commented out
200 *
201 * 62 2/06/99 7:05p Jeff
202 * turned off osiris debug messages by default
203 *
204 * 61 2/05/99 9:06p Jeff
205 * added aux events for a couple new ainotify's
206 *
207 * 60 2/03/99 1:51a Jeff
208 * added predefs for ship permissions
209 *
210 * 59 2/03/99 12:43a Chris
211 * Added Obj_GetGroundPos
212 *
213 * 58 2/02/99 12:46p Jeff
214 * handy mprintfs on save/restore state
215 *
216 * 57 2/01/99 5:29p Jeff
217 * obj_dummy's can be assigned scripts
218 *
219 * 56 1/31/99 10:40p Jeff
220 * exported Osiris_CancelTimerID to DLLs
221 *
222 * 55 1/31/99 10:16p Matt
223 * Added Osiris_CancelTimerID()
224 *
225 * 54 1/31/99 8:52p Jeff
226 * new in game cinematics system finished
227 *
228 * 51 1/25/99 8:18a Chris
229 * Made the AUX Notify remap more obvious
230 *
231 * 50 1/25/99 8:13a Chris
232 * Made the AUX goal remap more obvious...
233 *
234 * 49 1/24/99 8:18p Chris
235 * Updated AI and OSIRIS. Externalized fireball constants for spew and
236 * sparks. Added CreateRandomSparks to OSIRIS, renamed a bunch of AI
237 * Notify names to use underscores. Fixed a memory access leak in the
238 * matcen effect code.
239 *
240 * 48 1/24/99 6:36p Jeff
241 * fixed trigger call event bug (wasn't using the correct DLLid)
242 *
243 * 47 1/22/99 8:54p Jeff
244 * added custom-default script overrides
245 *
246 * 46 1/22/99 6:53p Chris
247 * Fixed LoadandBind Aux notify problems, fixed static path problems,
248 * fixed AIF_FORCE_AWARE Problems, improved path code
249 *
250 * 45 1/22/99 5:15p Jeff
251 * added a key to toggle osiris debug messages
252 *
253 * 44 1/22/99 4:47p Jeff
254 *
255 * 43 1/21/99 11:15p Jeff
256 * pulled out some structs and defines from header files and moved them
257 * into seperate header files so that multiplayer dlls don't require major
258 * game headers, just those new headers. Side effect is a shorter build
259 * time. Also cleaned up some header file #includes that weren't needed.
260 * This affected polymodel.h, object.h, player.h, vecmat.h, room.h,
261 * manage.h and multi.h
262 *
263 * 42 1/20/99 4:17p Jeff
264 * added ai notify child events and predefs to get ids of sound, room,
265 * trigger, object names
266 *
267 * 41 1/20/99 3:46a Jeff
268 * exported boss introduction functions
269 *
270 * 39 1/16/99 2:19p Jeff
271 * only save and use the base filename of a dll (to keep it platform
272 * independent)
273 *
274 * 38 1/16/99 1:29p Jeff
275 * updated the OMMS system to be faster. Removed the event for restoring
276 * it, since it is require to surround code in attach/detach blocks.
277 *
278 * 37 1/16/99 10:39a Jeff
279 * added mission memory management to Osiris...only slightly tested. Need
280 * to solve game save/restore problem still
281 *
282 * 36 1/15/99 5:59p Chris
283 *
284 * 35 1/13/99 5:20p Jeff
285 * added 4 new file operation predefs
286 *
287 * 34 1/13/99 4:05p Jeff
288 * when loading a script dll, a string table is looked for and
289 * automatically loaded and passed to the newly loaded dll on init for
290 * use.
291 *
292 * 33 1/13/99 3:25a Chris
293 * Added Obj_Burning and Obj_IsEffect to OSIRIS
294 *
295 * 32 1/13/99 2:29a Chris
296 * Massive AI, OSIRIS update
297 *
298 * 31 1/11/99 2:14p Chris
299 * Massive work on OSIRIS and AI
300 *
301 * 30 1/11/99 12:53p Jeff
302 * added a function that given a module name it will make sure it has an
303 * extension. Made Osiris friendly with modules with no extension
304 *
305 * 29 1/08/99 2:02p Jeff
306 * handle the case of extracting too many scripts
307 *
308 * 28 1/08/99 2:00p Jeff
309 * fixed minor bug with hog extraction (mem leak) and made it so you can
310 * keep calling ExtractScripts for multiple hogs
311 *
312 * 27 1/08/99 1:50p Jeff
313 * finished support on loading scripts from hogs
314 *
315 * 26 1/07/99 10:52p Jeff
316 * wrote skeleton of hog script file extraction
317 *
318 * 25 1/04/99 6:43p Jeff
319 * added support to get/set mission flag values
320 *
321 * 24 1/04/99 12:42p Chris
322 * Updated OSIRIS with "xxxx_external.h" files and Obj_Value, and
323 * Matcen_XXX functions
324 *
325 * 23 1/04/99 12:23p Jeff
326 * added to evt_use and support for mission module scripts
327 *
328 * 22 12/31/98 7:33p Jeff
329 * improved Osiris timers to have unique IDs, along with adding an
330 * EVT_TIMERCANCEL and a new flag to autodestruct the timer if a given
331 * object handle dies.
332 *
333 * 21 12/31/98 2:37p Jeff
334 * added SaveRestoreState import function
335 *
336 * 20 12/30/98 5:17p Jeff
337 * changes made to handle script name override, to override the name of
338 * the script to use in a module.
339 *
340 * 19 12/30/98 3:46p Chris
341 * Incremental AI changes
342 *
343 * 18 12/30/98 12:31p Jeff
344 * when freeing object scripts, the type is changed before it's freed in
345 * ObjDelete. Also, when destroyed, OBJ_ROBOT becomes OBJ_DEBRIS and
346 * Osiris was not handling this.
347 *
348 * 17 12/23/98 12:10p Chris
349 * Added Gametime and Frametime to OSIRIS
350 *
351 * 16 12/22/98 4:51p Chris
352 * Added a ObjCreate predefined function
353 *
354 * 15 12/22/98 4:19p Jeff
355 * exported msafe_DoPowerup
356 *
357 * 14 12/22/98 2:46p Chris
358 * Added the AIValue predefined function
359 *
360 * 13 12/18/98 6:00p Jeff
361 * added support for door scripts in new osiris
362 *
363 * 12 12/18/98 3:10p Mark
364 * removed int3
365 *
366 * 11 12/18/98 11:07a Jeff
367 * triggers are implemented
368 *
369 * 10 12/18/98 10:42a Jeff
370 * added timer support and auto-save memory manager for new osiris. New
371 * events evt_memrestore state added also
372 *
373 * 9 12/17/98 7:26p Jeff
374 * added memory manager for autosaving script data
375 *
376 * 8 12/17/98 5:44p Jeff
377 * created timer system for osiris and save restore events
378 *
379 * 7 12/17/98 2:27p Keneta
380 * Commented out an Int3(), as per Jeff's directions. (MattT)
381 *
382 * 6 12/17/98 12:08p Jeff
383 * first checkin of new implementation of OSIRIS (old OSIRIS no longer
384 * works)
385 *
386 * 5 12/16/98 10:21p Jeff
387 * added level and trigger event call functions. added trigger script
388 * functionality (still primative)
389 *
390 * 4 12/16/98 5:37p Jason
391 * added new multisafe architecture
392 *
393 * 3 12/16/98 10:58a Jeff
394 * checked in so Jason can use
395 *
396 * 2 12/14/98 11:32a Jeff
397 * started work on osiris load and bind functions
398 *
399 * $NoKeywords: $
400 */
401
402 #include "osiris_dll.h"
403 #include "pserror.h"
404 #include "mono.h"
405 #include "cfile.h"
406 #include "ddio.h"
407 #include "manage.h"
408 #include <stdlib.h>
409 #include "mem.h"
410 #include "DllWrappers.h"
411 #include "objinfo.h"
412 #include "multisafe.h"
413 #include "osiris_predefs.h"
414 #include "trigger.h"
415 #include "game.h"
416 #include "multi.h"
417 #include "door.h"
418 #include "localization.h"
419 #include "player.h"
420 #include "gamecinematics.h"
421 #include "demofile.h"
422
423 #ifdef _DEBUG
424 #define OSIRISDEBUG
425 #endif
426
427
428 bool Show_osiris_debug = false;
429
430 #define MAX_LOADED_MODULES 96 // maximum number of dlls that can be loaded at a time
431
432 #define OSIMF_INUSE 0x1 // slot in use
433 #define OSIMF_LEVEL 0x2 // level module
434 #define OSIMF_DLLELSEWHERE 0x4 // mission module
435 #define OSIMF_INTEMPDIR 0x8 // the dll was extracted from a hog and it is in a temp file
436 #define OSIMF_NOUNLOAD \
437 0x10 // the dll should not be unloaded if the reference count is
438 // 0, only when the level ends
439
440 // The exported DLL function call prototypes
441 #if defined(POSIX)
442 typedef char DLLFUNCCALL (*InitializeDLL_fp)(tOSIRISModuleInit *function_list);
443 typedef void DLLFUNCCALL (*ShutdownDLL_fp)(void);
444 typedef int DLLFUNCCALL (*GetGOScriptID_fp)(const char *name, uint8_t isdoor);
445 typedef void DLLFUNCCALL *(*CreateInstance_fp)(int id);
446 typedef void DLLFUNCCALL (*DestroyInstance_fp)(int id, void *ptr);
447 typedef int16_t DLLFUNCCALL (*CallInstanceEvent_fp)(int id, void *ptr, int event, tOSIRISEventInfo *data);
448 typedef int DLLFUNCCALL (*GetTriggerScriptID_fp)(int trigger_room, int trigger_face);
449 typedef int DLLFUNCCALL (*GetCOScriptList_fp)(int **list, int **id_list);
450 typedef int DLLFUNCCALL (*SaveRestoreState_fp)(void *file_ptr, uint8_t saving_state);
451 #else
452 typedef char(DLLFUNCCALL *InitializeDLL_fp)(tOSIRISModuleInit *function_list);
453 typedef void(DLLFUNCCALL *ShutdownDLL_fp)(void);
454 typedef int(DLLFUNCCALL *GetGOScriptID_fp)(const char *name, uint8_t isdoor);
455 typedef void *(DLLFUNCCALL *CreateInstance_fp)(int id);
456 typedef void(DLLFUNCCALL *DestroyInstance_fp)(int id, void *ptr);
457 typedef int16_t(DLLFUNCCALL *CallInstanceEvent_fp)(int id, void *ptr, int event, tOSIRISEventInfo *data);
458 typedef int(DLLFUNCCALL *GetTriggerScriptID_fp)(int trigger_room, int trigger_face);
459 typedef int(DLLFUNCCALL *GetCOScriptList_fp)(int **list, int **id_list);
460 typedef int(DLLFUNCCALL *SaveRestoreState_fp)(void *file_ptr, uint8_t saving_state);
461 #endif
462
463 struct tRefObj {
464 int objnum;
465 int type, id;
466 bool dummy;
467 tRefObj *next;
468 };
469
470 struct tOSIRISModule {
471 uint8_t flags;
472 uint8_t extracted_id;
473 uint16_t reference_count;
474 InitializeDLL_fp InitializeDLL;
475 ShutdownDLL_fp ShutdownDLL;
476 GetGOScriptID_fp GetGOScriptID;
477 CreateInstance_fp CreateInstance;
478 DestroyInstance_fp DestroyInstance;
479 CallInstanceEvent_fp CallInstanceEvent;
480 GetTriggerScriptID_fp GetTriggerScriptID;
481 GetCOScriptList_fp GetCOScriptList;
482 SaveRestoreState_fp SaveRestoreState;
483 module mod;
484 char *module_name;
485 char **string_table;
486 int strings_loaded;
487
488 #ifdef OSIRISDEBUG
489 tRefObj *RefRoot;
490 #endif
491 };
492
493 static tOSIRISModule OSIRIS_loaded_modules[MAX_LOADED_MODULES];
494 tOSIRISModuleInit Osiris_module_init;
495
496 struct {
497 bool level_loaded;
498 uint16_t num_customs;
499 uint16_t dll_id;
500 int *custom_ids;
501 int *custom_handles;
502 void *instance;
503 } tOSIRISCurrentLevel;
504
505 struct {
506 bool mission_loaded;
507 uint16_t dll_id;
508 } tOSIRISCurrentMission;
509
510 #define OESF_USED 0x0001
511 #define OESF_MISSION 0x0002 // mission dlls
512 struct tExtractedScriptInfo {
513 uint8_t flags;
514 char *temp_filename;
515 char *real_filename;
516 };
517 static tExtractedScriptInfo OSIRIS_Extracted_scripts[MAX_LOADED_MODULES];
518 static char *OSIRIS_Extracted_script_dir = NULL;
519
520 // Osiris_CreateModuleInitStruct
521 // Purpose:
522 // This function initializes a Module Init Struct with all the needed data to get sent
523 // to the module during initialization.
524 extern void Osiris_CreateModuleInitStruct(tOSIRISModuleInit *mi);
525
526 static void Osiris_RestoreOMMS(CFILE *file);
527 static void Osiris_SaveOMMS(CFILE *file);
528
529 // Osiris_CreateGameChecksum
530 // Purpose:
531 // Generates a checksum of the game's structures, to give to the modules
532 // so they can use to compare to the time when they were compiled, to see
533 // if they are compatible.
534 uint32_t Osiris_CreateGameChecksum(void);
535 // Osiris_IsEventEnabled
536 // Purpose:
537 // Returns true if the event is allowed to be called
538 static bool Osiris_IsEventEnabled(int event);
539
540 extern void Cinematic_StartCannedScript(tCannedCinematicInfo *info);
541
542 // Osiris_DumpLoadedObjects
543 //
544 // Debug. Dumps all loaded objects to given file
545 static void Osiris_DumpLoadedObjects(char *file);
546 static void Osiris_ForceUnloadModules(void);
547
548 uint32_t Osiris_game_checksum;
549
550 static uint8_t Osiris_event_mask = OEM_OBJECTS | OEM_TRIGGERS | OEM_LEVELS;
551 static bool Osiris_create_events_disabled = false;
552 static bool Osiris_level_script_loaded = false;
553
554 #define HAVECUSTOMONLY(type) (type == OBJ_CAMERA)
555 #define CANBEASSIGNEDSCRIPT(obj) \
556 ((obj) && \
557 ((obj->type == OBJ_ROBOT) || (obj->type == OBJ_BUILDING) || (obj->type == OBJ_POWERUP) || \
558 (obj->type == OBJ_CLUTTER) || (obj->type == OBJ_DOOR) || (obj->type == OBJ_CAMERA) || (obj->type == OBJ_DUMMY)))
559 #define CANHAVEANYSCRIPT(obj) \
560 (CANBEASSIGNEDSCRIPT(obj) || (obj && ((obj->type == OBJ_DEBRIS) || (obj->type == OBJ_GHOST))))
561 #define CANTYPEBEASSIGNEDSCRIPT(type) \
562 ((type == OBJ_ROBOT) || (type == OBJ_BUILDING) || (type == OBJ_POWERUP) || (type == OBJ_CLUTTER) || \
563 (type == OBJ_DOOR) || (type == OBJ_CAMERA))
564 //========================================================================
565
566 // Osiris_ShutdownModuleLoader
567 // Purpose:
568 // Closes down the OSIRIS module loader and handling system
569 void Osiris_ShutdownModuleLoader(void) {
570 mprintf(0, "OSIRIS: Shutting down module manager\n");
571 int i;
572 for (i = 0; i < MAX_LOADED_MODULES; i++) {
573 Osiris_FreeModule(i);
574 }
575 }
576
577 // Osiris_InitModuleLoader
578 // Purpose:
579 // Initializes the OSIRIS module loader and handling system
580 void Osiris_InitModuleLoader(void) {
581 mprintf(0, "OSIRIS: Initializing module manager\n");
582 int i;
583 for (i = 0; i < MAX_LOADED_MODULES; i++) {
584 OSIRIS_loaded_modules[i].flags = 0;
585 OSIRIS_loaded_modules[i].reference_count = 0;
586 OSIRIS_loaded_modules[i].module_name = NULL;
587 OSIRIS_loaded_modules[i].CallInstanceEvent = NULL;
588 OSIRIS_loaded_modules[i].CreateInstance = NULL;
589 OSIRIS_loaded_modules[i].DestroyInstance = NULL;
590 OSIRIS_loaded_modules[i].GetCOScriptList = NULL;
591 OSIRIS_loaded_modules[i].GetGOScriptID = NULL;
592 OSIRIS_loaded_modules[i].GetTriggerScriptID = NULL;
593 OSIRIS_loaded_modules[i].InitializeDLL = NULL;
594 OSIRIS_loaded_modules[i].SaveRestoreState = NULL;
595 OSIRIS_loaded_modules[i].string_table = NULL;
596 OSIRIS_loaded_modules[i].strings_loaded = 0;
597
598 #ifdef OSIRISDEBUG
599 ASSERT(OSIRIS_loaded_modules[i].RefRoot == NULL);
600 OSIRIS_loaded_modules[i].RefRoot = NULL;
601 #endif
602 }
603
604 Osiris_CreateModuleInitStruct(&Osiris_module_init);
605 Osiris_game_checksum = Osiris_CreateGameChecksum();
606 Osiris_module_init.game_checksum = Osiris_game_checksum;
607
608 tOSIRISCurrentLevel.level_loaded = false;
609 tOSIRISCurrentLevel.num_customs = 0;
610 tOSIRISCurrentLevel.dll_id = 0;
611 tOSIRISCurrentLevel.custom_ids = NULL;
612 tOSIRISCurrentLevel.custom_handles = NULL;
613 tOSIRISCurrentLevel.instance = NULL;
614
615 tOSIRISCurrentMission.mission_loaded = false;
616 tOSIRISCurrentMission.dll_id = 0;
617
618 Osiris_InitMemoryManager();
619 Osiris_InitOMMS();
620
621 OSIRIS_Extracted_script_dir = NULL;
622
623 atexit(Osiris_ShutdownModuleLoader);
624 }
625
626 // Osiris_CreateGameChecksum
627 // Purpose:
628 // Generates a checksum of the game's structures, to give to the modules
629 // so they can use to compare to the time when they were compiled, to see
630 // if they are compatible.
631 uint32_t Osiris_CreateGameChecksum(void) {
632 uint32_t value = 0xe1e1b0b0;
633
634 value += sizeof(object);
635 value += sizeof(player) * 2;
636 value += sizeof(tOSIRISModuleInit) * 3;
637 value += sizeof(tOSIRISEventInfo) * 5;
638 value += sizeof(tOSIRISTIMER) * 7;
639 value += sizeof(tOSIRISSCRIPTID) * 11;
640 value += sizeof(tOSIRISMEMCHUNK) * 13;
641 value += sizeof(msafe_struct) * 17;
642 value += sizeof(ray_info) * 19;
643 value += sizeof(vector) * 23;
644 value += sizeof(matrix) * 29;
645 value += sizeof(tGameCinematic) * 31;
646 value += sizeof(tCannedCinematicInfo) * 37;
647
648 value = value << 2;
649
650 int index = 0;
651 while (Osiris_module_init.fp[index]) {
652 value++;
653 index++;
654 }
655
656 return value;
657 }
658
659 // Osiris_FreeModule
660 // Purpose:
661 // Removes a currently loaded module from the OSIRIS system
662 void Osiris_FreeModule(int id) {
663 if (id < 0 || id >= MAX_LOADED_MODULES)
664 return;
665
666 if (OSIRIS_loaded_modules[id].flags & OSIMF_INUSE) {
667
668 #ifdef OSIRISDEBUG
669 ASSERT(OSIRIS_loaded_modules[id].RefRoot == NULL); // not all objects freed
670 #endif
671
672 if (OSIRIS_loaded_modules[id].flags & OSIMF_LEVEL) {
673 // we're freeing the level dll
674 tOSIRISCurrentLevel.level_loaded = false;
675 tOSIRISCurrentLevel.num_customs = 0;
676 tOSIRISCurrentLevel.dll_id = 0;
677 tOSIRISCurrentLevel.custom_ids = NULL;
678 tOSIRISCurrentLevel.custom_handles = NULL;
679 tOSIRISCurrentLevel.instance = NULL;
680 }
681
682 if (!(OSIRIS_loaded_modules[id].flags & OSIMF_DLLELSEWHERE)) {
683
684 // this is a DLL belonging to us
685 if (OSIRIS_loaded_modules[id].ShutdownDLL) {
686 // call the shutdown function so the DLL can perform what it needs
687 OSIRIS_loaded_modules[id].ShutdownDLL();
688 }
689
690 if (OSIRIS_loaded_modules[id].string_table != NULL) {
691 DestroyStringTable(OSIRIS_loaded_modules[id].string_table, OSIRIS_loaded_modules[id].strings_loaded);
692 }
693 mod_FreeModule(&OSIRIS_loaded_modules[id].mod);
694 }
695
696 if (tOSIRISCurrentMission.mission_loaded && id == tOSIRISCurrentMission.dll_id) {
697 // we're freeing the mission dll
698 tOSIRISCurrentMission.mission_loaded = false;
699 tOSIRISCurrentMission.dll_id = 0;
700 }
701
702 OSIRIS_loaded_modules[id].CallInstanceEvent = NULL;
703 OSIRIS_loaded_modules[id].CreateInstance = NULL;
704 OSIRIS_loaded_modules[id].DestroyInstance = NULL;
705 OSIRIS_loaded_modules[id].GetCOScriptList = NULL;
706 OSIRIS_loaded_modules[id].GetGOScriptID = NULL;
707 OSIRIS_loaded_modules[id].GetTriggerScriptID = NULL;
708 OSIRIS_loaded_modules[id].InitializeDLL = NULL;
709 OSIRIS_loaded_modules[id].SaveRestoreState = NULL;
710 OSIRIS_loaded_modules[id].string_table = NULL;
711 OSIRIS_loaded_modules[id].strings_loaded = 0;
712 OSIRIS_loaded_modules[id].flags = 0;
713 OSIRIS_loaded_modules[id].reference_count = 0;
714
715 #ifdef OSIRISDEBUG
716 ASSERT(OSIRIS_loaded_modules[id].RefRoot == NULL);
717 OSIRIS_loaded_modules[id].RefRoot = NULL;
718 #endif
719
720 if (OSIRIS_loaded_modules[id].module_name) {
721 mem_free(OSIRIS_loaded_modules[id].module_name);
722 OSIRIS_loaded_modules[id].module_name = NULL;
723 }
724 }
725 }
726
727 void Osiris_ForceUnloadModules(void) {
728 for (int j = 0; j < MAX_LOADED_MODULES; j++) {
729 if (OSIRIS_loaded_modules[j].flags & OSIMF_INUSE) {
730 Osiris_FreeModule(j);
731 }
732 }
733 }
734
735 // Osiris_DumpLoadedObjects
736 //
737 // Debug. Dumps all loaded objects to given file
738 void Osiris_DumpLoadedObjects(char *file) {
739 #ifndef OSIRISDEBUG
740 return;
741 #else
742 CFILE *f = cfopen(file, "wt");
743 if (!f) {
744 Int3();
745 return;
746 }
747
748 char buffy[1024];
749
750 for (int j = 0; j < MAX_LOADED_MODULES; j++) {
751 if (OSIRIS_loaded_modules[j].flags & OSIMF_INUSE && OSIRIS_loaded_modules[j].RefRoot != NULL) {
752 // uh oh! scripts were not completely decremented
753 tRefObj *node = OSIRIS_loaded_modules[j].RefRoot;
754 while (node) {
755 snprintf(buffy, sizeof(buffy), "Module: \"%s\" Objnum: %d Type: %d%s Id:%d\n",
756 OSIRIS_loaded_modules[j].module_name, node->objnum, node->type, (node->dummy) ? "(Dummy)" : "",
757 node->id);
758 cf_WriteString(f, buffy);
759 node = node->next;
760 }
761 }
762 }
763
764 cfclose(f);
765 #endif
766 }
767
768 // Osiris_FindLoadedModule
769 // Purpose:
770 // Given the name of a module, it returns the id of a loaded OSIRIS module. -1 if it isn't loaded.
771 int Osiris_FindLoadedModule(char *module_name) {
772 // search through the list of loaded modules and see if we can find a match
773 // strip off the extension
774 char real_name[_MAX_PATH];
775 ddio_SplitPath(module_name, NULL, real_name, NULL);
776
777 int i;
778 for (i = 0; i < MAX_LOADED_MODULES; i++) {
779 if (OSIRIS_loaded_modules[i].flags & OSIMF_INUSE) {
780 if (OSIRIS_loaded_modules[i].module_name && (!stricmp(OSIRIS_loaded_modules[i].module_name, real_name))) {
781 // we found a match
782 return i;
783 }
784 }
785 }
786
787 return -1;
788 }
789
790 // Osiris_UnloadModule
791 // Purpose:
792 // Given a module id, it will decrement the reference count to that module by one. If the reference
793 // count becomes zero, the module will be unloaded from memory.
794 void Osiris_UnloadModule(int module_id) {
795 if (module_id < 0 || module_id >= MAX_LOADED_MODULES)
796 return;
797 if (OSIRIS_loaded_modules[module_id].flags & OSIMF_INUSE) {
798 // the module is in use
799 if (Show_osiris_debug) {
800 mprintf(0, "OSIRIS: Decrementing reference count for module (%s)\n", OSIRIS_loaded_modules[module_id].module_name);
801 }
802 OSIRIS_loaded_modules[module_id].reference_count--;
803
804 ASSERT(OSIRIS_loaded_modules[module_id].reference_count >= 0);
805
806 if (OSIRIS_loaded_modules[module_id].reference_count <= 0) {
807
808 if (OSIRIS_loaded_modules[module_id].flags & OSIMF_NOUNLOAD) {
809
810 ASSERT(!(OSIRIS_loaded_modules[module_id].flags & OSIMF_LEVEL)); // level modules cannot be set static
811 ASSERT(!(OSIRIS_loaded_modules[module_id].flags & OSIMF_DLLELSEWHERE)); // mission modules cannot be set static
812
813 // do not unload this module, due to the forced stay in memory
814 mprintf(0, "OSIRIS: Module (%s) staying in memory due to static flag\n",
815 OSIRIS_loaded_modules[module_id].module_name);
816 } else {
817 // time to unload this module
818 if (Show_osiris_debug) {
819 mprintf(0, "OSIRIS: Module (%s) reference count is at 0, unloading\n",
820 OSIRIS_loaded_modules[module_id].module_name);
821 }
822 Osiris_FreeModule(module_id);
823 }
824 }
825 } else {
826 mprintf(0, "OSIRIS: Trying to unload a module (%d) that is not in use!\n", module_id);
827 Int3();
828 }
829 }
830
831 // Osiris_UnloadLevelModule
832 // Purpose:
833 // Instead of saving the handle returned from Osiris_LoadLevelModule() and calling
834 // Osiris_UnloadModule() with that handle, you can just call this, instead of the call
835 // to Osiris_UnloadModule().
836 void Osiris_UnloadLevelModule(void) {
837 Osiris_level_script_loaded = false;
838
839 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
840 // no scripts for a client!
841 return;
842 }
843
844 // free allocated scripts (we can do this, because the root node will just become
845 // NULL and once the first call to allocate memory is used, it'll automatically work)
846 Osiris_CloseMemoryManager();
847
848 if (tOSIRISCurrentLevel.level_loaded) {
849 int dll_id = tOSIRISCurrentLevel.dll_id;
850
851 // free up all instances of trigger scripts still around
852 for (int i = 0; i < Num_triggers; i++) {
853 if (Triggers[i].osiris_script.script_instance) {
854 OSIRIS_loaded_modules[dll_id].DestroyInstance(Triggers[i].osiris_script.script_id,
855 Triggers[i].osiris_script.script_instance);
856 }
857 Triggers[i].osiris_script.script_id = -1;
858 Triggers[i].osiris_script.script_instance = NULL;
859 }
860
861 Osiris_UnloadModule(dll_id);
862 }
863
864 // go through the remaining modules and unload those with the OSIMF_NOUNLOAD set
865 for (int j = 0; j < MAX_LOADED_MODULES; j++) {
866
867 if (OSIRIS_loaded_modules[j].flags & OSIMF_INUSE && OSIRIS_loaded_modules[j].flags & OSIMF_NOUNLOAD) {
868 // unload this module
869 mprintf(0, "OSIRIS: Unloading static module (%s) due to level end\n", OSIRIS_loaded_modules[j].module_name);
870 Osiris_FreeModule(j);
871 }
872
873 if (OSIRIS_loaded_modules[j].flags & OSIMF_INUSE && (!(OSIRIS_loaded_modules[j].flags & OSIMF_DLLELSEWHERE))) {
874 // Please get Jeff
875 // We are done with the level and all modules should be unloaded at this point,
876 // however, this module is still in use....
877 Osiris_FreeModule(j);
878 }
879 }
880 }
881
882 // returns: -2 if not found
883 // -1 if it is in data\scripts
884 // 0-x which extracted script id it is
885 int _get_full_path_to_module(char *module_name, char *fullpath, char *basename) {
886 char modfilename[_MAX_PATH];
887 char ppath[_MAX_PATH], pext[256];
888 char adjusted_name[_MAX_PATH], adjusted_fname[_MAX_PATH];
889 char *p;
890
891 ddio_SplitPath(module_name, ppath, basename, pext);
892
893 // make sure filename/ext is all lowercase, requirement for Linux, doesn't hurt Windows
894 p = basename;
895 while (p && *p) {
896 *p = tolower(*p);
897 p++;
898 }
899 p = pext;
900 while (p && *p) {
901 *p = tolower(*p);
902 p++;
903 }
904 strcpy(adjusted_fname, basename);
905 strcat(adjusted_fname, pext);
906
907 if (strlen(ppath) > 0) {
908 ddio_MakePath(adjusted_name, ppath, adjusted_fname, NULL);
909 } else {
910 strcpy(adjusted_name, adjusted_fname);
911 }
912
913 // determine real name of script
914 mod_GetRealModuleName(adjusted_name, modfilename);
915
916 int exist = cfexist(modfilename);
917 switch (exist) {
918 case CFES_ON_DISK:
919 ddio_MakePath(fullpath, LocalScriptDir, modfilename, NULL);
920 return -1;
921 break;
922 case CFES_IN_LIBRARY: {
923 ASSERT(OSIRIS_Extracted_script_dir);
924 if (!OSIRIS_Extracted_script_dir)
925 return -2;
926
927 // search through our list of extracted files to find it...
928 for (int i = 0; i < MAX_LOADED_MODULES; i++) {
929 if (OSIRIS_Extracted_scripts[i].flags & OESF_USED) {
930 if (!stricmp(basename, OSIRIS_Extracted_scripts[i].real_filename)) {
931 // this is it
932 ddio_MakePath(fullpath, OSIRIS_Extracted_script_dir, OSIRIS_Extracted_scripts[i].temp_filename, NULL);
933 return i;
934 }
935 }
936 }
937 Int3(); // this file was supposed to exist
938 } break;
939 default:
940 *fullpath = '\0';
941 return -2;
942 };
943 return -2;
944 }
945
946 // Osiris_LoadLevelModule
947 // Purpose:
948 // Given a module name, it will attempt to load the module as a level module. If it succeeds
949 // it will return the id of the module where it has been loaded. If the module was already loaded
950 // before calling this function, it will return the id to where the module is, and will not reload
951 // the module. Returns -1 if the module does not exist. Returns -2 if the module couldn't initialize.
952 // Returns -3 if the module is not a level module. Returns -4 if no module slots are available.
953 int Osiris_LoadLevelModule(char *module_name) {
954 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
955 // no scripts for a client!
956 return -2;
957 }
958
959 ASSERT(!tOSIRISCurrentLevel.level_loaded);
960 if (tOSIRISCurrentLevel.level_loaded) {
961 mprintf(0, "OSIRIS: Trying to load a level dll, when one has already been loaded\n");
962 return tOSIRISCurrentLevel.dll_id;
963 }
964
965 int loaded_id;
966 loaded_id = Osiris_FindLoadedModule(module_name);
967 if (loaded_id != -1) {
968 // the module is already loaded
969 OSIRIS_loaded_modules[loaded_id].reference_count++;
970 if (Show_osiris_debug) {
971 mprintf(0, "OSIRIS: Level Module (%s) reference count increased to %d\n", module_name,
972 OSIRIS_loaded_modules[loaded_id].reference_count);
973 }
974 return loaded_id;
975 }
976
977 // the module hasn't been loaded yet, find an available slot.
978 for (loaded_id = 0; loaded_id < MAX_LOADED_MODULES; loaded_id++) {
979 if (!(OSIRIS_loaded_modules[loaded_id].flags & OSIMF_INUSE)) {
980 // we found a free slot
981 break;
982 }
983 }
984
985 if (loaded_id >= MAX_LOADED_MODULES) {
986 // no slots available
987 mprintf(0, "OSIRIS: Osiris_LoadLevelModule(%s): No available slots\n", module_name);
988 Int3();
989 return -4;
990 }
991
992 OSIRIS_loaded_modules[loaded_id].flags = 0; // set this to 0 as we fill in the data
993
994 char fullpath[_MAX_PATH], basename[_MAX_PATH];
995 int ret_val = _get_full_path_to_module(module_name, fullpath, basename);
996 switch (ret_val) {
997 case -2:
998 // the module does not exist
999 mprintf(0, "OSIRIS: Osiris_LoadLevelModule(%s): Module doesn't exist\n", module_name);
1000 return -1;
1001 break;
1002 case -1:
1003 // the module is in data\scripts
1004 break;
1005 default:
1006 // the module was an extracted file
1007 mprintf(0, "OSIRIS: Found module (%s) in a temp file\n", basename);
1008 OSIRIS_loaded_modules[loaded_id].flags |= OSIMF_INTEMPDIR;
1009 OSIRIS_loaded_modules[loaded_id].extracted_id = ret_val;
1010 break;
1011 }
1012
1013 // the module exists, now attempt to load it
1014 if (!mod_LoadModule(&OSIRIS_loaded_modules[loaded_id].mod, fullpath)) {
1015 // there was an error trying to load the module
1016 mprintf(0, "OSIRIS: Osiris_LoadLevelModule(%s): Unable to load module\n", module_name);
1017 Int3();
1018 return -3;
1019 }
1020
1021 // the module has loaded, attempt to import all the level functions
1022 tOSIRISModule *osm = &OSIRIS_loaded_modules[loaded_id];
1023 module *mod = &osm->mod;
1024
1025 // there are 9 functions we need to import
1026 // InitializeDLL@4
1027 // ShutdownDLL@0
1028 // GetGOScriptID@4
1029 // GetTriggerScriptID@4
1030 // GetCOScriptList@8
1031 // CreateInstance@4
1032 // DestroyInstance@8
1033 // CallInstanceEvent@16
1034 // SaveRestoreState@8
1035
1036 osm->InitializeDLL = (InitializeDLL_fp)mod_GetSymbol(mod, "InitializeDLL", 4);
1037 osm->ShutdownDLL = (ShutdownDLL_fp)mod_GetSymbol(mod, "ShutdownDLL", 0);
1038 osm->GetGOScriptID = (GetGOScriptID_fp)mod_GetSymbol(mod, "GetGOScriptID", 8);
1039 osm->GetTriggerScriptID = (GetTriggerScriptID_fp)mod_GetSymbol(mod, "GetTriggerScriptID", 8);
1040 osm->GetCOScriptList = (GetCOScriptList_fp)mod_GetSymbol(mod, "GetCOScriptList", 8);
1041 osm->CreateInstance = (CreateInstance_fp)mod_GetSymbol(mod, "CreateInstance", 4);
1042 osm->DestroyInstance = (DestroyInstance_fp)mod_GetSymbol(mod, "DestroyInstance", 8);
1043 osm->CallInstanceEvent = (CallInstanceEvent_fp)mod_GetSymbol(mod, "CallInstanceEvent", 16);
1044 osm->SaveRestoreState = (SaveRestoreState_fp)mod_GetSymbol(mod, "SaveRestoreState", 8);
1045
1046 osm->flags |= OSIMF_INUSE | OSIMF_LEVEL;
1047 osm->module_name = mem_strdup(basename);
1048 osm->reference_count = 1;
1049
1050 #ifdef OSIRISDEBUG
1051 ASSERT(osm->RefRoot == NULL);
1052 osm->RefRoot = NULL;
1053 #endif
1054
1055 // make sure all of the functions imported ok
1056 if (!osm->InitializeDLL || !osm->ShutdownDLL || !osm->GetGOScriptID || !osm->GetTriggerScriptID ||
1057 !osm->GetCOScriptList || !osm->CreateInstance || !osm->DestroyInstance || !osm->SaveRestoreState ||
1058 !osm->CallInstanceEvent) {
1059 // there was an error importing a function
1060 mprintf(0, "OSIRIS: Osiris_LoadLevelModule(%s) couldn't import function.\n", module_name);
1061 Int3();
1062 osm->flags = 0;
1063 if (osm->module_name)
1064 mem_free(osm->module_name);
1065 osm->module_name = NULL;
1066 mod_FreeModule(mod);
1067 return -3;
1068 }
1069
1070 // check to see if there is a corresponding string table to load
1071 char stringtablename[_MAX_PATH];
1072 strcpy(stringtablename, basename);
1073 strcat(stringtablename, ".str");
1074
1075 if (cfexist(stringtablename)) {
1076 // there is a string table, load it up
1077 bool ret = CreateStringTable(stringtablename, &osm->string_table, &osm->strings_loaded);
1078 if (!ret) {
1079 mprintf(0, "OSIRIS: Unable to load string table (%s) for (%s)\n", stringtablename, basename);
1080 Int3();
1081 osm->string_table = NULL;
1082 osm->strings_loaded = 0;
1083 }
1084 } else {
1085 osm->string_table = NULL;
1086 osm->strings_loaded = 0;
1087 }
1088
1089 Osiris_module_init.string_count = osm->strings_loaded;
1090 Osiris_module_init.string_table = osm->string_table;
1091 Osiris_module_init.module_is_static = false;
1092 Osiris_module_init.script_identifier = osm->module_name;
1093 Osiris_module_init.module_identifier = loaded_id;
1094
1095 // when we get to this point we nearly have a loaded module, we just need to initialize it
1096 if (!osm->InitializeDLL(&Osiris_module_init)) {
1097 // there was an error initializing the module
1098 mprintf(0, "OSIRIS: Osiris_LoadLevelModule(%s) error initializing module.\n", basename);
1099 if (osm->string_table) {
1100 DestroyStringTable(osm->string_table, osm->strings_loaded);
1101 }
1102 osm->flags = 0;
1103 if (osm->module_name)
1104 mem_free(osm->module_name);
1105 osm->module_name = NULL;
1106 osm->string_table = NULL;
1107 osm->strings_loaded = 0;
1108 mod_FreeModule(mod);
1109 return -2;
1110 }
1111
1112 // intialize trigger scripts
1113 for (int i = 0; i < Num_triggers; i++) {
1114 int script_id;
1115 void *instance;
1116
1117 Triggers[i].osiris_script.script_id = -1;
1118 Triggers[i].osiris_script.script_instance = NULL;
1119
1120 script_id = osm->GetTriggerScriptID(Triggers[i].roomnum, Triggers[i].facenum);
1121 if (script_id != -1) {
1122 // the trigger was found
1123 instance = osm->CreateInstance(script_id);
1124 if (!instance) {
1125 mprintf(0, "OSIRIS: Unable to create instance for trigger script (%d)\n", i);
1126 } else {
1127 Triggers[i].osiris_script.script_id = script_id;
1128 Triggers[i].osiris_script.script_instance = instance;
1129 }
1130 }
1131 }
1132
1133 // we have a successful module load
1134 tOSIRISCurrentLevel.level_loaded = true;
1135 tOSIRISCurrentLevel.dll_id = loaded_id;
1136 tOSIRISCurrentLevel.num_customs = OSIRIS_loaded_modules[loaded_id].GetCOScriptList(
1137 &tOSIRISCurrentLevel.custom_handles, &tOSIRISCurrentLevel.custom_ids);
1138 tOSIRISCurrentLevel.instance =
1139 OSIRIS_loaded_modules[loaded_id].CreateInstance(0); // level scripts always have id of 0 in a level dll
1140
1141 mprintf(0, "OSIRIS: Level Module (%s) loaded successfully (%d custom handles)\n", basename,
1142 tOSIRISCurrentLevel.num_customs);
1143 Osiris_level_script_loaded = true;
1144 return loaded_id;
1145 }
1146
1147 // Osiris_LoadGameModule
1148 // Purpose:
1149 // Given a module name, it will attempt to load the module as a game module. If it succeeds
1150 // it will return the id of the module where it has been loaded. If the module was already loaded
1151 // before calling this function, it will return the id to where the module is, and will not reload
1152 // the module. Returns -1 if the module does not exist. Returns -2 if the module couldn't initialize.
1153 // Returns -3 if the module is not a game module. Returns -4 if no module slots are available.
1154 int Osiris_LoadGameModule(char *module_name) {
1155 if (module_name[0] == '\0') {
1156 return -1;
1157 }
1158
1159 int loaded_id;
1160 loaded_id = Osiris_FindLoadedModule(module_name);
1161 if (loaded_id != -1) {
1162 // the module is already loaded
1163 OSIRIS_loaded_modules[loaded_id].reference_count++;
1164 if (Show_osiris_debug) {
1165 mprintf(0, "OSIRIS: Game Module (%s) reference count increased to %d\n", module_name,
1166 OSIRIS_loaded_modules[loaded_id].reference_count);
1167 }
1168 return loaded_id;
1169 }
1170
1171 // the module hasn't been loaded yet, find an available slot.
1172 for (loaded_id = 0; loaded_id < MAX_LOADED_MODULES; loaded_id++) {
1173 if (!(OSIRIS_loaded_modules[loaded_id].flags & OSIMF_INUSE)) {
1174 // we found a free slot
1175 break;
1176 }
1177 }
1178
1179 if (loaded_id >= MAX_LOADED_MODULES) {
1180 // no slots available
1181 mprintf(0, "OSIRIS: Osiris_LoadGameModule(%s): No available slots\n", module_name);
1182 Int3();
1183 return -4;
1184 }
1185
1186 OSIRIS_loaded_modules[loaded_id].flags = 0; // set this to 0 as we fill in the data
1187
1188 char fullpath[_MAX_PATH], basename[_MAX_PATH];
1189 int ret_val = _get_full_path_to_module(module_name, fullpath, basename);
1190 switch (ret_val) {
1191 case -2:
1192 // the module does not exist
1193 mprintf(0, "OSIRIS: Osiris_LoadLevelModule(%s): Module doesn't exist\n", module_name);
1194 return -1;
1195 break;
1196 case -1:
1197 // the module is in data\scripts
1198 break;
1199 default:
1200 // the module was an extracted file
1201 mprintf(0, "OSIRIS: Found module (%s) in a temp file\n", basename);
1202 OSIRIS_loaded_modules[loaded_id].flags |= OSIMF_INTEMPDIR;
1203 OSIRIS_loaded_modules[loaded_id].extracted_id = ret_val;
1204 break;
1205 }
1206
1207 // the module exists, now attempt to load it
1208 if (!mod_LoadModule(&OSIRIS_loaded_modules[loaded_id].mod, fullpath)) {
1209 // there was an error trying to load the module
1210 mprintf(0, "OSIRIS: Osiris_LoadGameModule(%s): Unable to load module\n", module_name);
1211 Int3();
1212 return -3;
1213 }
1214
1215 // the module has loaded, attempt to import all the level functions
1216 tOSIRISModule *osm = &OSIRIS_loaded_modules[loaded_id];
1217 module *mod = &osm->mod;
1218
1219 // there are 7 functions we need to import
1220 // InitializeDLL@4
1221 // ShutdownDLL@0
1222 // GetGOScriptID@4
1223 // CreateInstance@4
1224 // DestroyInstance@8
1225 // CallInstanceEvent@16
1226 // SaveRestoreState@8
1227
1228 osm->InitializeDLL = (InitializeDLL_fp)mod_GetSymbol(mod, "InitializeDLL", 4);
1229 osm->ShutdownDLL = (ShutdownDLL_fp)mod_GetSymbol(mod, "ShutdownDLL", 0);
1230 osm->GetGOScriptID = (GetGOScriptID_fp)mod_GetSymbol(mod, "GetGOScriptID", 8);
1231 osm->GetTriggerScriptID = NULL;
1232 osm->GetCOScriptList = NULL;
1233 osm->CreateInstance = (CreateInstance_fp)mod_GetSymbol(mod, "CreateInstance", 4);
1234 osm->DestroyInstance = (DestroyInstance_fp)mod_GetSymbol(mod, "DestroyInstance", 8);
1235 osm->CallInstanceEvent = (CallInstanceEvent_fp)mod_GetSymbol(mod, "CallInstanceEvent", 16);
1236 osm->SaveRestoreState = (SaveRestoreState_fp)mod_GetSymbol(mod, "SaveRestoreState", 8);
1237
1238 osm->flags |= OSIMF_INUSE;
1239 osm->module_name = mem_strdup(basename);
1240 osm->reference_count = 1;
1241
1242 #ifdef OSIRISDEBUG
1243 ASSERT(osm->RefRoot == NULL);
1244 osm->RefRoot = NULL;
1245 #endif
1246
1247 // make sure all of the functions imported ok
1248 if (!osm->InitializeDLL || !osm->ShutdownDLL || !osm->GetGOScriptID || !osm->CreateInstance ||
1249 !osm->DestroyInstance || !osm->SaveRestoreState || !osm->CallInstanceEvent) {
1250 // there was an error importing a function
1251 mprintf(0, "OSIRIS: Osiris_LoadGameModule(%s) couldn't import function.\n", basename);
1252 Int3();
1253 osm->flags = 0;
1254 if (osm->module_name)
1255 mem_free(osm->module_name);
1256 osm->module_name = NULL;
1257 mod_FreeModule(mod);
1258 return -3;
1259 }
1260
1261 // check to see if there is a corresponding string table to load
1262 char stringtablename[_MAX_PATH];
1263 strcpy(stringtablename, basename);
1264 strcat(stringtablename, ".str");
1265
1266 if (cfexist(stringtablename)) {
1267 // there is a string table, load it up
1268 bool ret = CreateStringTable(stringtablename, &osm->string_table, &osm->strings_loaded);
1269 if (!ret) {
1270 mprintf(0, "OSIRIS: Unable to load string table (%s) for (%s)\n", stringtablename, basename);
1271 Int3();
1272 osm->string_table = NULL;
1273 osm->strings_loaded = 0;
1274 }
1275 } else {
1276 osm->string_table = NULL;
1277 osm->strings_loaded = 0;
1278 }
1279 Osiris_module_init.string_count = osm->strings_loaded;
1280 Osiris_module_init.string_table = osm->string_table;
1281 Osiris_module_init.module_is_static = false; // set this to false to avoid a fake true
1282 Osiris_module_init.script_identifier = osm->module_name;
1283 Osiris_module_init.module_identifier = loaded_id;
1284
1285 // when we get to this point we nearly have a loaded module, we just need to initialize it
1286 if (!osm->InitializeDLL(&Osiris_module_init)) {
1287 // there was an error initializing the module
1288 mprintf(0, "OSIRIS: Osiris_LoadGameModule(%s) error initializing module.\n", basename);
1289 if (osm->string_table) {
1290 DestroyStringTable(osm->string_table, osm->strings_loaded);
1291 }
1292 osm->string_table = NULL;
1293 osm->strings_loaded = 0;
1294 osm->flags = 0;
1295 if (osm->module_name)
1296 mem_free(osm->module_name);
1297 osm->module_name = NULL;
1298 mod_FreeModule(mod);
1299 return -2;
1300 }
1301
1302 if (Osiris_module_init.module_is_static) {
1303 // the module is requesting to be static
1304 mprintf(0, "OSIRIS: Module (%s) is requesting to be static\n", osm->module_name);
1305 osm->flags |= OSIMF_NOUNLOAD;
1306 }
1307
1308 // we have a successful module load
1309 mprintf(0, "OSIRIS: Game Module (%s) loaded successfully\n", basename);
1310 return loaded_id;
1311 }
1312
1313 // Osiris_LoadMissionModule
1314 // Purpose:
1315 // It will attempt to load the module as a game module. If it succeeds
1316 // it will return the id of the module where it has been loaded. If the module was already loaded
1317 // before calling this function, it will return the id to where the module is, and will not reload
1318 // the module. Returns -1 if the module does not exist. Returns -2 if the module couldn't initialize.
1319 // Returns -3 if the module is not a game module. Returns -4 if no module slots are available.
1320 // This technically doesn't load a mission module, as it should already be loaded by
1321 // Descent 3 prior.
1322 int Osiris_LoadMissionModule(module *module_handle, const char *filename) {
1323 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
1324 // no scripts for a client!
1325 return -1;
1326 }
1327
1328 if (!module_handle) {
1329 return -1;
1330 }
1331
1332 int loaded_id;
1333
1334 // find an available slot.
1335 for (loaded_id = 0; loaded_id < MAX_LOADED_MODULES; loaded_id++) {
1336 if (!(OSIRIS_loaded_modules[loaded_id].flags & OSIMF_INUSE)) {
1337 // we found a free slot
1338 break;
1339 }
1340 }
1341
1342 if (loaded_id >= MAX_LOADED_MODULES) {
1343 // no slots available
1344 mprintf(0, "OSIRIS: Osiris_LoadMissionModule(%s): No available slots\n", filename);
1345 Int3();
1346 return -4;
1347 }
1348
1349 // make sure the module exists so we can load it
1350 if (!module_handle->handle) {
1351 // the module does not exist
1352 mprintf(0, "OSIRIS: Osiris_LoadMissionModule(%s): Module doesn't exist\n", filename);
1353 // Int3();
1354 return -1;
1355 }
1356
1357 // the module has loaded, attempt to import all the game functions
1358 tOSIRISModule *osm = &OSIRIS_loaded_modules[loaded_id];
1359 memcpy(&osm->mod, module_handle, sizeof(module));
1360 module *mod = &osm->mod;
1361
1362 // there are 5 functions we need to import
1363 // GetGOScriptID@4
1364 // CreateInstance@4
1365 // DestroyInstance@8
1366 // CallInstanceEvent@16
1367 // SaveRestoreState@8
1368
1369 osm->InitializeDLL = NULL;
1370 osm->ShutdownDLL = NULL;
1371 osm->GetTriggerScriptID = NULL;
1372 osm->GetCOScriptList = NULL;
1373 osm->GetGOScriptID = (GetGOScriptID_fp)mod_GetSymbol(mod, "GetGOScriptID", 8);
1374 osm->CreateInstance = (CreateInstance_fp)mod_GetSymbol(mod, "CreateInstance", 4);
1375 osm->DestroyInstance = (DestroyInstance_fp)mod_GetSymbol(mod, "DestroyInstance", 8);
1376 osm->CallInstanceEvent = (CallInstanceEvent_fp)mod_GetSymbol(mod, "CallInstanceEvent", 16);
1377 osm->SaveRestoreState = (SaveRestoreState_fp)mod_GetSymbol(mod, "SaveRestoreState", 8);
1378
1379 osm->flags = OSIMF_INUSE | OSIMF_DLLELSEWHERE;
1380 osm->module_name = mem_strdup(filename);
1381 osm->reference_count = 1;
1382
1383 #ifdef OSIRISDEBUG
1384 ASSERT(osm->RefRoot == NULL);
1385 osm->RefRoot = NULL;
1386 #endif
1387
1388 // make sure all of the functions imported ok
1389 if (!osm->GetGOScriptID || !osm->CreateInstance || !osm->DestroyInstance || !osm->SaveRestoreState ||
1390 !osm->CallInstanceEvent) {
1391 // there was an error importing a function
1392 mprintf(0, "OSIRIS: Osiris_LoadMissionModule(%s) couldn't import function.\n", filename);
1393 osm->flags = 0;
1394 tOSIRISCurrentMission.mission_loaded = false;
1395 Int3();
1396 // mod_FreeModule(mod); //don't unload it! it's needed by the mission
1397 return -3;
1398 }
1399
1400 // we have a successful module load
1401 tOSIRISCurrentMission.mission_loaded = true;
1402 tOSIRISCurrentMission.dll_id = loaded_id;
1403 if (Show_osiris_debug) {
1404 mprintf(0, "OSIRIS: Mission Game Module (%s) loaded successfully\n", filename);
1405 }
1406 return loaded_id;
1407 }
1408
1409 // Osiris_UnloadMissionModule
1410 // Purpose:
1411 // Instead of saving the handle returned from Osiris_LoadMissionModule() and calling
1412 // Osiris_UnloadModule() with that handle, you can just call this, instead of the call
1413 // to Osiris_UnloadModule().
1414 void Osiris_UnloadMissionModule(void) {
1415 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
1416 // no scripts for a client!
1417 return;
1418 }
1419
1420 if (!tOSIRISCurrentMission.mission_loaded)
1421 return;
1422
1423 int dll_id = tOSIRISCurrentMission.dll_id;
1424
1425 Osiris_FreeModule(dll_id);
1426 }
1427
1428 // Osiris_BindScriptsToObject
1429 // Purpose:
1430 // Call this function after an object has been created to bind all the scripts associated
1431 // with it to the object. This function must be called near the end of it's initialization,
1432 // to make sure that all fields have been filled in. This function does not call any events.
1433 // This function will also load any dll's needed for it's game script.
1434 // returns false if nothing was bound.
1435 bool Osiris_BindScriptsToObject(object *obj) {
1436 ASSERT(obj->osiris_script == NULL);
1437 if (obj->osiris_script) // already has a script bound!
1438 return true;
1439
1440 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
1441 // no scripts for a client!
1442 return false;
1443 }
1444
1445 // make sure the object is valid
1446 if (!CANBEASSIGNEDSCRIPT(obj)) {
1447 // invalid object
1448 return false;
1449 }
1450 int real_type;
1451 real_type = (obj->type == OBJ_DUMMY) ? obj->dummy_type : obj->type;
1452
1453 if (!CANTYPEBEASSIGNEDSCRIPT(real_type)) {
1454 // invalid type
1455 return false;
1456 }
1457
1458 int dll_id, gos_id;
1459 void *gos_instance;
1460 tOSIRISScript *os;
1461
1462 bool isdoor = (bool)(real_type == OBJ_DOOR);
1463 bool iscustomonly = (bool)HAVECUSTOMONLY(real_type);
1464 char *default_module_name;
1465 char *page_name;
1466
1467 if (iscustomonly) {
1468 // this object can only have a custom script for it (i.e. OBJ_CAMERA)
1469 default_module_name = NULL;
1470 page_name = NULL;
1471 } else {
1472 if (isdoor) {
1473 default_module_name = Doors[obj->id].module_name;
1474 page_name = Doors[obj->id].name;
1475 } else {
1476 if (obj->custom_default_module_name) {
1477 // we have a custom default script
1478 default_module_name = obj->custom_default_module_name;
1479 } else {
1480 // use what was set in Object_info
1481 default_module_name = Object_info[obj->id].module_name;
1482 }
1483
1484 if (obj->custom_default_script_name) {
1485 // we have a custom default script
1486 page_name = obj->custom_default_script_name;
1487 } else {
1488 // use what was set in Object_info
1489 if (Object_info[obj->id].script_name_override[0] != '\0')
1490 page_name = Object_info[obj->id].script_name_override;
1491 else
1492 page_name = Object_info[obj->id].name;
1493 }
1494 }
1495 }
1496
1497 if (!iscustomonly) {
1498 // this object can have a default script
1499 ASSERT(default_module_name);
1500 ASSERT(page_name);
1501
1502 // load up the dllname associated with the object and get the id
1503 dll_id = Osiris_LoadGameModule(default_module_name);
1504 if (dll_id < 0) {
1505 // there was an error finding this object's dll
1506 if (Show_osiris_debug) {
1507 mprintf(0, "OSIRIS: Unable to load module (%s) to bind to object (%s)\n", default_module_name, page_name);
1508 }
1509 } else {
1510 // allocate the memory for the object's scripts
1511 obj->osiris_script = (tOSIRISScript *)mem_malloc(sizeof(tOSIRISScript));
1512 if (!obj->osiris_script) {
1513 // out of memory
1514 mprintf(0, "OSIRIS: Out of memory trying to bind script\n");
1515 return false;
1516 }
1517
1518 obj->osiris_script->default_script.script_instance = NULL;
1519 obj->osiris_script->custom_script.script_instance = NULL;
1520 obj->osiris_script->mission_script.script_instance = NULL;
1521 obj->osiris_script->level_script.script_instance = NULL;
1522 os = obj->osiris_script;
1523
1524 // we have the module loaded for the object, now we need to setup it's default script
1525 gos_id = OSIRIS_loaded_modules[dll_id].GetGOScriptID(page_name, isdoor);
1526
1527 if (gos_id == -1) {
1528 // the default script for this object does not exist in the dll set for it
1529 mprintf(0, "OSIRIS: Unable to find GOS ID for (%s) in (%s)!\n", page_name, default_module_name);
1530 Int3();
1531 Osiris_UnloadModule(dll_id);
1532 } else {
1533
1534 // we now have the GOS ID for the script. All future communication with the default script-dll is
1535 // to use this GOS ID. Now try to create an instance of the object. Hopefully we have enough memory.
1536 gos_instance = OSIRIS_loaded_modules[dll_id].CreateInstance(gos_id);
1537 if (!gos_instance) {
1538 // we had an error obtaining the instance of the GOS...ugh
1539 mprintf(0, "OSIRIS: Unable to create GOS instance for (%s)\n", page_name);
1540 Int3();
1541 Osiris_UnloadModule(dll_id);
1542 } else {
1543
1544 // all looks good! we're guaranteed to have at least one script for this object
1545 // setup default script values
1546 os->default_script.DLLID = dll_id;
1547 os->default_script.script_id = gos_id;
1548 os->default_script.script_instance = gos_instance;
1549
1550 // add to the list for this object
1551 #ifdef OSIRISDEBUG
1552 tRefObj *node;
1553 if (OSIRIS_loaded_modules[dll_id].RefRoot == NULL) {
1554 node = OSIRIS_loaded_modules[dll_id].RefRoot = (tRefObj *)mem_malloc(sizeof(tRefObj));
1555 } else {
1556 node = OSIRIS_loaded_modules[dll_id].RefRoot;
1557 while (node->next)
1558 node = node->next;
1559 node->next = (tRefObj *)mem_malloc(sizeof(tRefObj));
1560 node = node->next;
1561 }
1562 node->objnum = OBJNUM(obj);
1563 node->id = obj->id;
1564 node->dummy = (obj->type == OBJ_DUMMY) ? true : false;
1565 node->type = (node->dummy == false) ? obj->type : obj->dummy_type;
1566 node->next = NULL;
1567 #endif
1568 }
1569 }
1570 }
1571 }
1572
1573 // now check for a GOS and COS in the level dll (if available)
1574 if (tOSIRISCurrentLevel.level_loaded) {
1575 dll_id = tOSIRISCurrentLevel.dll_id;
1576
1577 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
1578 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
1579
1580 // check first for a GOS
1581 if (!iscustomonly) {
1582 // this script can have a GOS in the level script
1583 ASSERT(page_name);
1584
1585 gos_id = OSIRIS_loaded_modules[dll_id].GetGOScriptID(page_name, isdoor);
1586 if (gos_id != -1) {
1587 if (!obj->osiris_script) {
1588 // we need to allocate memory for a script
1589 obj->osiris_script = (tOSIRISScript *)mem_malloc(sizeof(tOSIRISScript));
1590 if (!obj->osiris_script) {
1591 // out of memory
1592 mprintf(0, "OSIRIS: Out of memory trying to bind script\n");
1593 return false;
1594 }
1595
1596 obj->osiris_script->default_script.script_instance = NULL;
1597 obj->osiris_script->custom_script.script_instance = NULL;
1598 obj->osiris_script->mission_script.script_instance = NULL;
1599 obj->osiris_script->level_script.script_instance = NULL;
1600 }
1601 os = obj->osiris_script;
1602
1603 // ok, the level dll has a script for us
1604 gos_instance = OSIRIS_loaded_modules[dll_id].CreateInstance(gos_id);
1605 if (!gos_instance) {
1606 // we had an error obtaining the instance of the GOS...ick
1607 mprintf(0, "OSIRIS: Unable to create GOS instance from level dll for (%s)\n", page_name);
1608 Int3();
1609 } else {
1610 // ok, we got a valid instance
1611 os->level_script.DLLID = dll_id;
1612 os->level_script.script_id = gos_id;
1613 os->level_script.script_instance = gos_instance;
1614
1615 #ifdef OSIRISDEBUG
1616 tRefObj *node;
1617 if (OSIRIS_loaded_modules[dll_id].RefRoot == NULL) {
1618 node = OSIRIS_loaded_modules[dll_id].RefRoot = (tRefObj *)mem_malloc(sizeof(tRefObj));
1619 } else {
1620 node = OSIRIS_loaded_modules[dll_id].RefRoot;
1621 while (node->next)
1622 node = node->next;
1623 node->next = (tRefObj *)mem_malloc(sizeof(tRefObj));
1624 node = node->next;
1625 }
1626 node->objnum = OBJNUM(obj);
1627 node->id = obj->id;
1628 node->dummy = (obj->type == OBJ_DUMMY) ? true : false;
1629 node->type = (node->dummy == false) ? obj->type : obj->dummy_type;
1630 node->next = NULL;
1631 #endif
1632 }
1633 }
1634 } // end if(!iscustomonly)
1635
1636 // now check to see if we have a custom script for our handle
1637 int i;
1638 for (i = 0; i < tOSIRISCurrentLevel.num_customs; i++) {
1639 if (obj->handle == tOSIRISCurrentLevel.custom_handles[i]) {
1640 // we found a matching handle, connect it to the script
1641 gos_id = tOSIRISCurrentLevel.custom_ids[i];
1642 if (gos_id != -1) {
1643
1644 if (!obj->osiris_script) {
1645 // we need to allocate memory for a script
1646 obj->osiris_script = (tOSIRISScript *)mem_malloc(sizeof(tOSIRISScript));
1647 if (!obj->osiris_script) {
1648 // out of memory
1649 mprintf(0, "OSIRIS: Out of memory trying to bind script\n");
1650 return false;
1651 }
1652
1653 obj->osiris_script->default_script.script_instance = NULL;
1654 obj->osiris_script->custom_script.script_instance = NULL;
1655 obj->osiris_script->mission_script.script_instance = NULL;
1656 obj->osiris_script->level_script.script_instance = NULL;
1657 }
1658 os = obj->osiris_script;
1659
1660 gos_instance = OSIRIS_loaded_modules[dll_id].CreateInstance(gos_id);
1661 if (!gos_instance) {
1662 // we had an error obtaining the instance of the COS...doh!
1663 mprintf(0, "OSIRIS: Unable to create COS instance from level dll for (%s)\n",
1664 (page_name) ? (page_name) : "<No Name>");
1665 Int3();
1666 } else {
1667 // ok, everything is valid
1668 os->custom_script.DLLID = dll_id;
1669 os->custom_script.script_id = gos_id;
1670 os->custom_script.script_instance = gos_instance;
1671
1672 #ifdef OSIRISDEBUG
1673 tRefObj *node;
1674 if (OSIRIS_loaded_modules[dll_id].RefRoot == NULL) {
1675 node = OSIRIS_loaded_modules[dll_id].RefRoot = (tRefObj *)mem_malloc(sizeof(tRefObj));
1676 } else {
1677 node = OSIRIS_loaded_modules[dll_id].RefRoot;
1678 while (node->next)
1679 node = node->next;
1680 node->next = (tRefObj *)mem_malloc(sizeof(tRefObj));
1681 node = node->next;
1682 }
1683 node->objnum = OBJNUM(obj);
1684 node->id = obj->id;
1685 node->dummy = (obj->type == OBJ_DUMMY) ? true : false;
1686 node->type = (node->dummy == false) ? obj->type : obj->dummy_type;
1687 node->next = NULL;
1688 #endif
1689
1690 if (iscustomonly) {
1691 mprintf(0, "OSIRIS: Attached custom script to 'custom only' object 0x%x\n", obj->handle);
1692 }
1693 }
1694 }
1695 }
1696 }
1697 }
1698 }
1699
1700 // last we need to check the mission dll
1701 if (!iscustomonly) {
1702 // this object can have a script in the mission dll
1703 ASSERT(page_name);
1704
1705 if (tOSIRISCurrentMission.mission_loaded) {
1706 dll_id = tOSIRISCurrentMission.dll_id;
1707
1708 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
1709 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
1710
1711 // check first for a GOS
1712 gos_id = OSIRIS_loaded_modules[dll_id].GetGOScriptID(page_name, isdoor);
1713 if (gos_id != -1) {
1714 if (!obj->osiris_script) {
1715 // we need to allocate memory for a script
1716 obj->osiris_script = (tOSIRISScript *)mem_malloc(sizeof(tOSIRISScript));
1717 if (!obj->osiris_script) {
1718 // out of memory
1719 mprintf(0, "OSIRIS: Out of memory trying to bind script\n");
1720 return false;
1721 }
1722
1723 obj->osiris_script->default_script.script_instance = NULL;
1724 obj->osiris_script->custom_script.script_instance = NULL;
1725 obj->osiris_script->mission_script.script_instance = NULL;
1726 obj->osiris_script->level_script.script_instance = NULL;
1727 }
1728 os = obj->osiris_script;
1729
1730 // ok, the mission dll has a script for us
1731 gos_instance = OSIRIS_loaded_modules[dll_id].CreateInstance(gos_id);
1732 if (!gos_instance) {
1733 // we had an error obtaining the instance of the GOS...ick
1734 mprintf(0, "OSIRIS: Unable to create GOS instance from mission dll for (%s)\n", page_name);
1735 Int3();
1736 } else {
1737 // ok, we got a valid instance
1738 os->mission_script.DLLID = dll_id;
1739 os->mission_script.script_id = gos_id;
1740 os->mission_script.script_instance = gos_instance;
1741
1742 #ifdef OSIRISDEBUG
1743 tRefObj *node;
1744 if (OSIRIS_loaded_modules[dll_id].RefRoot == NULL) {
1745 node = OSIRIS_loaded_modules[dll_id].RefRoot = (tRefObj *)mem_malloc(sizeof(tRefObj));
1746 } else {
1747 node = OSIRIS_loaded_modules[dll_id].RefRoot;
1748 while (node->next)
1749 node = node->next;
1750 node->next = (tRefObj *)mem_malloc(sizeof(tRefObj));
1751 node = node->next;
1752 }
1753 node->objnum = OBJNUM(obj);
1754 node->id = obj->id;
1755 node->dummy = (obj->type == OBJ_DUMMY) ? true : false;
1756 node->type = (node->dummy == false) ? obj->type : obj->dummy_type;
1757 node->next = NULL;
1758 #endif
1759 }
1760 }
1761 }
1762 }
1763 } // end if(!iscustomonly)
1764
1765 return true;
1766 }
1767
1768 // Osiris_DetachScriptsFromObject
1769 // Purpose:
1770 // Call this function when an object is about to be destroyed. This will unbind and remove
1771 // all scripts associated with that object. This function does not call any events.
1772 void Osiris_DetachScriptsFromObject(object *obj) {
1773 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
1774 // no scripts for a client!
1775 return;
1776 }
1777
1778 // make sure the object is valid
1779 if (!CANHAVEANYSCRIPT(obj)) {
1780 // invalid object
1781 return;
1782 }
1783
1784 if (!obj->osiris_script) {
1785 return;
1786 }
1787
1788 // free the memory for the allocated script
1789 tOSIRISSCRIPTID osid;
1790 osid.objhandle = obj->handle;
1791 osid.type = OBJECT_SCRIPT;
1792 Osiris_FreeMemoryForScript(&osid);
1793
1794 int dll_id;
1795 tOSIRISScript *os;
1796
1797 os = obj->osiris_script;
1798
1799 // free up the scripts for the object, starting with it's default script
1800 if (os->default_script.script_instance) {
1801 // first we need to free the instance
1802 dll_id = os->default_script.DLLID;
1803
1804 #ifdef OSIRISDEBUG
1805 tRefObj *prev = NULL, *node = OSIRIS_loaded_modules[dll_id].RefRoot;
1806 while (node) {
1807 if (node->objnum == OBJNUM(obj)) {
1808 // free this node
1809 if (prev)
1810 prev->next = node->next;
1811 else {
1812 ASSERT(node == OSIRIS_loaded_modules[dll_id].RefRoot);
1813 OSIRIS_loaded_modules[dll_id].RefRoot = node->next;
1814 }
1815
1816 mem_free(node);
1817 break;
1818 }
1819 prev = node;
1820 node = node->next;
1821 }
1822 ASSERT(node); // make sure we found the node
1823 #endif
1824
1825 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
1826 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
1827
1828 OSIRIS_loaded_modules[dll_id].DestroyInstance(os->default_script.script_id, os->default_script.script_instance);
1829
1830 // now decrement the dll's count
1831 Osiris_UnloadModule(dll_id);
1832 }
1833
1834 os->default_script.DLLID = 0;
1835 os->default_script.script_id = 0;
1836 os->default_script.script_instance = NULL;
1837 }
1838
1839 // now check for the level script
1840 if (os->level_script.script_instance) {
1841 // free the instance
1842 dll_id = os->level_script.DLLID;
1843
1844 #ifdef OSIRISDEBUG
1845 tRefObj *prev = NULL, *node = OSIRIS_loaded_modules[dll_id].RefRoot;
1846 while (node) {
1847 if (node->objnum == OBJNUM(obj)) {
1848 // free this node
1849 if (prev)
1850 prev->next = node->next;
1851 else {
1852 ASSERT(node == OSIRIS_loaded_modules[dll_id].RefRoot);
1853 OSIRIS_loaded_modules[dll_id].RefRoot = node->next;
1854 }
1855
1856 mem_free(node);
1857 break;
1858 }
1859 prev = node;
1860 node = node->next;
1861 }
1862 ASSERT(node); // make sure we found the node
1863 #endif
1864
1865 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
1866 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
1867
1868 OSIRIS_loaded_modules[dll_id].DestroyInstance(os->level_script.script_id, os->level_script.script_instance);
1869 }
1870
1871 os->level_script.DLLID = 0;
1872 os->level_script.script_id = 0;
1873 os->level_script.script_instance = NULL;
1874 }
1875
1876 // check for an attached custom script
1877 if (os->custom_script.script_instance) {
1878 // free the instance
1879 dll_id = os->custom_script.DLLID;
1880
1881 #ifdef OSIRISDEBUG
1882 tRefObj *prev = NULL, *node = OSIRIS_loaded_modules[dll_id].RefRoot;
1883 while (node) {
1884 if (node->objnum == OBJNUM(obj)) {
1885 // free this node
1886 if (prev)
1887 prev->next = node->next;
1888 else {
1889 ASSERT(node == OSIRIS_loaded_modules[dll_id].RefRoot);
1890 OSIRIS_loaded_modules[dll_id].RefRoot = node->next;
1891 }
1892
1893 mem_free(node);
1894 break;
1895 }
1896 prev = node;
1897 node = node->next;
1898 }
1899 ASSERT(node); // make sure we found the node
1900 #endif
1901
1902 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
1903 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
1904
1905 OSIRIS_loaded_modules[dll_id].DestroyInstance(os->custom_script.script_id, os->custom_script.script_instance);
1906 }
1907
1908 os->custom_script.DLLID = 0;
1909 os->custom_script.script_id = 0;
1910 os->custom_script.script_instance = NULL;
1911 }
1912
1913 // check for a mission dll script
1914 if (os->mission_script.script_instance) {
1915 // free the instance
1916 dll_id = os->mission_script.DLLID;
1917
1918 #ifdef OSIRISDEBUG
1919 tRefObj *prev = NULL, *node = OSIRIS_loaded_modules[dll_id].RefRoot;
1920 while (node) {
1921 if (node->objnum == OBJNUM(obj)) {
1922 // free this node
1923 if (prev)
1924 prev->next = node->next;
1925 else {
1926 ASSERT(node == OSIRIS_loaded_modules[dll_id].RefRoot);
1927 OSIRIS_loaded_modules[dll_id].RefRoot = node->next;
1928 }
1929
1930 mem_free(node);
1931 break;
1932 }
1933 prev = node;
1934 node = node->next;
1935 }
1936 ASSERT(node); // make sure we found the node
1937 #endif
1938
1939 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
1940 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
1941
1942 OSIRIS_loaded_modules[dll_id].DestroyInstance(os->mission_script.script_id, os->mission_script.script_instance);
1943 }
1944
1945 os->mission_script.DLLID = 0;
1946 os->mission_script.script_id = 0;
1947 os->mission_script.script_instance = NULL;
1948 }
1949
1950 // finally free up the memory allocated for the script struct
1951 mem_free(obj->osiris_script);
1952 obj->osiris_script = NULL;
1953 }
1954
1955 // Osiris_CallLevelEvent
1956 // Purpose:
1957 // Triggers an event for a level script. Returns true if the default action should continue
1958 // to process.
1959 bool Osiris_CallLevelEvent(int event, tOSIRISEventInfo *data) {
1960 if (!Osiris_level_script_loaded)
1961 return true;
1962
1963 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
1964 // no scripts for a client!
1965 return true;
1966 }
1967
1968 if (!(Osiris_event_mask & OEM_LEVELS))
1969 return true; // level events are disabled
1970
1971 if (!Osiris_IsEventEnabled(event))
1972 return true;
1973
1974 int aux_event = -1;
1975 if (event == EVT_AI_NOTIFY) {
1976 switch (data->evt_ai_notify.notify_type) {
1977 case AIN_GOAL_COMPLETE:
1978 aux_event = EVT_AIN_GOALCOMPLETE;
1979 break;
1980 case AIN_GOAL_INVALID:
1981 aux_event = EVT_AIN_GOALFAIL;
1982 break;
1983 case AIN_GOAL_FAIL:
1984 aux_event = EVT_AIN_GOALFAIL;
1985 break;
1986 case AIN_GOAL_ERROR:
1987 aux_event = EVT_AIN_GOALFAIL;
1988 break;
1989 }
1990 }
1991
1992 if (tOSIRISCurrentLevel.level_loaded) {
1993 // there is a loaded level, get it's dll id and call it's event
1994 int dll_id = tOSIRISCurrentLevel.dll_id;
1995 void *instance = tOSIRISCurrentLevel.instance;
1996
1997 if (instance) {
1998 data->me_handle = OBJECT_HANDLE_NONE; // its a level script!...no me
1999 int16_t ret;
2000
2001 ret = OSIRIS_loaded_modules[dll_id].CallInstanceEvent(0, instance, event, data);
2002 if (aux_event != -1) {
2003 // call child event
2004 ret = OSIRIS_loaded_modules[dll_id].CallInstanceEvent(0, instance, aux_event, data);
2005 }
2006
2007 return (bool)((ret & CONTINUE_DEFAULT) != 0);
2008 }
2009 }
2010
2011 return true;
2012 }
2013
2014 // Osiris_CallTriggerEvent
2015 // Purpose:
2016 // Triggers an event for a trigger script. Returns true if the default action should continue
2017 // to process.
2018 bool Osiris_CallTriggerEvent(int trignum, int event, tOSIRISEventInfo *ei) {
2019 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
2020 // no scripts for a client!
2021 return true;
2022 }
2023
2024 if (!(Osiris_event_mask & OEM_TRIGGERS))
2025 return true; // trigger events are disabled
2026
2027 if (!Osiris_IsEventEnabled(event))
2028 return true;
2029
2030 if (trignum < 0 || trignum >= Num_triggers)
2031 return true;
2032
2033 if (!tOSIRISCurrentLevel.level_loaded)
2034 return true;
2035
2036 int dll_id, script_id;
2037 int aux_event = -1;
2038 void *instance;
2039
2040 if (event == EVT_AI_NOTIFY) {
2041 switch (ei->evt_ai_notify.notify_type) {
2042 case AIN_GOAL_COMPLETE:
2043 aux_event = EVT_AIN_GOALCOMPLETE;
2044 break;
2045 case AIN_GOAL_INVALID:
2046 aux_event = EVT_AIN_GOALFAIL;
2047 break;
2048 case AIN_GOAL_FAIL:
2049 aux_event = EVT_AIN_GOALFAIL;
2050 break;
2051 case AIN_GOAL_ERROR:
2052 aux_event = EVT_AIN_GOALFAIL;
2053 break;
2054 }
2055 }
2056
2057 dll_id = tOSIRISCurrentLevel.dll_id;
2058 script_id = Triggers[trignum].osiris_script.script_id;
2059 instance = Triggers[trignum].osiris_script.script_instance;
2060
2061 if (instance) {
2062 int16_t ret;
2063 ret = OSIRIS_loaded_modules[dll_id].CallInstanceEvent(script_id, instance, event, ei);
2064
2065 if (aux_event != -1) {
2066 // call child event
2067 ret = OSIRIS_loaded_modules[dll_id].CallInstanceEvent(script_id, instance, aux_event, ei);
2068 }
2069
2070 return (bool)((ret & CONTINUE_DEFAULT) != 0);
2071 }
2072
2073 return true;
2074 }
2075
2076 // Osiris_EnableEvents
2077 // Purpose:
2078 // Enables the passed in mask of event types to be called
2079 void Osiris_EnableEvents(uint8_t mask) { Osiris_event_mask |= mask; }
2080
2081 // Osiris_DisableEvents
2082 // Purpose:
2083 // Disables the passed in mask of event types
2084 void Osiris_DisableEvents(uint8_t mask) { Osiris_event_mask &= ~mask; }
2085
2086 // Osiris_DisableCreateEvents
2087 // Purpose:
2088 // Disables any events involved when an object is created. This is to be used for
2089 // Loading games/viewing demos, as so not to re-initialize good data.
2090 void Osiris_DisableCreateEvents(void) { Osiris_create_events_disabled = true; }
2091
2092 // Osiris_EnablesCreateEvents
2093 // Purpose:
2094 // Enables any events involved when an object is created. This is to be used for
2095 // Loading games/viewing demos, as so not to re-initialize good data. (call when done with
2096 // Osiris_DisableCreateEvents())
2097 void Osiris_EnableCreateEvents(void) { Osiris_create_events_disabled = false; }
2098
2099 // Osiris_IsEventEnabled
2100 // Purpose:
2101 // Returns true if the event is allowed to be called
2102 bool Osiris_IsEventEnabled(int event) {
2103 switch (event) {
2104 case EVT_CREATED:
2105 case EVT_AI_INIT:
2106 return !Osiris_create_events_disabled;
2107 break;
2108 default:
2109 return true;
2110 break;
2111 }
2112 return true;
2113 }
2114
2115 // Osiris_CallEvent
2116 // Purpose:
2117 // Triggers an event for an object. Pass in the event number and the associated
2118 // structure of data. All events will be chained through the associated scripts of the
2119 // object (as long as they are available) in the order: custom script, level script,
2120 // mission script, and finally it's default script. The chain breaks if one of the scripts
2121 // returns false on the call to their CallInstanceEvent().
2122 bool Osiris_CallEvent(object *obj, int event, tOSIRISEventInfo *data) {
2123 if ((Game_mode & GM_MULTI) && (Netgame.local_role != LR_SERVER)) {
2124 // no scripts for a client!
2125 return true;
2126 }
2127
2128 if (!(Osiris_event_mask & OEM_OBJECTS))
2129 return true; // object events are disabled
2130
2131 if (!Osiris_IsEventEnabled(event))
2132 return true;
2133
2134 // make sure the object is valid
2135 if (!CANHAVEANYSCRIPT(obj)) {
2136 // invalid object
2137 return true;
2138 }
2139
2140 if (!obj->osiris_script) {
2141 // mprintf(0,"OSIRIS: Unhandled event (%d) for object id=%d\n",event,obj->id);
2142 return true; // no script for this object...hmm
2143 }
2144
2145 int dll_id;
2146 int aux_event = -1; // event value
2147 tOSIRISScript *os;
2148 int16_t ret = CONTINUE_CHAIN | CONTINUE_DEFAULT;
2149
2150 if (event == EVT_AI_NOTIFY) {
2151 switch (data->evt_ai_notify.notify_type) {
2152 case AIN_OBJ_KILLED:
2153 aux_event = EVT_AIN_OBJKILLED;
2154 break;
2155 case AIN_SEE_TARGET:
2156 aux_event = EVT_AIN_SEEPLAYER;
2157 break;
2158 case AIN_WHIT_OBJECT:
2159 aux_event = EVT_AIN_WHITOBJECT;
2160 break;
2161 case AIN_GOAL_COMPLETE:
2162 aux_event = EVT_AIN_GOALCOMPLETE;
2163 break;
2164 case AIN_GOAL_INVALID:
2165 aux_event = EVT_AIN_GOALFAIL;
2166 break;
2167 case AIN_GOAL_FAIL:
2168 aux_event = EVT_AIN_GOALFAIL;
2169 break;
2170 case AIN_GOAL_ERROR:
2171 aux_event = EVT_AIN_GOALFAIL;
2172 break;
2173 case AIN_MELEE_HIT:
2174 aux_event = EVT_AIN_MELEE_HIT;
2175 break;
2176 case AIN_MELEE_ATTACK_FRAME:
2177 aux_event = EVT_AIN_MELEE_ATTACK_FRAME;
2178 break;
2179 case AIN_MOVIE_START:
2180 aux_event = EVT_AIN_MOVIE_START;
2181 break;
2182 case AIN_MOVIE_END:
2183 aux_event = EVT_AIN_MOVIE_END;
2184 break;
2185 }
2186 }
2187
2188 os = obj->osiris_script;
2189 data->me_handle = obj->handle;
2190
2191 if (os->custom_script.script_instance) {
2192 dll_id = os->custom_script.DLLID;
2193
2194 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
2195 if (aux_event != -1) {
2196 // call the child event
2197 OSIRIS_loaded_modules[dll_id].CallInstanceEvent(os->custom_script.script_id, os->custom_script.script_instance,
2198 aux_event, data);
2199 }
2200
2201 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
2202
2203 // call the event
2204 ret = OSIRIS_loaded_modules[dll_id].CallInstanceEvent(os->custom_script.script_id,
2205 os->custom_script.script_instance, event, data);
2206 }
2207 }
2208
2209 if ((ret & CONTINUE_CHAIN) && os->level_script.script_instance) {
2210 dll_id = os->level_script.DLLID;
2211
2212 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
2213 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
2214
2215 if (aux_event != -1) {
2216 // call the child event
2217 OSIRIS_loaded_modules[dll_id].CallInstanceEvent(os->level_script.script_id, os->level_script.script_instance,
2218 aux_event, data);
2219 }
2220
2221 // call the event
2222 ret = OSIRIS_loaded_modules[dll_id].CallInstanceEvent(os->level_script.script_id,
2223 os->level_script.script_instance, event, data);
2224 }
2225 }
2226
2227 if ((ret & CONTINUE_CHAIN) && os->mission_script.script_instance) {
2228 dll_id = os->mission_script.DLLID;
2229
2230 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
2231 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
2232 if (aux_event != -1) {
2233 // call the child event
2234 OSIRIS_loaded_modules[dll_id].CallInstanceEvent(os->mission_script.script_id,
2235 os->mission_script.script_instance, aux_event, data);
2236 }
2237
2238 // call the event
2239 ret = OSIRIS_loaded_modules[dll_id].CallInstanceEvent(os->mission_script.script_id,
2240 os->mission_script.script_instance, event, data);
2241 }
2242 }
2243
2244 if ((ret & CONTINUE_CHAIN) && os->default_script.script_instance) {
2245 dll_id = os->default_script.DLLID;
2246
2247 ASSERT(OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE);
2248 if (OSIRIS_loaded_modules[dll_id].flags & OSIMF_INUSE) {
2249
2250 if (aux_event != -1) {
2251 // call the child event
2252 OSIRIS_loaded_modules[dll_id].CallInstanceEvent(os->default_script.script_id,
2253 os->default_script.script_instance, aux_event, data);
2254 }
2255
2256 // call the event
2257 ret = OSIRIS_loaded_modules[dll_id].CallInstanceEvent(os->default_script.script_id,
2258 os->default_script.script_instance, event, data);
2259 }
2260 }
2261
2262 return (bool)((ret & CONTINUE_DEFAULT) != 0);
2263 }
2264
2265 #define MAX_OSIRIS_TIMERS 64
2266 #define OITF_USED 0x0001
2267 #define OITF_REPEATCALL 0x0002
2268 #define OITF_TRIGGERTIMER 0x0004
2269 #define OITF_LEVELTIMER 0x0008
2270 #define OITF_CANCELONDEAD 0x0010
2271 struct tOSIRISINTERNALTIMER {
2272 uint16_t flags;
2273 union {
2274 int objhandle;
2275 int trignum;
2276 };
2277 int id;
2278 int repeat_count;
2279 int objhandle_detonator;
2280 int handle;
2281 float timer_interval;
2282 float timer_next_signal;
2283 float timer_end;
2284 };
2285 tOSIRISINTERNALTIMER OsirisTimers[MAX_OSIRIS_TIMERS];
2286
2287 static inline int FORM_HANDLE(int counter, int slot) { return (((counter & 0xFFFFFF) << 8) | (slot & 0xFF)); }
2288
2289 static inline int GET_SLOT(int handle) { return (handle & 0xFF); }
2290
2291 int Osiris_timer_counter = 0;
2292
2293 // Osiris_ProcessTimers
2294 // Purpose:
2295 // This function checks all timers currently running, if any need to be signaled it signals them.
2296 void Osiris_ProcessTimers(void) {
2297 object *obj;
2298 bool signal, kill;
2299 tOSIRISEventInfo ei;
2300
2301 for (int i = 0; i < MAX_OSIRIS_TIMERS; i++) {
2302 signal = false;
2303 kill = false;
2304
2305 if (OsirisTimers[i].flags & OITF_USED) {
2306
2307 if (OsirisTimers[i].flags & OITF_CANCELONDEAD) {
2308 obj = ObjGet(OsirisTimers[i].objhandle_detonator);
2309 if (!obj || (obj->type == OBJ_GHOST) ||
2310 (obj->type == OBJ_PLAYER && Players[obj->id].flags & (PLAYER_FLAGS_DYING | PLAYER_FLAGS_DEAD))) {
2311 // the detontator died...cancel the timer!
2312 OsirisTimers[i].flags &= ~OITF_USED;
2313 OsirisTimers[i].repeat_count = 0;
2314
2315 tOSIRISEventInfo ei;
2316 ei.evt_timercancel.detonated = 1;
2317 ei.evt_timercancel.handle = OsirisTimers[i].handle;
2318
2319 if (OsirisTimers[i].flags & OITF_TRIGGERTIMER) {
2320 Osiris_CallTriggerEvent(OsirisTimers[i].trignum, EVT_TIMERCANCEL, &ei);
2321 } else if (OsirisTimers[i].flags & OITF_LEVELTIMER) {
2322 Osiris_CallLevelEvent(EVT_TIMERCANCEL, &ei);
2323 } else {
2324 object *obj = ObjGet(OsirisTimers[i].objhandle);
2325 if (obj)
2326 Osiris_CallEvent(obj, EVT_TIMERCANCEL, &ei);
2327 }
2328
2329 mprintf(0, "OSIRIS TIMER: Cancelling Timer (%d/%d)\n", OsirisTimers[i].handle, i);
2330 continue;
2331 }
2332 }
2333
2334 if (OsirisTimers[i].timer_next_signal <= Gametime) {
2335 // this timer needs to be signaled
2336 signal = true;
2337
2338 if (OsirisTimers[i].flags & OITF_REPEATCALL) {
2339 // this is a repeater
2340 if (OsirisTimers[i].repeat_count != -1) {
2341 // it has a finite repeat
2342 OsirisTimers[i].repeat_count--;
2343 if (OsirisTimers[i].repeat_count <= 0) {
2344 // remove the timer
2345 kill = true;
2346 OsirisTimers[i].repeat_count = 0;
2347 } else {
2348 // adjust for next signal
2349 OsirisTimers[i].timer_next_signal += OsirisTimers[i].timer_interval;
2350 }
2351 } else {
2352 // infinite repeat
2353 OsirisTimers[i].timer_next_signal += OsirisTimers[i].timer_interval;
2354 }
2355 }
2356 }
2357
2358 if ((!((OsirisTimers[i].flags & OITF_REPEATCALL) && (OsirisTimers[i].repeat_count == -1))) &&
2359 OsirisTimers[i].timer_end <= Gametime) {
2360
2361 // this timer has expired, remove it
2362 kill = true;
2363 // signal timer
2364 signal = true;
2365 }
2366
2367 if (signal) {
2368 ei.evt_timer.game_time = Gametime;
2369 ei.evt_timer.id = OsirisTimers[i].id;
2370 }
2371
2372 // this timer is currently in use, see what kind of trigger it is
2373 if (OsirisTimers[i].flags & OITF_TRIGGERTIMER) {
2374 // trigger timer
2375 if (signal) {
2376 Osiris_CallTriggerEvent(OsirisTimers[i].trignum, EVT_TIMER, &ei);
2377 }
2378 } else if (OsirisTimers[i].flags & OITF_LEVELTIMER) {
2379 // level timer
2380 if (signal) {
2381 Osiris_CallLevelEvent(EVT_TIMER, &ei);
2382 }
2383 } else {
2384 // object timer
2385 obj = ObjGet(OsirisTimers[i].objhandle);
2386 if (obj) {
2387 // process this object timer
2388 if (signal) {
2389 Osiris_CallEvent(obj, EVT_TIMER, &ei);
2390 }
2391 } else {
2392 // this object no longer exists, remove the timer
2393 kill = true;
2394 }
2395 }
2396
2397 if (kill)
2398 OsirisTimers[i].flags &= ~OITF_USED;
2399 }
2400 }
2401 }
2402
2403 // Osiris_ResetAllTimers
2404 // Purpose:
2405 // Flushes all the timers
2406 void Osiris_ResetAllTimers(void) {
2407 for (int i = 0; i < MAX_OSIRIS_TIMERS; i++) {
2408 OsirisTimers[i].flags = 0;
2409 }
2410 }
2411
2412 // Osiris_CreateTimer
2413 // Pupose:
2414 // Adds a timer to the list to be processed. You'll receive a EVT_TIMER when the timer is signaled.
2415 // Returns an id to the timer, which can be used to cancel a timer. -1 on error.
2416 int Osiris_CreateTimer(tOSIRISTIMER *ot) {
2417 // find an empty timer
2418 int i;
2419 for (i = 0; i < MAX_OSIRIS_TIMERS; i++) {
2420 if (!(OsirisTimers[i].flags & OITF_USED)) {
2421 break;
2422 }
2423 }
2424
2425 if (i >= MAX_OSIRIS_TIMERS)
2426 return -1; // no more slots available
2427
2428 // clear out the slots
2429 OsirisTimers[i].flags = 0;
2430 OsirisTimers[i].id = 0;
2431 OsirisTimers[i].objhandle = 0;
2432 OsirisTimers[i].repeat_count = 0;
2433 OsirisTimers[i].timer_end = 0;
2434 OsirisTimers[i].timer_interval = 0;
2435 OsirisTimers[i].timer_next_signal = 0;
2436 OsirisTimers[i].handle = 0;
2437 OsirisTimers[i].objhandle_detonator = OBJECT_HANDLE_NONE;
2438
2439 // fill in the data
2440 OsirisTimers[i].flags |= OITF_USED;
2441 OsirisTimers[i].id = ot->id;
2442 OsirisTimers[i].timer_end = ot->timer_interval + Gametime;
2443 OsirisTimers[i].timer_interval = ot->timer_interval;
2444 OsirisTimers[i].timer_next_signal = ot->timer_interval + Gametime;
2445
2446 if (ot->flags & OTF_TRIGGER) {
2447 OsirisTimers[i].trignum = ot->trigger_number;
2448 OsirisTimers[i].flags |= OITF_TRIGGERTIMER;
2449 } else if (ot->flags & OTF_LEVEL) {
2450 OsirisTimers[i].flags |= OITF_LEVELTIMER;
2451 } else {
2452 OsirisTimers[i].objhandle = ot->object_handle;
2453 }
2454
2455 if (ot->flags & OTF_REPEATER) {
2456 // this is a repeater timer
2457 OsirisTimers[i].flags |= OITF_REPEATCALL;
2458 OsirisTimers[i].repeat_count = ot->repeat_count;
2459 if (ot->repeat_count != -1) {
2460 OsirisTimers[i].timer_end = (ot->timer_interval * ot->repeat_count) + Gametime;
2461 }
2462 }
2463
2464 if (ot->flags & OTF_CANCELONDEAD) {
2465 // there is a detonator
2466 OsirisTimers[i].flags |= OITF_CANCELONDEAD;
2467 OsirisTimers[i].objhandle_detonator = ot->object_handle_detonator;
2468 }
2469
2470 // create a handle
2471 Osiris_timer_counter++;
2472 int handle = FORM_HANDLE(Osiris_timer_counter, i);
2473
2474 OsirisTimers[i].handle = handle;
2475
2476 return handle;
2477 }
2478
2479 // Osiris_CancelTimer
2480 // Purpose:
2481 // Cancels a timer that's in use, given its handle
2482 void Osiris_CancelTimer(int handle) {
2483 int slot;
2484
2485 slot = GET_SLOT(handle);
2486
2487 if (slot < 0 || slot >= MAX_OSIRIS_TIMERS)
2488 return;
2489
2490 if (OsirisTimers[slot].handle != handle) // not the same timer
2491 return;
2492
2493 OsirisTimers[slot].flags &= ~OITF_USED;
2494
2495 tOSIRISEventInfo ei;
2496 ei.evt_timercancel.detonated = 0;
2497 ei.evt_timercancel.handle = handle;
2498
2499 if (OsirisTimers[slot].flags & OITF_TRIGGERTIMER) {
2500 Osiris_CallTriggerEvent(OsirisTimers[slot].trignum, EVT_TIMERCANCEL, &ei);
2501 } else if (OsirisTimers[slot].flags & OITF_LEVELTIMER) {
2502 Osiris_CallLevelEvent(EVT_TIMERCANCEL, &ei);
2503 } else {
2504 object *obj = ObjGet(OsirisTimers[slot].objhandle);
2505 if (obj)
2506 Osiris_CallEvent(obj, EVT_TIMERCANCEL, &ei);
2507 }
2508 }
2509
2510 // Osiris_GetTimerHandle
2511 // Purpose:
2512 // Gets the handle for the timer with the specified id
2513 int Osiris_GetTimerHandle(int id) {
2514 // Look for timer with this ID
2515 for (int i = 0; i < MAX_OSIRIS_TIMERS; i++)
2516 if ((OsirisTimers[i].flags & OITF_USED) && (OsirisTimers[i].id == id)) {
2517 return OsirisTimers[i].handle;
2518 }
2519
2520 return 0;
2521 }
2522
2523 // Osiris_CancelTimer
2524 // Purpose:
2525 // Cancels a timer given its ID
2526 void Osiris_CancelTimerID(int id) {
2527 // Look for timer with this ID
2528 for (int i = 0; i < MAX_OSIRIS_TIMERS; i++)
2529 if ((OsirisTimers[i].flags & OITF_USED) && (OsirisTimers[i].id == id)) {
2530 Osiris_CancelTimer(OsirisTimers[i].handle);
2531 return;
2532 }
2533 }
2534
2535 // Osiris_TimerExists
2536 // Purpose:
2537 // Returns true if the timer is valid
2538 uint8_t Osiris_TimerExists(int handle) {
2539 int id = GET_SLOT(handle);
2540
2541 if (id < 0 || id >= MAX_OSIRIS_TIMERS)
2542 return false;
2543
2544 if (!(OsirisTimers[id].flags & OITF_USED))
2545 return false;
2546
2547 if (OsirisTimers[id].handle != handle) // not the same timer
2548 return false;
2549
2550 return true;
2551 }
2552
2553 // Osiris_TimerTimeRemaining
2554 // Purpose:
2555 // Returns the amount of time remaining on the specified timer
2556 float Osiris_TimerTimeRemaining(int handle) {
2557 int id = GET_SLOT(handle);
2558
2559 if (id < 0 || id >= MAX_OSIRIS_TIMERS)
2560 return -1.0;
2561
2562 if (!(OsirisTimers[id].flags & OITF_USED))
2563 return -1.0;
2564
2565 if (OsirisTimers[id].handle != handle) // not the same timer
2566 return -1.0;
2567
2568 return (OsirisTimers[id].timer_end - Gametime);
2569 }
2570
2571 #define OSIRIS_SYSTEM_FILEVERSION 0x01
2572 // Osiris_SaveSystemState
2573 // Purpose:
2574 // Saves the current state of the system (not the scripts!) to file
2575 void Osiris_SaveSystemState(CFILE *file) {
2576 int i;
2577 int save_start = cftell(file);
2578 int checksum_pos;
2579
2580 cf_WriteString(file, "OSIRIS");
2581
2582 cf_WriteByte(file, OSIRIS_SYSTEM_FILEVERSION);
2583
2584 checksum_pos = cftell(file);
2585 cf_WriteInt(file, 0); // this will be # of bytes writtens
2586
2587 cf_WriteInt(file, Osiris_timer_counter);
2588
2589 // save out the timer state
2590 for (i = 0; i < MAX_OSIRIS_TIMERS; i++) {
2591 if (OsirisTimers[i].flags & OITF_USED) {
2592 // write out information about this timer
2593 cf_WriteByte(file, 1); // timer exists
2594 cf_WriteShort(file, OsirisTimers[i].flags);
2595 cf_WriteInt(file, OsirisTimers[i].id);
2596 cf_WriteInt(file, OsirisTimers[i].repeat_count);
2597 cf_WriteFloat(file, OsirisTimers[i].timer_interval);
2598 cf_WriteFloat(file, OsirisTimers[i].timer_next_signal);
2599 cf_WriteFloat(file, OsirisTimers[i].timer_end);
2600 cf_WriteInt(file, OsirisTimers[i].objhandle);
2601 cf_WriteInt(file, OsirisTimers[i].objhandle_detonator);
2602 cf_WriteInt(file, OsirisTimers[i].handle);
2603 } else {
2604 cf_WriteByte(file, 0);
2605 }
2606 }
2607
2608 // auto-save script mallocs
2609 Osiris_SaveMemoryChunks(file);
2610
2611 // go through all loaded DLLs and save states
2612 // this is touchy, we need to make sure all DLL modules that are currently
2613 // loaded, be loaded when we restore states. As a safety precaution, the Global
2614 // state will be saved as the following (an array of the following):
2615 // byte offset size description
2616 // 0 1 Number of loaded DLLs
2617 // ...
2618 // +1 1 String length of module name
2619 // +2 x Name of the module
2620 // +2+x 4 Size of global data stored
2621 // +6+x y global data
2622 // ...
2623
2624 // first count up the number of loaded modules
2625 int loaded_module_count = 0;
2626 for (i = 0; i < MAX_LOADED_MODULES; i++) {
2627 if (OSIRIS_loaded_modules[i].flags & OSIMF_INUSE) {
2628 // this is a loaded module
2629 loaded_module_count++;
2630 }
2631 }
2632
2633 cf_WriteByte(file, loaded_module_count);
2634
2635 for (i = 0; i < MAX_LOADED_MODULES; i++) {
2636 if (OSIRIS_loaded_modules[i].flags & OSIMF_INUSE) {
2637 // get the length of the module name
2638 int module_name_length = strlen(OSIRIS_loaded_modules[i].module_name) + 1;
2639 cf_WriteByte(file, module_name_length);
2640 cf_WriteBytes((uint8_t *)OSIRIS_loaded_modules[i].module_name, module_name_length, file);
2641
2642 // now here is the tricky part, save the current fileposition, write a dummy 0 int
2643 int saved_file_pos = cftell(file);
2644 cf_WriteInt(file, 0);
2645
2646 int global_size = OSIRIS_loaded_modules[i].SaveRestoreState(file, 1);
2647 int restore_file_pos = cftell(file);
2648
2649 // now jump back and fill in the correct global data size, than jump back
2650 cfseek(file, saved_file_pos, SEEK_SET);
2651 cf_WriteInt(file, global_size);
2652 cfseek(file, restore_file_pos, SEEK_SET);
2653 }
2654 }
2655
2656 // Go through all the objects and call their EVT_SAVESTATE (if they have a script)
2657 Osiris_SaveOMMS(file);
2658
2659 tOSIRISEventInfo ei;
2660 ei.evt_savestate.fileptr = (void *)file;
2661
2662 Osiris_CallLevelEvent(EVT_SAVESTATE, &ei);
2663
2664 for (i = 0; i <= Num_triggers; i++) {
2665 Osiris_CallTriggerEvent(i, EVT_SAVESTATE, &ei);
2666 }
2667
2668 for (i = 0; i < MAX_OBJECTS; i++) {
2669 if (Objects[i].type != OBJ_NONE && Objects[i].osiris_script) {
2670 Osiris_CallEvent(&Objects[i], EVT_SAVESTATE, &ei);
2671 }
2672 }
2673
2674 int save_end = cftell(file);
2675
2676 mprintf(0, "Osiris: Save state, %d bytes written\n", save_end - save_start);
2677
2678 cfseek(file, checksum_pos, SEEK_SET);
2679 cf_WriteInt(file, save_end - save_start); // write out 'checksum'
2680 cfseek(file, save_end, SEEK_SET);
2681 }
2682
2683 // Osiris_RestoreSystemState
2684 // Purpose:
2685 // Restore the state of the system from file (does not restore scripts!)
2686 bool Osiris_RestoreSystemState(CFILE *file) {
2687 int i;
2688 int restore_start = cftell(file);
2689 int num_bytes_to_be_restored;
2690
2691 char tag[256];
2692 cf_ReadString(tag, 256, file);
2693 if (strcmp(tag, "OSIRIS")) {
2694 // Things aren't right...our tag is not here
2695 mprintf(0, "Missing OSIRIS tag\n");
2696 Int3();
2697 return false;
2698 }
2699
2700 uint8_t version = (uint8_t)cf_ReadByte(file);
2701
2702 num_bytes_to_be_restored = cf_ReadInt(file);
2703
2704 Osiris_timer_counter = cf_ReadInt(file);
2705
2706 // restore timer state
2707 for (i = 0; i < MAX_OSIRIS_TIMERS; i++) {
2708 if (cf_ReadByte(file)) {
2709 // timer is used
2710 OsirisTimers[i].flags = cf_ReadShort(file);
2711 OsirisTimers[i].id = cf_ReadInt(file);
2712 OsirisTimers[i].repeat_count = cf_ReadInt(file);
2713 OsirisTimers[i].timer_interval = cf_ReadFloat(file);
2714 OsirisTimers[i].timer_next_signal = cf_ReadFloat(file);
2715 OsirisTimers[i].timer_end = cf_ReadFloat(file);
2716 OsirisTimers[i].objhandle = cf_ReadInt(file);
2717 OsirisTimers[i].objhandle_detonator = cf_ReadInt(file);
2718 OsirisTimers[i].handle = cf_ReadInt(file);
2719
2720 } else {
2721 OsirisTimers[i].flags = 0;
2722 }
2723 }
2724
2725 // restore auto-saved memory chunks
2726 Osiris_RestoreMemoryChunks(file);
2727
2728 // now we need to restore the global state of the DLLs
2729 // byte offset size description
2730 // 0 1 Number of loaded DLLs
2731 // ...
2732 // +1 1 String length of module name
2733 // +2 x Name of the module
2734 // +2+x 4 Size of global data stored
2735 // +6+x y global data
2736 // ...
2737 int loaded_module_count = 0;
2738 for (i = 0; i < MAX_LOADED_MODULES; i++) {
2739 if (OSIRIS_loaded_modules[i].flags & OSIMF_INUSE) {
2740 // this is a loaded module
2741 loaded_module_count++;
2742 }
2743 }
2744
2745 int read_module_count = cf_ReadByte(file);
2746 if (read_module_count != loaded_module_count) {
2747 // the current number of loaded module does not equal the number of modules that were loaded
2748 // when the state was saved. This means that things are not going to be restored exactly for
2749 // sure. We'll skip over those that are not loaded. We're int3 here because I want to know
2750 // when this happens.
2751 mprintf(0,
2752 "OSIRIS: Restoring global state, the number of loaded modules is not the same as the restored count (%d "
2753 "vs. %d)\n",
2754 loaded_module_count, read_module_count);
2755 if (Demo_flags != DF_PLAYBACK) {
2756 Int3();
2757 }
2758 }
2759
2760 // now go through all the read module count DLLs and see if that DLL is currently loaded
2761 for (i = 0; i < read_module_count; i++) {
2762 char read_module_name[_MAX_PATH];
2763 int read_module_namelen;
2764 int read_module_globalsize;
2765 int next_file_pos;
2766 int module_handle;
2767
2768 read_module_namelen = cf_ReadByte(file);
2769 cf_ReadBytes((uint8_t *)read_module_name, read_module_namelen, file);
2770 read_module_name[read_module_namelen] = '\0';
2771
2772 read_module_globalsize = cf_ReadInt(file);
2773 next_file_pos = cftell(file) + read_module_globalsize;
2774
2775 module_handle = Osiris_FindLoadedModule(read_module_name);
2776 if (module_handle == -1) {
2777 mprintf(0, "OSIRIS: The module (%s) was not found while trying to restore the state\n", read_module_name);
2778 if (Demo_flags != DF_PLAYBACK) {
2779 Int3();
2780 }
2781 } else {
2782 OSIRIS_loaded_modules[module_handle].SaveRestoreState(file, 0);
2783 }
2784
2785 cfseek(file, next_file_pos, SEEK_SET); // this ensures that we keep track in the file, even if the
2786 // DLL reads too much/little
2787 }
2788
2789 Osiris_RestoreOMMS(file);
2790
2791 // Go through all the objects and call their EVT_RESTORESTATE (if they have a script)
2792 tOSIRISEventInfo ei;
2793
2794 ei.evt_restorestate.fileptr = (void *)file;
2795
2796 Osiris_CallLevelEvent(EVT_RESTORESTATE, &ei);
2797
2798 for (i = 0; i <= Num_triggers; i++) {
2799 Osiris_CallTriggerEvent(i, EVT_RESTORESTATE, &ei);
2800 }
2801
2802 for (i = 0; i < MAX_OBJECTS; i++) {
2803 if (Objects[i].type != OBJ_NONE && Objects[i].osiris_script) {
2804 Osiris_CallEvent(&Objects[i], EVT_RESTORESTATE, &ei);
2805 }
2806 }
2807
2808 int restore_end = cftell(file);
2809
2810 mprintf(0, "Osiris: Restore state, %d bytes read\n", restore_end - restore_start);
2811
2812 ASSERT(num_bytes_to_be_restored == (restore_end - restore_start));
2813 if (num_bytes_to_be_restored == (restore_end - restore_start))
2814 return true;
2815 else {
2816 if (Demo_flags == DF_PLAYBACK) {
2817 cfseek(file, restore_start + num_bytes_to_be_restored, SEEK_SET);
2818 return true;
2819 }
2820 }
2821
2822 return false;
2823 }
2824
2825 struct tOSIRISMEMNODE {
2826 tOSIRISMEMCHUNK chunk_id;
2827 void *memory;
2828 tOSIRISMEMNODE *next;
2829 };
2830
2831 tOSIRISMEMNODE *Osiris_mem_root;
2832
2833 // Osiris_InitMemoryManager
2834 // Purpose:
2835 // Initializes the memory manager for the scripts, for buffers that the scripts want
2836 // automatically restored/save.
2837 void Osiris_InitMemoryManager(void) {
2838 Osiris_mem_root = NULL;
2839 atexit(Osiris_CloseMemoryManager);
2840 }
2841
2842 // Osiris_CloseMemoryManager
2843 // Purpose:
2844 // Shuts down the Osiris memory manager, freeing any unfreed memory
2845 void Osiris_CloseMemoryManager(void) {
2846 tOSIRISMEMNODE *curr, *next;
2847 curr = Osiris_mem_root;
2848 while (curr) {
2849 next = curr->next;
2850 if (curr->memory)
2851 mem_free(curr->memory);
2852 mem_free(curr);
2853 curr = next;
2854 }
2855 Osiris_mem_root = NULL;
2856 }
2857
2858 // Osiris_AllocateMemory
2859 // Purpose:
2860 // Allocates a chunk of memory to be associated with a script. It will automatically
2861 // save this memory to disk on game save, and will pass the pointer to this memory on EVT_RESTORE
2862 void *Osiris_AllocateMemory(tOSIRISMEMCHUNK *mc) {
2863 // find the end of the list
2864 tOSIRISMEMNODE *curr, **error_node;
2865
2866 if (!Osiris_mem_root) {
2867 // it'll be the first node
2868 Osiris_mem_root = (tOSIRISMEMNODE *)mem_malloc(sizeof(tOSIRISMEMNODE));
2869 if (!Osiris_mem_root)
2870 return NULL;
2871
2872 curr = Osiris_mem_root;
2873 error_node = &Osiris_mem_root;
2874 } else {
2875 // traverse to the tail
2876 curr = Osiris_mem_root;
2877 while (curr->next) {
2878 curr = curr->next;
2879 }
2880
2881 curr->next = (tOSIRISMEMNODE *)mem_malloc(sizeof(tOSIRISMEMNODE));
2882 if (!curr->next)
2883 return NULL;
2884 error_node = &curr->next;
2885 curr = curr->next;
2886 }
2887
2888 // setup the data
2889 curr->next = NULL;
2890 curr->memory = mem_malloc(mc->size);
2891 if (!curr->memory) {
2892 // ack...out of memory
2893 *error_node = NULL; // make sure we cut off the list
2894 mem_free(curr);
2895 return NULL;
2896 }
2897 memcpy(&curr->chunk_id, mc, sizeof(tOSIRISMEMCHUNK));
2898
2899 return curr->memory;
2900 }
2901
2902 // Osiris_FreeMemory
2903 // Purpose:
2904 // Frees a chunk of memory that was allocated by Osiris_AllocateMemory().
2905 void Osiris_FreeMemory(void *mem_ptr) {
2906 tOSIRISMEMNODE *tofree;
2907
2908 if (!Osiris_mem_root)
2909 return;
2910
2911 if (Osiris_mem_root->memory == mem_ptr) {
2912 // free the base pointer
2913 tofree = Osiris_mem_root;
2914 Osiris_mem_root = Osiris_mem_root->next;
2915 } else {
2916 // traverse until we find the node
2917 tOSIRISMEMNODE *curr;
2918 curr = Osiris_mem_root;
2919 bool done = false;
2920 tofree = NULL;
2921 while (!done) {
2922 if (!curr->next) {
2923 done = true; // we didn't find it
2924 } else if (curr->next->memory == mem_ptr) {
2925 // this is the guy to free
2926 tofree = curr->next;
2927 done = true;
2928 } else
2929 curr = curr->next;
2930 }
2931
2932 if (tofree) {
2933 // ok there is a value to free, pull the list back one from curr on
2934 curr->next = tofree->next;
2935 } else {
2936 // nothing to do
2937 return;
2938 }
2939 }
2940
2941 // free the memory associated with tofree
2942 if (tofree->memory)
2943 mem_free(tofree->memory);
2944 mem_free(tofree);
2945 }
2946
2947 bool compareid(tOSIRISSCRIPTID *sid, tOSIRISSCRIPTID *oid) {
2948 if (sid->type == oid->type) {
2949 if (sid->type == LEVEL_SCRIPT)
2950 return true;
2951 if (sid->type == TRIGGER_SCRIPT && sid->triggernum == oid->triggernum)
2952 return true;
2953 if (sid->type == OBJECT_SCRIPT && sid->objhandle == oid->objhandle)
2954 return true;
2955 }
2956 return false;
2957 }
2958
2959 // Osiris_FreeMemoryForScript
2960 // Purpose:
2961 // Frees all memory allocated for a given script
2962 void Osiris_FreeMemoryForScript(tOSIRISSCRIPTID *sid) {
2963 if (!Osiris_mem_root)
2964 return;
2965 bool done = false;
2966 tOSIRISMEMNODE *curr, *next, *prev;
2967 curr = Osiris_mem_root;
2968 prev = NULL;
2969
2970 while (!done) {
2971 if (!curr) {
2972 done = true;
2973 } else {
2974 next = curr->next;
2975
2976 if (compareid(sid, &curr->chunk_id.my_id)) {
2977 // this has to go
2978 if (curr == Osiris_mem_root) {
2979 // removing root
2980 Osiris_mem_root = curr->next;
2981
2982 if (curr->memory)
2983 mem_free(curr->memory);
2984 mem_free(curr);
2985 } else {
2986 // remove from list and pull back
2987 prev->next = curr->next;
2988
2989 if (curr->memory)
2990 mem_free(curr->memory);
2991 mem_free(curr);
2992 }
2993 } else {
2994 prev = curr;
2995 }
2996
2997 curr = next;
2998 }
2999 }
3000 }
3001
3002 // Osiris_SaveMemoryChunks
3003 // Purpose:
3004 // Saves out the 'auto manage' script memory to file
3005 void Osiris_SaveMemoryChunks(CFILE *file) {
3006 tOSIRISMEMNODE *curr;
3007 curr = Osiris_mem_root;
3008
3009 while (curr) {
3010 cf_WriteInt(file, curr->chunk_id.size);
3011 cf_WriteByte(file, curr->chunk_id.my_id.type);
3012 switch (curr->chunk_id.my_id.type) {
3013 case OBJECT_SCRIPT:
3014 cf_WriteInt(file, curr->chunk_id.my_id.objhandle);
3015 break;
3016 case TRIGGER_SCRIPT:
3017 cf_WriteInt(file, curr->chunk_id.my_id.triggernum);
3018 break;
3019 case LEVEL_SCRIPT:
3020 break;
3021 }
3022 cf_WriteInt(file, curr->chunk_id.id);
3023 cf_WriteBytes((uint8_t *)curr->memory, curr->chunk_id.size, file);
3024 curr = curr->next;
3025 }
3026
3027 cf_WriteInt(file, 0);
3028 }
3029
3030 // Osiris_RestoreMemoryChunks
3031 // Purpose:
3032 // Restores the 'auto manage' from file, calls the EVT_MEMRESTORE
3033 void Osiris_RestoreMemoryChunks(CFILE *file) {
3034 tOSIRISMEMNODE *curr;
3035 tOSIRISMEMNODE *memchunk;
3036
3037 // Osiris_CloseMemoryManager(); We might not want to close this down...due to some objects don't get destroyed
3038 // Osiris_mem_root = NULL;
3039 curr = Osiris_mem_root;
3040 if (curr) {
3041 while (curr->next) {
3042 curr = curr->next;
3043 }
3044 }
3045
3046 bool done = false;
3047 while (!done) {
3048 int size = cf_ReadInt(file);
3049 if (size == 0) {
3050 // we're done
3051 done = true;
3052 } else {
3053 // handle this node
3054 memchunk = (tOSIRISMEMNODE *)mem_malloc(sizeof(tOSIRISMEMNODE));
3055 if (!memchunk) {
3056 Error("Out of memory");
3057 }
3058
3059 memchunk->chunk_id.size = size;
3060 memchunk->chunk_id.my_id.type = (script_type)cf_ReadByte(file);
3061 switch (memchunk->chunk_id.my_id.type) {
3062 case OBJECT_SCRIPT:
3063 memchunk->chunk_id.my_id.objhandle = cf_ReadInt(file);
3064 break;
3065 case TRIGGER_SCRIPT:
3066 memchunk->chunk_id.my_id.triggernum = cf_ReadInt(file);
3067 break;
3068 case LEVEL_SCRIPT:
3069 break;
3070 }
3071 memchunk->chunk_id.id = cf_ReadInt(file);
3072 memchunk->memory = mem_malloc(memchunk->chunk_id.size);
3073 if (!memchunk->memory) {
3074 Error("Out of memory");
3075 }
3076 cf_ReadBytes((uint8_t *)memchunk->memory, memchunk->chunk_id.size, file);
3077 memchunk->next = NULL;
3078
3079 // ok, the node is setup, add it to the linked list
3080 if (!Osiris_mem_root) {
3081 Osiris_mem_root = curr = memchunk;
3082 } else {
3083 curr->next = memchunk;
3084 curr = curr->next;
3085 }
3086
3087 tOSIRISEventInfo ei;
3088 ei.evt_memrestore.id = memchunk->chunk_id.id;
3089 ei.evt_memrestore.memory_ptr = memchunk->memory;
3090
3091 // send an event to the object
3092 switch (memchunk->chunk_id.my_id.type) {
3093 case OBJECT_SCRIPT: {
3094 object *obj = ObjGet(memchunk->chunk_id.my_id.objhandle);
3095 if (obj) {
3096 Osiris_CallEvent(obj, EVT_MEMRESTORE, &ei);
3097 }
3098 } break;
3099 case TRIGGER_SCRIPT:
3100 Osiris_CallTriggerEvent(memchunk->chunk_id.my_id.triggernum, EVT_MEMRESTORE, &ei);
3101 break;
3102 case LEVEL_SCRIPT:
3103 Osiris_CallLevelEvent(EVT_MEMRESTORE, &ei);
3104 break;
3105 };
3106 }
3107 }
3108 }
3109
3110 void _extractscript(char *script, char *tempfilename) { cf_CopyFile(tempfilename, script); }
3111
3112 int _getfreeextractslot(void) {
3113 // find a free slot
3114 for (int q = 0; q < MAX_LOADED_MODULES; q++) {
3115 if (!(OSIRIS_Extracted_scripts[q].flags & OESF_USED)) {
3116 return q;
3117 }
3118 }
3119 return -1;
3120 }
3121
3122 void _clearextractedall(void) { Osiris_ClearExtractedScripts(false); }
3123
3124 int Osiris_ExtractScriptsFromHog(int library_handle, bool is_mission_hog) {
3125 if (library_handle == 0)
3126 return 0;
3127
3128 mprintf(0, "OSIRIS: Extracting Scripts From Hog\n");
3129
3130 char filename[_MAX_PATH], temp_filename[_MAX_PATH];
3131 char tempdir[_MAX_PATH], temp_file[_MAX_PATH], temp_fileext[_MAX_EXT];
3132 char temp_realname[_MAX_PATH];
3133
3134 if (!OSIRIS_Extracted_script_dir) {
3135 strcpy(tempdir, Descent3_temp_directory);
3136 OSIRIS_Extracted_script_dir = mem_strdup(tempdir);
3137 if (!OSIRIS_Extracted_script_dir)
3138 Error("Out of memory");
3139 } else {
3140 strcpy(tempdir, OSIRIS_Extracted_script_dir);
3141 }
3142
3143 int count = 0;
3144
3145 const char *script_extension;
3146 #if defined(MACOSX)
3147 script_extension = "*.dylib";
3148 #elif defined(__LINUX__)
3149 script_extension = "*.so";
3150 #elif defined(WIN32)
3151 script_extension = "*.dll";
3152 #else
3153 #error Unsupported platform!
3154 #endif
3155
3156 int index;
3157 index = _getfreeextractslot();
3158 if (index == -1) {
3159 mprintf(0, "OSIRIS: Out of slots extracting scripts!!!!!!!!\n");
3160 Int3();
3161 goto ex_error;
3162 }
3163
3164 mprintf(0, "Search started\n");
3165 if (cf_LibraryFindFirst(library_handle, script_extension, filename)) {
3166
3167 mprintf(0, " Found: %s...", filename);
3168 if (!ddio_GetTempFileName(tempdir, "d3s", temp_filename))
3169 Int3();
3170 else {
3171 ddio_SplitPath(temp_filename, NULL, temp_file, temp_fileext);
3172 strcat(temp_file, temp_fileext);
3173
3174 OSIRIS_Extracted_scripts[index].flags = OESF_USED;
3175 OSIRIS_Extracted_scripts[index].temp_filename = mem_strdup(temp_file);
3176
3177 ddio_SplitPath(filename, NULL, temp_realname, NULL);
3178 OSIRIS_Extracted_scripts[index].real_filename = mem_strdup(temp_realname);
3179
3180 if (is_mission_hog) {
3181 OSIRIS_Extracted_scripts[index].flags |= OESF_MISSION;
3182 }
3183
3184 // extract it out
3185 mprintf(0, "Extracting...");
3186 _extractscript(filename, temp_filename);
3187 mprintf(0, "Done\n");
3188
3189 count++;
3190
3191 while (cf_LibraryFindNext(filename)) {
3192 mprintf(0, " Found: %s...", filename);
3193
3194 index = _getfreeextractslot();
3195 if (index == -1) {
3196 mprintf(0, "OSIRIS: Out of slots extracting scripts!!!!!!!!\n");
3197 Int3();
3198 goto ex_error;
3199 }
3200
3201 // generate temp filename
3202 if (!ddio_GetTempFileName(tempdir, "d3s", temp_filename))
3203 Int3();
3204 else {
3205 ddio_SplitPath(temp_filename, NULL, temp_file, temp_fileext);
3206 strcat(temp_file, temp_fileext);
3207
3208 OSIRIS_Extracted_scripts[index].flags = OESF_USED;
3209 OSIRIS_Extracted_scripts[index].temp_filename = mem_strdup(temp_file);
3210
3211 ddio_SplitPath(filename, NULL, temp_realname, NULL);
3212 OSIRIS_Extracted_scripts[index].real_filename = mem_strdup(temp_realname);
3213
3214 if (is_mission_hog) {
3215 OSIRIS_Extracted_scripts[index].flags |= OESF_MISSION;
3216 }
3217
3218 // extract it out
3219 mprintf(0, "Extracting...");
3220 _extractscript(filename, temp_filename);
3221 mprintf(0, "Done\n");
3222
3223 count++;
3224 }
3225 }
3226 }
3227 }
3228
3229 mprintf(0, "Done Extracting\n");
3230
3231 ex_error:
3232 cf_LibraryFindClose();
3233
3234 static bool atex = false;
3235
3236 if (!atex) {
3237 atexit(_clearextractedall);
3238 atex = true;
3239 }
3240
3241 return count;
3242 }
3243
3244 void Osiris_ClearExtractedScripts(bool mission_only) {
3245 mprintf(0, "OSIRIS: Removing Extracted DLLs\n");
3246
3247 char fullpath[_MAX_PATH];
3248 if (!OSIRIS_Extracted_script_dir) {
3249 return;
3250 }
3251
3252 for (int i = 0; i < MAX_LOADED_MODULES; i++) {
3253 if (OSIRIS_Extracted_scripts[i].flags & OESF_USED) {
3254 if (mission_only && (!(OSIRIS_Extracted_scripts[i].flags & OESF_MISSION)))
3255 continue;
3256
3257 ASSERT(OSIRIS_Extracted_scripts[i].temp_filename);
3258 ASSERT(OSIRIS_Extracted_scripts[i].real_filename);
3259 if (!(OSIRIS_Extracted_scripts[i].temp_filename && OSIRIS_Extracted_scripts[i].real_filename))
3260 continue;
3261
3262 ddio_MakePath(fullpath, OSIRIS_Extracted_script_dir, OSIRIS_Extracted_scripts[i].temp_filename, NULL);
3263 ddio_DeleteFile(fullpath);
3264
3265 mem_free(OSIRIS_Extracted_scripts[i].temp_filename);
3266 mem_free(OSIRIS_Extracted_scripts[i].real_filename);
3267 OSIRIS_Extracted_scripts[i].temp_filename = NULL;
3268 OSIRIS_Extracted_scripts[i].real_filename = NULL;
3269 OSIRIS_Extracted_scripts[i].flags &= ~OESF_USED;
3270 }
3271 }
3272
3273 if (!mission_only) {
3274 mem_free(OSIRIS_Extracted_script_dir);
3275 OSIRIS_Extracted_script_dir = NULL;
3276 }
3277 }
3278
3279 /*
3280 ******************************************************************************
3281 Osiris Mission Memory System:
3282 ----------------------------
3283 OMMS is a way to allocate memory that can be shared between scripts and/or modules. This
3284 memory can also last through level changes. The basic process of using this system is someone
3285 calls the OMMS_Malloc() to allocate a chunk of memory that is to be shared/global. This returns
3286 a handle which is to be used by OMMS_Attach(), to get the pointer to the memory, and OMMS_Detach(),
3287 which informs Osiris that you're no longer using the pointer OMMS_Attach() returned. OMMS_Detach()
3288 will NOT free the memory, only OMMS_Free() does that, and it only does that when the reference
3289 count for the memory is at 0 (OMMS_Attach() increments the reference count, OMMS_Detach() decrements
3290 the reference count). Basically, just surround the code that uses the global memory with a call
3291 to OMMS_Attach() and OMMS_Detach(). ALWAYS make sure that you detach before you leave the event.
3292
3293 // Allocates a block of global memory for this module, of size amount_of_memory.
3294 // unique_identfier is the script provided unique ID which is used throughout.
3295 // script_identifier is the pointer of data provided to the script in it's InitializeDLL function (really the name of
3296 the script)
3297 // Returns -1 if there isn't enough available memory
3298 // Returns -2 if the unique identifier passed in is already used, but the requested amount_of_memory is different
3299 // If the memory has already been allocated, it will return the handle.
3300 OMMSHANDLE OMMS_Malloc(size_t amount_of_memory,uint32_t unique_identifier,char *script_identifier);
3301
3302 // Attaches to a block of global OMMS memory. As long as at least one module (or script) is
3303 // attached to a module, the memory will not be deleted. (Increments the reference count)
3304 // Returns NULL if the memory couldn't be attached (it has been either free'd or never malloced)
3305 void *OMMS_Attach(OMMSHANDLE handle);
3306
3307 // Detaches a block of global OMMS memory. (Reduces the reference count).
3308 void OMMS_Detach(OMMSHANDLE handle);
3309
3310 // Frees a block of global memory
3311 // Only has affect if you are attached to the memory. Memory will _ONLY_ be deleted when the
3312 // following conditions are meant for the shared memory block:
3313 // 1) The reference count for the global memory is at 0 (OMMS_Attach() adds to reference count, OMMS_Detach()
3314 subtracts).
3315 // 2) OMMS_Free() has been called for the block of global memory.
3316 // The conditions can happen in any order, but as soon as both are satisfied, the memory
3317 // becomes deleted and any pointer returned by OMMS_Attach() becomes invalid.
3318 //
3319 // handle : the value returned by OMMS_Malloc()
3320 void OMMS_Free(OMMSHANDLE handle);
3321
3322 // Returns an OMMSHANDLE to a block of global memory allocated by a module/script. Pass
3323 // in the unique_identifier and the script_identifier that was passed in the OMMS_Malloc().
3324 // Note: script_identifier is really the filename of the module that called the OMMS_Malloc().
3325 // Returns -1 if the module was never OMMS_Malloc()'d.
3326 OMMSHANDLE OMMS_Find(uint32_t unique_identifier,char *script_identifier);
3327
3328 // Returns information about the OMMS memory given it's handle returned from the OMMS_Find() or
3329 // OMMS_Malloc(). Returns 0 if the handle was invalid, 1 if the information has been filled in;
3330 // Pass NULL in for those parameters you don't need information about.
3331 char OMMS_GetInfo(OMMSHANDLE handle,uint32_t *mem_size,uint32_t *uid,uint16_t *reference_count,uint8_t *has_free_been_called);
3332
3333
3334 ******************************************************************************
3335 */
3336
3337 struct tOMMSNode {
3338 uint16_t id;
3339 uint32_t size_of_memory;
3340 uint32_t unique_id;
3341 uint16_t reference_count;
3342 uint8_t free_called;
3343 void *memory_ptr;
3344 tOMMSNode *next;
3345 };
3346
3347 struct tOMMSHashNode {
3348 char *script_name;
3349 uint16_t base_id;
3350 tOMMSNode *root;
3351 tOMMSHashNode *next;
3352 };
3353
3354 tOMMSHashNode *OMMS_Hash_node_root = NULL;
3355 uint16_t OMMS_Current_base_id = 0;
3356 uint16_t OMMS_Current_id = 0;
3357
3358 // Searches through the hash nodes and looks for the one associated with
3359 // the script name, if one doesn't exist it will create one (if autocreate is true).
3360 tOMMSHashNode *Osiris_OMMS_FindHashNode(char *script_name, bool autocreate);
3361 // frees all memory associated with the OMMSHashNode given (includes all script
3362 // memory...returns the next node in the list, NULL if none
3363 tOMMSHashNode *Osiris_OMMS_DeleteHashNode(tOMMSHashNode *node);
3364 // finds an OMMS node, given the hash node to start at. If it isn't
3365 // found than one is created. NULL if out of memory.
3366 tOMMSNode *Osiris_OMMS_FindNode(tOMMSHashNode *root, uint32_t uid, bool autocreate);
3367 // Removes the OMMS node for the given HashNode (completly remove)
3368 void Osiris_OMMS_RemoveNode(tOMMSHashNode *root, uint32_t uid);
3369 // Reduces the reference count for an OMMSNode by 1
3370 void Osiris_OMMS_ReduceRefCount(tOMMSHashNode *root, tOMMSNode *node);
3371 // Calls free on a node
3372 void Osiris_OMMS_CallFreeForNode(tOMMSHashNode *root, tOMMSNode *node);
3373 // Searches for the given OMMSHANDLE, returns NULL if not found. if hash is
3374 // given it will return the hash root that the node was found in.
3375 tOMMSNode *Osiris_OMMS_FindHandle(OMMSHANDLE handle, tOMMSHashNode **hash = NULL);
3376
3377 // Allocates a block of global memory for this module, of size amount_of_memory.
3378 // unique_identfier is the script provided unique ID which is used throughout.
3379 // script_identifier is the pointer of data provided to the script in it's InitializeDLL function (really the name of
3380 // the script) Returns -1 if there isn't enough available memory Returns -2 if the unique identifier passed in is
3381 // already used, but the requested amount_of_memory is different Returns -3 if the unique identifier passed in is
3382 // already used, same size requested
3383 static OMMSHANDLE Osiris_OMMS_Malloc(size_t amount_of_memory, uint32_t unique_identifier, char *script_identifier);
3384
3385 // Attaches to a block of global OMMS memory. As long as at least one module (or script) is
3386 // attached to a module, the memory will not be deleted. (Increments the reference count)
3387 // Returns NULL if the memory couldn't be attached (it has been either free'd or never malloced)
3388 static void *Osiris_OMMS_Attach(OMMSHANDLE handle);
3389
3390 // Detaches a block of global OMMS memory. (Reduces the reference count).
3391 static void Osiris_OMMS_Detach(OMMSHANDLE handle);
3392
3393 // Frees a block of global memory
3394 // Only has affect if you are attached to the memory. Memory will _ONLY_ be deleted when the
3395 // following conditions are meant for the shared memory block:
3396 // 1) The reference count for the global memory is at 0 (OMMS_Attach() adds to reference count, OMMS_Detach()
3397 // subtracts). 2) OMMS_Free() has been called for the block of global memory. The conditions can happen in any order,
3398 // but
3399 // as soon as both are satisfied, the memory becomes deleted and any pointer returned by OMMS_Attach() becomes
3400 // invalid.
3401 //
3402 // handle : the value returned by OMMS_Malloc()
3403 static void Osiris_OMMS_Free(OMMSHANDLE handle);
3404
3405 // Returns an OMMSHANDLE to a block of global memory allocated by a module/script. Pass
3406 // in the unique_identifier and the script_identifier that was passed in the OMMS_Malloc().
3407 // Note: script_identifier is really the filename of the module that called the OMMS_Malloc().
3408 // Returns -1 if the module was never OMMS_Malloc()'d.
3409 static OMMSHANDLE Osiris_OMMS_Find(uint32_t unique_identifier, char *script_identifier);
3410
3411 // Returns information about the OMMS memory given it's handle returned from the OMMS_Find() or
3412 // OMMS_Malloc(). Returns 0 if the handle was invalid, 1 if the information has been filled in;
3413 // Pass NULL in for those parameters you don't need information about.
3414 static char Osiris_OMMS_GetInfo(OMMSHANDLE handle, uint32_t *mem_size, uint32_t *uid, uint16_t *reference_count,
3415 uint8_t *has_free_been_called);
3416
3417 void Osiris_InitOMMS(void) {
3418 OMMS_Current_base_id = 0;
3419 OMMS_Current_id = 0;
3420 OMMS_Hash_node_root = NULL;
3421 atexit(Osiris_CloseOMMS);
3422 }
3423
3424 void Osiris_CloseOMMS(void) {
3425 mprintf(0, "OSIRIS: Reseting OMMS memory\n");
3426
3427 tOMMSHashNode *curr = OMMS_Hash_node_root;
3428
3429 while (curr) {
3430 curr = Osiris_OMMS_DeleteHashNode(curr);
3431 }
3432
3433 OMMS_Hash_node_root = NULL;
3434 }
3435
3436 void Osiris_SaveOMMS(CFILE *file) {
3437 // save out our current OMMS handle position
3438 cf_WriteShort(file, OMMS_Current_base_id);
3439 cf_WriteShort(file, OMMS_Current_id);
3440
3441 // go through all the hash nodes write their information out
3442 tOMMSHashNode *currhash = OMMS_Hash_node_root;
3443 while (currhash) {
3444 // write out a 1, saying that we have a hash node here
3445 cf_WriteByte(file, 1);
3446
3447 cf_WriteShort(file, currhash->base_id);
3448
3449 // write out the info about this hash node
3450 int length;
3451 length = (currhash->script_name) ? strlen(currhash->script_name) : 0;
3452 cf_WriteByte(file, length);
3453 if (length)
3454 cf_WriteBytes((uint8_t *)currhash->script_name, length, file);
3455
3456 // now go through all the nodes and write their data
3457 tOMMSNode *node;
3458 node = currhash->root;
3459 while (node) {
3460 // write out 1, for valid hash
3461 cf_WriteByte(file, 1);
3462 cf_WriteShort(file, node->id);
3463
3464 // write out all the node data
3465 cf_WriteByte(file, node->free_called);
3466 cf_WriteShort(file, node->reference_count);
3467 cf_WriteInt(file, node->unique_id);
3468 cf_WriteInt(file, node->size_of_memory);
3469 if (node->size_of_memory)
3470 cf_WriteBytes((uint8_t *)node->memory_ptr, node->size_of_memory, file);
3471
3472 node = node->next;
3473 }
3474 // write out terminating 0
3475 cf_WriteByte(file, 0);
3476
3477 // go to the next hash node
3478 currhash = currhash->next;
3479 }
3480
3481 // write out terminating 0
3482 cf_WriteByte(file, 0);
3483 }
3484
3485 void Osiris_RestoreOMMS(CFILE *file) {
3486 ASSERT(OMMS_Hash_node_root == NULL);
3487
3488 OMMS_Current_base_id = (uint16_t)cf_ReadShort(file);
3489 OMMS_Current_id = (uint16_t)cf_ReadShort(file);
3490
3491 tOMMSHashNode *currhash;
3492 tOMMSNode *node;
3493
3494 currhash = NULL;
3495
3496 // we have to rebuild the nodes
3497 while (cf_ReadByte(file)) {
3498 if (!currhash) {
3499 currhash = OMMS_Hash_node_root = (tOMMSHashNode *)mem_malloc(sizeof(tOMMSHashNode));
3500 } else {
3501 currhash->next = (tOMMSHashNode *)mem_malloc(sizeof(tOMMSHashNode));
3502 currhash = currhash->next;
3503 }
3504
3505 if (!currhash)
3506 Error("Out of memory");
3507
3508 currhash->next = NULL;
3509 currhash->root = NULL;
3510 currhash->script_name = NULL;
3511
3512 currhash->base_id = (uint16_t)cf_ReadShort(file);
3513
3514 // read length of string
3515 int length = cf_ReadByte(file);
3516 if (length) {
3517 currhash->script_name = (char *)mem_malloc(length + 1);
3518 if (!currhash->script_name)
3519 Error("Out of Memory");
3520 else
3521 cf_ReadBytes((uint8_t *)currhash->script_name, length, file);
3522 }
3523
3524 node = NULL;
3525
3526 // now go through all the nodes and right their data
3527 while (cf_ReadByte(file)) {
3528 if (!node) {
3529 node = currhash->root = (tOMMSNode *)mem_malloc(sizeof(tOMMSNode));
3530 } else {
3531 node->next = (tOMMSNode *)mem_malloc(sizeof(tOMMSNode));
3532 node = node->next;
3533 }
3534
3535 if (!node)
3536 Error("Out of memory");
3537
3538 node->memory_ptr = NULL;
3539 node->next = NULL;
3540
3541 node->id = (uint16_t)cf_ReadShort(file);
3542
3543 node->free_called = (cf_ReadByte(file)) ? true : false;
3544 node->reference_count = (uint16_t)cf_ReadShort(file);
3545 node->unique_id = cf_ReadInt(file);
3546 node->size_of_memory = cf_ReadInt(file);
3547 if (node->size_of_memory) {
3548 node->memory_ptr = mem_malloc(node->size_of_memory);
3549 if (!node->memory_ptr)
3550 Error("Out of memory");
3551
3552 cf_ReadBytes((uint8_t *)node->memory_ptr, node->size_of_memory, file);
3553 }
3554 } // end reading nodes
3555 } // end reading hash nodes
3556 }
3557
3558 // Searches through the hash nodes and looks for the one associated with
3559 // the script name, if one doesn't exist it will create one (if autocreate is true).
3560 tOMMSHashNode *Osiris_OMMS_FindHashNode(char *script_name, bool autocreate) {
3561 tOMMSHashNode *curr = OMMS_Hash_node_root;
3562
3563 if (!OMMS_Hash_node_root) {
3564 // allocate the root node
3565 if (!autocreate)
3566 return NULL;
3567
3568 curr = OMMS_Hash_node_root = (tOMMSHashNode *)mem_malloc(sizeof(tOMMSHashNode));
3569 } else {
3570 if (curr->script_name && !stricmp(curr->script_name, script_name)) {
3571 // the root node matches
3572 return curr;
3573 }
3574
3575 // search through to see if we can find the node
3576 while (curr->next) {
3577 if (curr->next->script_name && !stricmp(curr->next->script_name, script_name)) {
3578 // curr->next is a matching node
3579 return curr->next;
3580 }
3581
3582 curr = curr->next;
3583 }
3584
3585 // allocate a node and tack it on the end
3586 if (!autocreate)
3587 return NULL;
3588
3589 curr->next = (tOMMSHashNode *)mem_malloc(sizeof(tOMMSHashNode));
3590 curr = curr->next;
3591 }
3592
3593 // if we get here then curr is a freshly allocated node
3594 curr->next = NULL;
3595 curr->root = NULL;
3596 curr->script_name = mem_strdup(script_name);
3597 curr->base_id = ++OMMS_Current_base_id;
3598
3599 return curr;
3600 }
3601
3602 // frees all memory associated with the OMMSHashNode given (includes all script
3603 // memory...returns the next node in the list, NULL if none
3604 tOMMSHashNode *Osiris_OMMS_DeleteHashNode(tOMMSHashNode *node) {
3605 if (!node)
3606 return NULL;
3607 tOMMSHashNode *ret = node->next;
3608
3609 if (node->script_name)
3610 mem_free(node->script_name);
3611
3612 tOMMSNode *curr, *next;
3613 curr = next = node->root;
3614
3615 while (curr) {
3616 next = curr->next;
3617 mem_free(curr->memory_ptr);
3618 mem_free(curr);
3619 curr = next;
3620 }
3621
3622 mem_free(node);
3623
3624 return ret;
3625 }
3626
3627 // finds an OMMS node, given the hash node to start at. If it isn't
3628 // found than one is created. NULL if out of memory.
3629 tOMMSNode *Osiris_OMMS_FindNode(tOMMSHashNode *root, uint32_t uid, bool autocreate) {
3630 tOMMSNode *curr = root->root;
3631
3632 if (!root->root) {
3633 // allocate the root node
3634 if (!autocreate)
3635 return NULL;
3636
3637 curr = root->root = (tOMMSNode *)mem_malloc(sizeof(tOMMSNode));
3638 } else {
3639 if (curr->unique_id == uid) {
3640 // the root node matches
3641 return curr;
3642 }
3643
3644 // search through to see if we can find the node
3645 while (curr->next) {
3646 if (curr->next->unique_id == uid) {
3647 // curr->next is a matching node
3648 return curr->next;
3649 }
3650
3651 curr = curr->next;
3652 }
3653
3654 // allocate a node and tack it on the end
3655 if (!autocreate)
3656 return NULL;
3657
3658 curr->next = (tOMMSNode *)mem_malloc(sizeof(tOMMSNode));
3659 curr = curr->next;
3660 }
3661
3662 // if we get here then curr is a freshly allocated node
3663 curr->free_called = 0;
3664 curr->memory_ptr = NULL;
3665 curr->next = NULL;
3666 curr->reference_count = 0;
3667 curr->size_of_memory = 0;
3668 curr->unique_id = uid;
3669 curr->id = ++OMMS_Current_id;
3670
3671 return curr;
3672 }
3673
3674 // Removes the OMMS node for the given HashNode (completly remove)
3675 void Osiris_OMMS_RemoveNode(tOMMSHashNode *root, uint32_t uid) {
3676 tOMMSNode *curr = root->root;
3677 tOMMSNode *node_to_free = NULL;
3678
3679 if (!root->root)
3680 return;
3681
3682 if (root->root->unique_id == uid) {
3683 // the root node matches
3684 node_to_free = root->root;
3685 root->root = NULL;
3686 goto free_mem;
3687 }
3688
3689 // search through to see if we can find the node
3690 while (curr->next) {
3691 if (curr->next->unique_id == uid) {
3692 // curr->next is a matching node
3693 node_to_free = curr->next;
3694 curr->next = curr->next->next;
3695 goto free_mem;
3696 }
3697 curr = curr->next;
3698 }
3699
3700 free_mem:
3701 if (!node_to_free)
3702 return;
3703
3704 mprintf(0, "OMMS: deleting uid 0x%x\n", node_to_free->unique_id);
3705 if (node_to_free->memory_ptr)
3706 mem_free(node_to_free->memory_ptr);
3707 mem_free(node_to_free);
3708 }
3709
3710 // Reduces the reference count for an OMMSNode by 1
3711 void Osiris_OMMS_ReduceRefCount(tOMMSHashNode *root, tOMMSNode *node) {
3712 if (!node)
3713 return;
3714
3715 node->reference_count--;
3716
3717 if (node->reference_count <= 0 && node->free_called) {
3718 // free the node
3719 Osiris_OMMS_RemoveNode(root, node->unique_id);
3720 }
3721 }
3722
3723 // Calls free on a node
3724 void Osiris_OMMS_CallFreeForNode(tOMMSHashNode *root, tOMMSNode *node) {
3725 if (!node)
3726 return;
3727
3728 node->free_called = 1;
3729
3730 if (node->reference_count <= 0 && node->free_called) {
3731 // free the node
3732 Osiris_OMMS_RemoveNode(root, node->unique_id);
3733 }
3734 }
3735
3736 // Searches for the given OMMSHANDLE, returns NULL if not found. if hash is
3737 // given it will return the hash root that the node was found in.
3738 tOMMSNode *Osiris_OMMS_FindHandle(OMMSHANDLE handle, tOMMSHashNode **hash) {
3739 tOMMSHashNode *hashcurr = OMMS_Hash_node_root;
3740 tOMMSNode *nodecurr;
3741 uint16_t base_id;
3742 uint16_t id;
3743 base_id = ((handle & 0xFFFF0000) >> 16);
3744 id = (handle & 0x0000FFFF);
3745
3746 while (hashcurr) {
3747 if (hashcurr->base_id == base_id) {
3748
3749 nodecurr = hashcurr->root;
3750 while (nodecurr) {
3751 if (nodecurr->id == id) {
3752 if (hash)
3753 *hash = hashcurr;
3754 return nodecurr;
3755 }
3756
3757 nodecurr = nodecurr->next;
3758 }
3759 }
3760
3761 hashcurr = hashcurr->next;
3762 }
3763
3764 return NULL;
3765 }
3766
3767 // Allocates a block of global memory for this module, of size amount_of_memory.
3768 // unique_identfier is the script provided unique ID which is used throughout.
3769 // script_identifier is the pointer of data provided to the script in it's InitializeDLL function (really the name of
3770 // the script) Returns -1 if there isn't enough available memory Returns -2 if the unique identifier passed in is
3771 // already used, but the requested amount_of_memory is different If the memory has already been allocated, it will
3772 // return the handle.
3773 OMMSHANDLE Osiris_OMMS_Malloc(size_t amount_of_memory, uint32_t unique_identifier, char *script_identifier) {
3774 ASSERT(amount_of_memory > 0);
3775 if (amount_of_memory <= 0)
3776 return -1;
3777
3778 // find the correct hash node
3779 tOMMSHashNode *hash = Osiris_OMMS_FindHashNode(script_identifier, true);
3780 if (!hash)
3781 return -1;
3782
3783 tOMMSNode *node = Osiris_OMMS_FindNode(hash, unique_identifier, true);
3784 if (!node)
3785 return -1;
3786
3787 if (node->memory_ptr) {
3788 // the memory already has been allocated
3789 if (node->size_of_memory == amount_of_memory)
3790 return ((hash->base_id << 16) | (node->id));
3791
3792 // the size's requested don't match
3793 return -2;
3794 }
3795
3796 // we need to allocate the memory
3797 node->memory_ptr = mem_malloc(amount_of_memory);
3798 if (!node->memory_ptr)
3799 return -1; // out of memory
3800
3801 node->size_of_memory = amount_of_memory;
3802 node->unique_id = unique_identifier;
3803
3804 mprintf(0, "OMMS: malloc handle (0x%x%x) size = %d\n", hash->base_id, node->id, node->size_of_memory);
3805 return ((hash->base_id << 16) | (node->id));
3806 }
3807
3808 // Attaches to a block of global OMMS memory. As long as at least one module (or script) is
3809 // attached to a module, the memory will not be deleted. (Increments the reference count)
3810 // Returns NULL if the memory couldn't be attached (it has been either free'd or never malloced)
3811 void *Osiris_OMMS_Attach(OMMSHANDLE handle) {
3812 tOMMSNode *node = Osiris_OMMS_FindHandle(handle);
3813 if (!node)
3814 return NULL;
3815
3816 if (node->memory_ptr) {
3817 node->reference_count++;
3818 }
3819 return node->memory_ptr;
3820 }
3821
3822 // Detaches a block of global OMMS memory. (Reduces the reference count).
3823 void Osiris_OMMS_Detach(OMMSHANDLE handle) {
3824 tOMMSHashNode *hash;
3825 tOMMSNode *node = Osiris_OMMS_FindHandle(handle, &hash);
3826 if (!node)
3827 return;
3828
3829 Osiris_OMMS_ReduceRefCount(hash, node);
3830 }
3831
3832 // Frees a block of global memory
3833 // Only has affect if you are attached to the memory. Memory will _ONLY_ be deleted when the
3834 // following conditions are meant for the shared memory block:
3835 // 1) The reference count for the global memory is at 0 (OMMS_Attach() adds to reference count, OMMS_Detach()
3836 // subtracts). 2) OMMS_Free() has been called for the block of global memory. The conditions can happen in any order,
3837 // but
3838 // as soon as both are satisfied, the memory becomes deleted and any pointer returned by OMMS_Attach() becomes
3839 // invalid.
3840 //
3841 // handle : the value returned by OMMS_Malloc()
3842 void Osiris_OMMS_Free(OMMSHANDLE handle) {
3843 tOMMSHashNode *hash;
3844 tOMMSNode *node = Osiris_OMMS_FindHandle(handle, &hash);
3845 if (!node)
3846 return;
3847
3848 Osiris_OMMS_CallFreeForNode(hash, node);
3849 }
3850
3851 // Returns an OMMSHANDLE to a block of global memory allocated by a module/script. Pass
3852 // in the unique_identifier and the script_identifier that was passed in the OMMS_Malloc().
3853 // Note: script_identifier is really the filename of the module that called the OMMS_Malloc().
3854 // Returns -1 if the module was never OMMS_Malloc()'d.
3855 OMMSHANDLE Osiris_OMMS_Find(uint32_t unique_identifier, char *script_identifier) {
3856 tOMMSHashNode *hash = Osiris_OMMS_FindHashNode(script_identifier, false);
3857 if (!hash)
3858 return -1;
3859
3860 tOMMSNode *node = Osiris_OMMS_FindNode(hash, unique_identifier, false);
3861 if (!node)
3862 return -1;
3863 if (!node->memory_ptr)
3864 return -1;
3865
3866 return ((hash->base_id << 16) | (node->id));
3867 }
3868
3869 // Returns information about the OMMS memory given it's handle returned from the OMMS_Find() or
3870 // OMMS_Malloc(). Returns 0 if the handle was invalid, 1 if the information has been filled in;
3871 // Pass NULL in for those parameters you don't need information about.
3872 char Osiris_OMMS_GetInfo(OMMSHANDLE handle, uint32_t *mem_size, uint32_t *uid, uint16_t *reference_count,
3873 uint8_t *has_free_been_called) {
3874 if (mem_size)
3875 *mem_size = 0;
3876 if (uid)
3877 *uid = 0;
3878 if (reference_count)
3879 *reference_count = 0;
3880 if (has_free_been_called)
3881 *has_free_been_called = 0;
3882
3883 tOMMSHashNode *hash;
3884 tOMMSNode *node = Osiris_OMMS_FindHandle(handle, &hash);
3885 if (!node)
3886 return 0;
3887
3888 if (mem_size)
3889 *mem_size = node->size_of_memory;
3890 if (uid)
3891 *uid = node->unique_id;
3892 if (reference_count)
3893 *reference_count = node->reference_count;
3894 if (has_free_been_called)
3895 *has_free_been_called = node->free_called;
3896
3897 return 1;
3898 }
3899
3900 //*****************************************************************************
3901 // Osiris_CreateModuleInitStruct
3902 // Purpose:
3903 // This function initializes a Module Init Struct with all the needed data to get sent
3904 // to the module during initialization.
3905 void Osiris_CreateModuleInitStruct(tOSIRISModuleInit *mi) {
3906 int i = 0;
3907
3908 // fill in function pointers here
3909 mi->fp[i++] = (int *)MonoPrintf;
3910 mi->fp[i++] = (int *)msafe_CallFunction;
3911 mi->fp[i++] = (int *)msafe_GetValue;
3912 mi->fp[i++] = (int *)osipf_CallObjectEvent;
3913 mi->fp[i++] = (int *)osipf_CallTriggerEvent;
3914 mi->fp[i++] = (int *)osipf_SoundTouch;
3915 mi->fp[i++] = (int *)osipf_ObjectFindID;
3916 mi->fp[i++] = (int *)osipf_WeaponFindID;
3917 mi->fp[i++] = (int *)osipf_ObjectGetTimeLived;
3918 mi->fp[i++] = (int *)osipf_GetGunPos;
3919 mi->fp[i++] = (int *)osipf_RoomValue;
3920 mi->fp[i++] = (int *)osipf_IsRoomValid;
3921 mi->fp[i++] = (int *)osipf_GetAttachParent;
3922 mi->fp[i++] = (int *)osipf_GetNumAttachSlots;
3923 mi->fp[i++] = (int *)osipf_GetAttachChildHandle;
3924 mi->fp[i++] = (int *)osipf_AttachObjectAP;
3925 mi->fp[i++] = (int *)osipf_AttachObjectRad;
3926 mi->fp[i++] = (int *)osipf_UnattachFromParent;
3927 mi->fp[i++] = (int *)osipf_UnattachChild;
3928 mi->fp[i++] = (int *)osipf_UnattachChildren;
3929 mi->fp[i++] = (int *)osipf_RayCast;
3930 mi->fp[i++] = (int *)osipf_AIGetPathID;
3931 mi->fp[i++] = (int *)osipf_AIGoalFollowPathSimple;
3932 mi->fp[i++] = (int *)osipf_AIPowerSwitch;
3933 mi->fp[i++] = (int *)osipf_AITurnTowardsVectors;
3934 mi->fp[i++] = (int *)osipf_AISetType;
3935 mi->fp[i++] = (int *)osipf_AIFindHidePos;
3936 mi->fp[i++] = (int *)osipf_AIGoalAddEnabler;
3937 mi->fp[i++] = (int *)osipf_AIGoalAdd;
3938 mi->fp[i++] = (int *)osipf_AIGoalClear;
3939 mi->fp[i++] = (int *)osipf_AIValue;
3940 mi->fp[i++] = (int *)osipf_AIFindObjOfType;
3941 mi->fp[i++] = (int *)osipf_AIGetRoomPathPoint;
3942 mi->fp[i++] = (int *)osipf_AIFindEnergyCenter;
3943 mi->fp[i++] = (int *)osipf_AIGetDistToObj;
3944 mi->fp[i++] = (int *)osipf_AISetGoalFlags;
3945 mi->fp[i++] = (int *)osipf_AISetGoalCircleDist;
3946 mi->fp[i++] = (int *)osipf_CFReadBytes;
3947 mi->fp[i++] = (int *)osipf_CFReadInt;
3948 mi->fp[i++] = (int *)osipf_CFReadShort;
3949 mi->fp[i++] = (int *)osipf_CFReadByte;
3950 mi->fp[i++] = (int *)osipf_CFReadFloat;
3951 mi->fp[i++] = (int *)osipf_CFReadDouble;
3952 mi->fp[i++] = (int *)osipf_CFReadString;
3953 mi->fp[i++] = (int *)osipf_CFWriteBytes;
3954 mi->fp[i++] = (int *)osipf_CFWriteString;
3955 mi->fp[i++] = (int *)osipf_CFWriteInt;
3956 mi->fp[i++] = (int *)osipf_CFWriteShort;
3957 mi->fp[i++] = (int *)osipf_CFWriteByte;
3958 mi->fp[i++] = (int *)osipf_CFWriteFloat;
3959 mi->fp[i++] = (int *)osipf_CFWriteDouble;
3960 mi->fp[i++] = (int *)Osiris_AllocateMemory;
3961 mi->fp[i++] = (int *)Osiris_FreeMemory;
3962 mi->fp[i++] = (int *)Osiris_CancelTimer;
3963 mi->fp[i++] = (int *)Osiris_CreateTimer;
3964 mi->fp[i++] = (int *)msafe_DoPowerup;
3965 mi->fp[i++] = (int *)osipf_ObjCreate;
3966 mi->fp[i++] = (int *)osipf_GameTime;
3967 mi->fp[i++] = (int *)osipf_FrameTime;
3968 mi->fp[i++] = (int *)osipf_ObjWBValue;
3969 mi->fp[i++] = (int *)Osiris_TimerExists;
3970 mi->fp[i++] = (int *)osipf_ObjectValue;
3971 mi->fp[i++] = (int *)osipf_MatcenValue;
3972 mi->fp[i++] = (int *)osipf_MatcenReset;
3973 mi->fp[i++] = (int *)osipf_MatcenCopy;
3974 mi->fp[i++] = (int *)osipf_MatcenCreate;
3975 mi->fp[i++] = (int *)osipf_MatcenFindId;
3976 mi->fp[i++] = (int *)osipf_MissionFlagSet;
3977 mi->fp[i++] = (int *)osipf_MissionFlagGet;
3978 mi->fp[i++] = (int *)osipf_PlayerValue;
3979 mi->fp[i++] = (int *)osipf_ObjectCustomAnim;
3980 mi->fp[i++] = (int *)osipf_PlayerAddHudMessage;
3981 mi->fp[i++] = (int *)osipf_ObjGhost;
3982 mi->fp[i++] = (int *)osipf_ObjBurning;
3983 mi->fp[i++] = (int *)osipf_ObjIsEffect;
3984 mi->fp[i++] = (int *)osipf_CFopen;
3985 mi->fp[i++] = (int *)osipf_CFclose;
3986 mi->fp[i++] = (int *)osipf_CFtell;
3987 mi->fp[i++] = (int *)osipf_CFeof;
3988 mi->fp[i++] = (int *)osipf_SoundStop;
3989 mi->fp[i++] = (int *)osipf_SoundPlay2d;
3990 mi->fp[i++] = (int *)osipf_SoundPlay3d;
3991 mi->fp[i++] = (int *)osipf_SoundFindId;
3992 mi->fp[i++] = (int *)osipf_AIIsObjFriend;
3993 mi->fp[i++] = (int *)osipf_AIIsObjEnemy;
3994 mi->fp[i++] = (int *)osipf_AIGoalValue;
3995 mi->fp[i++] = (int *)osipf_AIGetNearbyObjs;
3996 mi->fp[i++] = (int *)osipf_AIGetCurGoalIndex;
3997 mi->fp[i++] = (int *)Osiris_OMMS_Malloc;
3998 mi->fp[i++] = (int *)Osiris_OMMS_Attach;
3999 mi->fp[i++] = (int *)Osiris_OMMS_Detach;
4000 mi->fp[i++] = (int *)Osiris_OMMS_Free;
4001 mi->fp[i++] = (int *)Osiris_OMMS_Find;
4002 mi->fp[i++] = (int *)Osiris_OMMS_GetInfo;
4003 mi->fp[i++] = (int *)Cinematic_Start;
4004 mi->fp[i++] = (int *)Cinematic_Stop;
4005 mi->fp[i++] = (int *)osipf_FindSoundName;
4006 mi->fp[i++] = (int *)osipf_FindRoomName;
4007 mi->fp[i++] = (int *)osipf_FindTriggerName;
4008 mi->fp[i++] = (int *)osipf_FindObjectName;
4009 mi->fp[i++] = (int *)osipf_GetTriggerRoom;
4010 mi->fp[i++] = (int *)osipf_GetTriggerFace;
4011 mi->fp[i++] = (int *)osipf_FindDoorName;
4012 mi->fp[i++] = (int *)osipf_FindTextureName;
4013 mi->fp[i++] = (int *)osipf_CreateRandomSparks;
4014 mi->fp[i++] = (int *)Osiris_CancelTimerID;
4015 mi->fp[i++] = (int *)osipf_GetGroundPos;
4016 mi->fp[i++] = (int *)osipf_EnableShip;
4017 mi->fp[i++] = (int *)osipf_IsShipEnabled;
4018 mi->fp[i++] = (int *)osipf_PathGetInformation;
4019 mi->fp[i++] = (int *)Cinematic_StartCannedScript;
4020 mi->fp[i++] = (int *)osipf_FindMatcenName;
4021 mi->fp[i++] = (int *)osipf_FindPathName;
4022 mi->fp[i++] = (int *)osipf_FindLevelGoalName;
4023 mi->fp[i++] = (int *)osipf_ObjectFindType;
4024 mi->fp[i++] = (int *)osipf_LGoalValue;
4025 mi->fp[i++] = (int *)osipf_ObjMakeListOfType;
4026 mi->fp[i++] = (int *)osipf_ObjKill;
4027 // mi->fp[i++] = (int *)osipf_AIAreRoomsReachable;
4028 mi->fp[i++] = (int *)osipf_AIIsDestReachable;
4029 mi->fp[i++] = (int *)osipf_AIIsObjReachable;
4030 mi->fp[i++] = (int *)osipf_GameGetDiffLevel;
4031 mi->fp[i++] = (int *)osipf_GetLanguageSetting;
4032 mi->fp[i++] = (int *)osipf_PathValue;
4033
4034 // fill in the remaining with NULL
4035 for (; i < MAX_MODULEFUNCS; i++) {
4036 mi->fp[i] = NULL;
4037 }
4038 }