2 * vim: set ts=4 sw=4 tw=99 noet :
3 * =============================================================================
5 * Copyright (C) 2004-2010 AlliedModders LLC. All rights reserved.
6 * =============================================================================
8 * This program is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, version 3.0, as published by the
10 * Free Software Foundation.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * You should have received a copy of the GNU General Public License along with
18 * this program. If not, see <http://www.gnu.org/licenses/>.
20 * As a special exception, AlliedModders LLC gives you permission to link the
21 * code of this program (as well as its derivative works) to "Half-Life 2," the
22 * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
23 * by the Valve Corporation. You must obey the GNU General Public License in
24 * all respects for all other code used. Additionally, AlliedModders LLC grants
25 * this exception to all derivative works. AlliedModders LLC defines further
26 * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
27 * or <http://www.sourcemod.net/license.php>.
32 #include "EventManager.h"
33 #include "ForwardSys.h"
34 #include "sm_stringutil.h"
35 #include "logic_bridge.h"
37 EventManager g_EventManager;
39 SH_DECL_HOOK2(IGameEventManager2, FireEvent, SH_NOATTRIB, 0, bool, IGameEvent *, bool);
41 const ParamType GAMEEVENT_PARAMS[] = {Param_Cell, Param_String, Param_Cell};
42 typedef List<EventHook *> EventHookList;
44 class EventForwardFilter : public IForwardFilter
46 EventInfo *pEventInfo;
48 EventForwardFilter(EventInfo *pEventInfo) : pEventInfo(pEventInfo)
52 void Preprocess(IPluginFunction *fun, FwdParamInfo *params)
54 params[2].val = pEventInfo->bDontBroadcast ? 1 : 0;
58 EventManager::EventManager() : m_EventType(0)
62 EventManager::~EventManager()
64 /* Free memory used by EventInfo structs if any */
65 CStack<EventInfo *>::iterator iter;
66 for (iter = m_FreeEvents.begin(); iter != m_FreeEvents.end(); iter++)
71 m_FreeEvents.popall();
74 void EventManager::OnSourceModAllInitialized()
76 /* Add a hook for IGameEventManager2::FireEvent() */
77 SH_ADD_HOOK(IGameEventManager2, FireEvent, gameevents, SH_MEMBER(this, &EventManager::OnFireEvent), false);
78 SH_ADD_HOOK(IGameEventManager2, FireEvent, gameevents, SH_MEMBER(this, &EventManager::OnFireEvent_Post), true);
82 /* Handle access security for 'GameEvent' handle type */
83 sec.access[HandleAccess_Read] = 0;
84 sec.access[HandleAccess_Delete] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
85 sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY | HANDLE_RESTRICT_OWNER;
87 /* Create the 'GameEvent' handle type */
88 m_EventType = handlesys->CreateType("GameEvent", this, 0, NULL, &sec, g_pCoreIdent, NULL);
91 void EventManager::OnSourceModShutdown()
93 /* Remove hook for IGameEventManager2::FireEvent() */
94 SH_REMOVE_HOOK(IGameEventManager2, FireEvent, gameevents, SH_MEMBER(this, &EventManager::OnFireEvent), false);
95 SH_REMOVE_HOOK(IGameEventManager2, FireEvent, gameevents, SH_MEMBER(this, &EventManager::OnFireEvent_Post), true);
97 /* Remove the 'GameEvent' handle type */
98 handlesys->RemoveType(m_EventType, g_pCoreIdent);
100 /* Remove ourselves as listener for events */
101 gameevents->RemoveListener(this);
104 void EventManager::OnHandleDestroy(HandleType_t type, void *object)
106 EventInfo *pInfo = static_cast<EventInfo *>(object);
108 /* Should only free event when created by a plugin */
111 /* Free IGameEvent */
112 gameevents->FreeEvent(pInfo->pEvent);
114 /* Add EventInfo struct to free event stack */
115 m_FreeEvents.push(pInfo);
119 void EventManager::OnPluginUnloaded(IPlugin *plugin)
121 EventHookList *pHookList;
122 EventHookList::iterator iter;
125 // If plugin has an event hook list...
126 if (plugin->GetProperty("EventHooks", reinterpret_cast<void **>(&pHookList), true))
128 for (iter = pHookList->begin(); iter != pHookList->end(); iter++)
132 if (--pHook->refCount == 0)
136 g_Forwards.ReleaseForward(pHook->pPreHook);
139 if (pHook->pPostHook)
141 g_Forwards.ReleaseForward(pHook->pPostHook);
152 /* IGameEventListener2::FireGameEvent */
153 void EventManager::FireGameEvent(IGameEvent *pEvent)
155 /* Not going to do anything here.
156 Just need to add ourselves as a listener to make our hook on IGameEventManager2::FireEvent work */
159 #if SOURCE_ENGINE >= SE_LEFT4DEAD
160 int EventManager::GetEventDebugID()
162 return EVENT_DEBUG_ID_INIT;
166 EventHookError EventManager::HookEvent(const char *name, IPluginFunction *pFunction, EventHookMode mode)
170 /* If we aren't listening to this event... */
171 if (!gameevents->FindListener(this, name))
173 /* Then add ourselves */
174 if (!gameevents->AddListener(this, name, true))
176 /* If event doesn't exist... */
177 return EventHookErr_InvalidEvent;
181 /* If a hook structure does not exist... */
182 if (!m_EventHooks.retrieve(name, &pHook))
184 EventHookList *pHookList;
185 IPlugin *plugin = scripts->FindPluginByContext(pFunction->GetParentContext()->GetContext());
187 /* Check plugin for an existing EventHook list */
188 if (!plugin->GetProperty("EventHooks", (void **)&pHookList))
190 pHookList = new EventHookList();
191 plugin->SetProperty("EventHooks", pHookList);
194 /* Create new GameEventHook structure */
195 pHook = new EventHook();
197 if (mode == EventHookMode_Pre)
199 /* Create forward for a pre hook */
200 pHook->pPreHook = g_Forwards.CreateForwardEx(NULL, ET_Hook, 3, GAMEEVENT_PARAMS);
201 /* Add to forward list */
202 pHook->pPreHook->AddFunction(pFunction);
204 /* Create forward for a post hook */
205 pHook->pPostHook = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, GAMEEVENT_PARAMS);
206 /* Should we copy data from a pre hook to the post hook? */
207 pHook->postCopy = (mode == EventHookMode_Post);
208 /* Add to forward list */
209 pHook->pPostHook->AddFunction(pFunction);
212 /* Cache the name for post hooks */
213 pHook->name = sm_strdup(name);
215 /* Increase reference count */
218 /* Add hook structure to hook lists */
219 pHookList->push_back(pHook);
220 m_EventHooks.insert(name, pHook);
222 return EventHookErr_Okay;
225 /* Hook structure already exists at this point */
227 if (mode == EventHookMode_Pre)
229 /* Create pre hook forward if necessary */
230 if (!pHook->pPreHook)
232 pHook->pPreHook = g_Forwards.CreateForwardEx(NULL, ET_Event, 3, GAMEEVENT_PARAMS);
235 /* Add plugin function to forward list */
236 pHook->pPreHook->AddFunction(pFunction);
238 /* Create post hook forward if necessary */
239 if (!pHook->pPostHook)
241 pHook->pPostHook = g_Forwards.CreateForwardEx(NULL, ET_Ignore, 3, GAMEEVENT_PARAMS);
244 /* If postCopy is false, then we may want to set it to true */
245 if (!pHook->postCopy)
247 pHook->postCopy = (mode == EventHookMode_Post);
250 /* Add plugin function to forward list */
251 pHook->pPostHook->AddFunction(pFunction);
254 /* Increase reference count */
257 return EventHookErr_Okay;
260 EventHookError EventManager::UnhookEvent(const char *name, IPluginFunction *pFunction, EventHookMode mode)
263 IChangeableForward **pEventForward;
265 /* If hook does not exist at all */
266 if (!m_EventHooks.retrieve(name, &pHook))
268 return EventHookErr_NotActive;
271 /* One forward to rule them all */
272 if (mode == EventHookMode_Pre)
274 pEventForward = &pHook->pPreHook;
276 pEventForward = &pHook->pPostHook;
279 /* Remove function from forward's list */
280 if (*pEventForward == NULL || !(*pEventForward)->RemoveFunction(pFunction))
282 return EventHookErr_InvalidCallback;
285 /* If forward's list contains 0 functions now, free it */
286 if ((*pEventForward)->GetFunctionCount() == 0)
288 g_Forwards.ReleaseForward(*pEventForward);
289 *pEventForward = NULL;
292 /* Decrement reference count */
293 if (--pHook->refCount == 0)
295 /* If reference count is now 0, free hook structure */
297 EventHookList *pHookList;
298 IPlugin *plugin = scripts->FindPluginByContext(pFunction->GetParentContext()->GetContext());
300 /* Get plugin's event hook list */
301 if (!plugin->GetProperty("EventHooks", (void**)&pHookList))
303 return EventHookErr_NotActive;
306 /* Make sure the event was actually being hooked */
307 if (pHookList->find(pHook) == pHookList->end())
309 return EventHookErr_NotActive;
312 /* Remove current structure from plugin's list */
313 pHookList->remove(pHook);
315 /* Delete entry in trie */
316 m_EventHooks.remove(name);
318 /* Free the cached name */
321 /* And finally free structure memory */
325 return EventHookErr_Okay;
328 EventInfo *EventManager::CreateEvent(IPluginContext *pContext, const char *name, bool force)
331 IGameEvent *pEvent = gameevents->CreateEvent(name, force);
335 if (m_FreeEvents.empty())
337 pInfo = new EventInfo();
339 pInfo = m_FreeEvents.front();
344 pInfo->pEvent = pEvent;
345 pInfo->pOwner = pContext->GetIdentity();
346 pInfo->bDontBroadcast = false;
354 void EventManager::FireEvent(EventInfo *pInfo, bool bDontBroadcast)
356 /* Actually fire event now */
357 gameevents->FireEvent(pInfo->pEvent, bDontBroadcast);
359 /* IGameEvent is free at this point, so no one owns this */
360 pInfo->pOwner = NULL;
362 /* Add EventInfo struct to free event stack */
363 m_FreeEvents.push(pInfo);
366 void EventManager::CancelCreatedEvent(EventInfo *pInfo)
368 /* Free event from IGameEventManager2 */
369 gameevents->FreeEvent(pInfo->pEvent);
371 /* IGameEvent is free at this point, so no one owns this */
372 pInfo->pOwner = NULL;
374 /* Add EventInfo struct to free event stack */
375 m_FreeEvents.push(pInfo);
378 /* IGameEventManager2::FireEvent hook */
379 bool EventManager::OnFireEvent(IGameEvent *pEvent, bool bDontBroadcast)
382 IChangeableForward *pForward;
384 cell_t res = Pl_Continue;
385 bool broadcast = bDontBroadcast;
387 /* The engine accepts NULL without crashing, so to prevent a crash in SM we ignore these */
390 RETURN_META_VALUE(MRES_IGNORED, false);
393 name = pEvent->GetName();
395 if (m_EventHooks.retrieve(name, &pHook))
397 /* Push the event onto the event stack. The reference count is increased to make sure
398 * the structure is not garbage collected in between now and the post hook.
401 m_EventStack.push(pHook);
403 pForward = pHook->pPreHook;
407 EventInfo info(pEvent, NULL);
408 HandleSecurity sec(NULL, g_pCoreIdent);
409 Handle_t hndl = handlesys->CreateHandle(m_EventType, &info, NULL, g_pCoreIdent, NULL);
411 info.bDontBroadcast = bDontBroadcast;
413 EventForwardFilter filter(&info);
415 pForward->PushCell(hndl);
416 pForward->PushString(name);
417 pForward->PushCell(bDontBroadcast);
418 pForward->Execute(&res, &filter);
420 broadcast = info.bDontBroadcast;
422 handlesys->FreeHandle(hndl, &sec);
427 m_EventCopies.push(gameevents->DuplicateEvent(pEvent));
432 gameevents->FreeEvent(pEvent);
433 RETURN_META_VALUE(MRES_SUPERCEDE, false);
438 m_EventStack.push(NULL);
441 if (broadcast != bDontBroadcast)
442 RETURN_META_VALUE_NEWPARAMS(MRES_IGNORED, true, &IGameEventManager2::FireEvent, (pEvent, broadcast));
444 RETURN_META_VALUE(MRES_IGNORED, true);
447 /* IGameEventManager2::FireEvent post hook */
448 bool EventManager::OnFireEvent_Post(IGameEvent *pEvent, bool bDontBroadcast)
452 IChangeableForward *pForward;
455 /* The engine accepts NULL without crashing, so to prevent a crash in SM we ignore these */
458 RETURN_META_VALUE(MRES_IGNORED, false);
461 pHook = m_EventStack.front();
465 pForward = pHook->pPostHook;
471 info.bDontBroadcast = bDontBroadcast;
472 info.pEvent = m_EventCopies.front();
474 hndl = handlesys->CreateHandle(m_EventType, &info, NULL, g_pCoreIdent, NULL);
476 pForward->PushCell(hndl);
478 pForward->PushCell(BAD_HANDLE);
481 pForward->PushString(pHook->name);
482 pForward->PushCell(bDontBroadcast);
483 pForward->Execute(NULL);
488 HandleSecurity sec(NULL, g_pCoreIdent);
489 handlesys->FreeHandle(hndl, &sec);
491 /* Free event structure */
492 gameevents->FreeEvent(info.pEvent);
497 /* Decrement reference count, check if a delayed delete is needed */
498 if (--pHook->refCount == 0)
500 assert(pHook->pPostHook == NULL);
501 assert(pHook->pPreHook == NULL);
502 m_EventHooks.remove(pHook->name);
510 RETURN_META_VALUE(MRES_IGNORED, true);