core/smn_timers.cpp
author David Anderson <dvander@alliedmods.net>
Wed Feb 25 20:07:12 2009 -0500 (2009-02-25)
changeset 2607 f3b8bbe17f85
parent 2379 85c7816b2f08
child 2639 021fbd7a8cf6
permissions -rw-r--r--
Backed out changeset fa286305bd3f
     1 /**
     2  * vim: set ts=4 :
     3  * =============================================================================
     4  * SourceMod
     5  * Copyright (C) 2004-2008 AlliedModders LLC.  All rights reserved.
     6  * =============================================================================
     7  *
     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.
    11  * 
    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
    15  * details.
    16  *
    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/>.
    19  *
    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>.
    28  *
    29  * Version: $Id$
    30  */
    31 
    32 #include "HandleSys.h"
    33 #include "TimerSys.h"
    34 #include "PluginSys.h"
    35 #include "Logger.h"
    36 #include "DebugReporter.h"
    37 
    38 #define TIMER_HNDL_CLOSE	(1<<9)
    39 
    40 HandleType_t g_TimerType;
    41 
    42 struct TimerInfo 
    43 {
    44 	ITimer *Timer;
    45 	IPluginFunction *Hook;
    46 	IPluginContext *pContext;
    47 	Handle_t TimerHandle;
    48 	int UserData;
    49 	int Flags;
    50 };
    51 
    52 class TimerNatives :
    53 	public SMGlobalClass,
    54 	public IHandleTypeDispatch,
    55 	public ITimedEvent
    56 {
    57 public:
    58 	~TimerNatives();
    59 public: //ITimedEvent
    60 	ResultType OnTimer(ITimer *pTimer, void *pData);
    61 	void OnTimerEnd(ITimer *pTimer, void *pData);
    62 public: //IHandleTypeDispatch
    63 	void OnHandleDestroy(HandleType_t type, void *object);
    64 public: //SMGlobalClass
    65 	void OnSourceModAllInitialized();
    66 	void OnSourceModShutdown();
    67 public:
    68 	TimerInfo *CreateTimerInfo();
    69 	void DeleteTimerInfo(TimerInfo *pInfo);
    70 private:
    71 	CStack<TimerInfo *> m_FreeTimers;
    72 };
    73 
    74 TimerNatives::~TimerNatives()
    75 {
    76 	CStack<TimerInfo *>::iterator iter;
    77 	for (iter=m_FreeTimers.begin(); iter!=m_FreeTimers.end(); iter++)
    78 	{
    79 		delete (*iter);
    80 	}
    81 	m_FreeTimers.popall();
    82 }
    83 
    84 void TimerNatives::OnSourceModAllInitialized()
    85 {
    86 	HandleAccess sec;
    87 
    88 	g_HandleSys.InitAccessDefaults(NULL, &sec);
    89 	sec.access[HandleAccess_Clone] = HANDLE_RESTRICT_IDENTITY;
    90 
    91 	g_TimerType = g_HandleSys.CreateType("Timer", this, 0, NULL, &sec, g_pCoreIdent, NULL);
    92 }
    93 
    94 void TimerNatives::OnSourceModShutdown()
    95 {
    96 	g_HandleSys.RemoveType(g_TimerType, g_pCoreIdent);
    97 	g_TimerType = 0;
    98 }
    99 
   100 void TimerNatives::OnHandleDestroy(HandleType_t type, void *object)
   101 {
   102 	TimerInfo *pTimer = reinterpret_cast<TimerInfo *>(object);
   103 
   104 	g_Timers.KillTimer(pTimer->Timer);
   105 }
   106 
   107 TimerInfo *TimerNatives::CreateTimerInfo()
   108 {
   109 	TimerInfo *pInfo;
   110 
   111 	if (m_FreeTimers.empty())
   112 	{
   113 		pInfo = new TimerInfo;
   114 	} else {
   115 		pInfo = m_FreeTimers.front();
   116 		m_FreeTimers.pop();
   117 	}
   118 
   119 	return pInfo;
   120 }
   121 
   122 void TimerNatives::DeleteTimerInfo(TimerInfo *pInfo)
   123 {
   124 	m_FreeTimers.push(pInfo);
   125 }
   126 
   127 ResultType TimerNatives::OnTimer(ITimer *pTimer, void *pData)
   128 {
   129 	TimerInfo *pInfo = reinterpret_cast<TimerInfo *>(pData);
   130 	IPluginFunction *pFunc = pInfo->Hook;
   131 	cell_t res = static_cast<ResultType>(Pl_Continue);
   132 
   133 	pFunc->PushCell(pInfo->TimerHandle);
   134 	pFunc->PushCell(pInfo->UserData);
   135 	pFunc->Execute(&res);
   136 
   137 	return static_cast<ResultType>(res);
   138 }
   139 
   140 void TimerNatives::OnTimerEnd(ITimer *pTimer, void *pData)
   141 {
   142 	HandleSecurity sec;
   143 	HandleError herr;
   144 	TimerInfo *pInfo = reinterpret_cast<TimerInfo *>(pData);
   145 	Handle_t usrhndl = static_cast<Handle_t>(pInfo->UserData);
   146 
   147 	sec.pOwner = pInfo->pContext->GetIdentity();
   148 	sec.pIdentity = g_pCoreIdent;
   149 
   150 	if (pInfo->Flags & TIMER_HNDL_CLOSE)
   151 	{
   152 		if ((herr=g_HandleSys.FreeHandle(usrhndl, &sec)) != HandleError_None)
   153 		{
   154 			g_DbgReporter.GenerateError(pInfo->pContext,
   155 										pInfo->Hook->GetFunctionID(), 
   156 										SP_ERROR_NATIVE, 
   157 										"Invalid data handle %x (error %d) passed during timer end",
   158 										usrhndl, 
   159 										herr);
   160 		}
   161 	}
   162 
   163 	if (pInfo->TimerHandle != BAD_HANDLE)
   164 	{
   165 		if ((herr=g_HandleSys.FreeHandle(pInfo->TimerHandle, &sec)) != HandleError_None)
   166 		{
   167 			g_DbgReporter.GenerateError(pInfo->pContext, 
   168 				pInfo->Hook->GetFunctionID(), 
   169 				SP_ERROR_NATIVE, 
   170 				"Invalid timer handle %x (error %d) during timer end, displayed function is timer callback, not the stack trace", 
   171 				pInfo->TimerHandle, 
   172 				herr);
   173 		}
   174 	}
   175 
   176 	DeleteTimerInfo(pInfo);
   177 }
   178 
   179 /*******************************
   180 *                              *
   181 * TIMER NATIVE IMPLEMENTATIONS *
   182 *                              *
   183 ********************************/
   184 
   185 static TimerNatives s_TimerNatives;
   186 
   187 static cell_t smn_CreateTimer(IPluginContext *pCtx, const cell_t *params)
   188 {
   189 	IPluginFunction *pFunc;
   190 	TimerInfo *pInfo;
   191 	ITimer *pTimer;
   192 	Handle_t hndl;
   193 	int flags = params[4];
   194 
   195 	pFunc = pCtx->GetFunctionById(params[2]);
   196 	if (!pFunc)
   197 	{
   198 		return pCtx->ThrowNativeError("Invalid function id (%X)", params[2]);
   199 	}
   200 
   201 	pInfo = s_TimerNatives.CreateTimerInfo();
   202 	pTimer = g_Timers.CreateTimer(&s_TimerNatives, sp_ctof(params[1]), pInfo, flags);
   203 
   204 	if (!pTimer)
   205 	{
   206 		s_TimerNatives.DeleteTimerInfo(pInfo);
   207 		return 0;
   208 	}
   209 
   210 	hndl = g_HandleSys.CreateHandle(g_TimerType, pInfo, pCtx->GetIdentity(), g_pCoreIdent, NULL);
   211 
   212 	/* If we can't get a handle, the timer isn't refcounted against the plugin and 
   213 	 * we need to bail out to prevent a crash.
   214 	 */
   215 	if (hndl == BAD_HANDLE)
   216 	{
   217 		/* Free this for completeness. */
   218 		if (flags & TIMER_HNDL_CLOSE)
   219 		{
   220 			HandleSecurity sec(pCtx->GetIdentity(), g_pCoreIdent);
   221 			g_HandleSys.FreeHandle(params[3], &sec);
   222 		}
   223 		/* Zero everything so there's no conflicts */
   224 		memset(pInfo, 0, sizeof(TimerInfo));
   225 		g_Timers.KillTimer(pTimer);
   226 
   227 		return pCtx->ThrowNativeError("Could not create timer, no more handles");
   228 	}
   229 
   230 	pInfo->UserData = params[3];
   231 	pInfo->Flags = flags;
   232 	pInfo->TimerHandle = hndl;
   233 	pInfo->Hook = pFunc;
   234 	pInfo->Timer = pTimer;
   235 	pInfo->pContext = pCtx;
   236 
   237 	return hndl;
   238 }
   239 
   240 static cell_t smn_KillTimer(IPluginContext *pCtx, const cell_t *params)
   241 {
   242 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   243 	HandleError herr;
   244 	HandleSecurity sec;
   245 	TimerInfo *pInfo;
   246 
   247 	sec.pOwner = pCtx->GetIdentity();
   248 	sec.pIdentity = g_pCoreIdent;
   249 
   250 	if ((herr=g_HandleSys.ReadHandle(hndl, g_TimerType, &sec, (void **)&pInfo))
   251 		!= HandleError_None)
   252 	{
   253 		return pCtx->ThrowNativeError("Invalid timer handle %x (error %d)", hndl, herr);
   254 	}
   255 
   256 	g_Timers.KillTimer(pInfo->Timer);
   257 
   258 	if (params[2] && !(pInfo->Flags & TIMER_HNDL_CLOSE))
   259 	{
   260 		sec.pOwner = pInfo->pContext->GetIdentity();
   261 		sec.pIdentity = g_pCoreIdent;
   262 
   263 		if ((herr=g_HandleSys.FreeHandle(static_cast<Handle_t>(pInfo->UserData), &sec)) != HandleError_None)
   264 		{
   265 			return pCtx->ThrowNativeError("Invalid data handle %x (error %d)", hndl, herr);
   266 		}
   267 	}
   268 
   269 	return 1;
   270 }
   271 
   272 static cell_t smn_TriggerTimer(IPluginContext *pCtx, const cell_t *params)
   273 {
   274 	Handle_t hndl = static_cast<Handle_t>(params[1]);
   275 	HandleError herr;
   276 	HandleSecurity sec;
   277 	TimerInfo *pInfo;
   278 
   279 	sec.pOwner = pCtx->GetIdentity();
   280 	sec.pIdentity = g_pCoreIdent;
   281 
   282 	if ((herr=g_HandleSys.ReadHandle(hndl, g_TimerType, &sec, (void **)&pInfo))
   283 		!= HandleError_None)
   284 	{
   285 		return pCtx->ThrowNativeError("Invalid timer handle %x (error %d)", hndl, herr);
   286 	}
   287 
   288 	g_Timers.FireTimerOnce(pInfo->Timer, params[2] ? true : false);
   289 
   290 	return 1;
   291 }
   292 
   293 static cell_t smn_GetTickedTime(IPluginContext *pContext, const cell_t *params)
   294 {
   295 	return sp_ftoc(*g_pUniversalTime);
   296 }
   297 
   298 static cell_t smn_GetMapTimeLeft(IPluginContext *pContext, const cell_t *params)
   299 {
   300 	float time_left;
   301 	if (!g_Timers.GetMapTimeLeft(&time_left))
   302 	{
   303 		return 0;
   304 	}
   305 
   306 	cell_t *addr;
   307 	pContext->LocalToPhysAddr(params[1], &addr);
   308 	*addr = (int)time_left;
   309 
   310 	return 1;
   311 }
   312 
   313 static cell_t smn_GetMapTimeLimit(IPluginContext *pContext, const cell_t *params)
   314 {
   315 	IMapTimer *pMapTimer = g_Timers.GetMapTimer();
   316 
   317 	if (!pMapTimer)
   318 	{
   319 		return 0;
   320 	}
   321 
   322 	cell_t *addr;
   323 	pContext->LocalToPhysAddr(params[1], &addr);
   324 
   325 	*addr = pMapTimer->GetMapTimeLimit();
   326 
   327 	return 1;
   328 }
   329 
   330 static cell_t smn_ExtendMapTimeLimit(IPluginContext *pContext, const cell_t *params)
   331 {
   332 	IMapTimer *pMapTimer = g_Timers.GetMapTimer();
   333 
   334 	if (!pMapTimer)
   335 	{
   336 		return 0;
   337 	}
   338 
   339 	pMapTimer->ExtendMapTimeLimit(params[1]);
   340 
   341 	return 1;
   342 }
   343 
   344 static cell_t smn_IsServerProcessing(IPluginContext *pContext, const cell_t *params)
   345 {
   346 	return (gpGlobals->frametime > 0.0f) ? 1 : 0;
   347 }
   348 
   349 static cell_t smn_GetTickInterval(IPluginContext *pContext, const cell_t *params)
   350 {
   351 	return sp_ftoc(gpGlobals->interval_per_tick);
   352 }
   353 
   354 REGISTER_NATIVES(timernatives)
   355 {
   356 	{"CreateTimer",				smn_CreateTimer},
   357 	{"KillTimer",				smn_KillTimer},
   358 	{"TriggerTimer",			smn_TriggerTimer},
   359 	{"GetTickedTime",			smn_GetTickedTime},
   360 	{"GetMapTimeLeft",			smn_GetMapTimeLeft},
   361 	{"GetMapTimeLimit",			smn_GetMapTimeLimit},
   362 	{"ExtendMapTimeLimit",		smn_ExtendMapTimeLimit},
   363 	{"IsServerProcessing",		smn_IsServerProcessing},
   364 	{"GetTickInterval",			smn_GetTickInterval},
   365 	{NULL,						NULL}
   366 };
   367