Problems with stencils

Hi people, I’m using this code to draw an outline around NPC’s to see them through walls. Its a slightly modified version of a piece of code posted by Bletotum:


hook.Add("PostDrawOpaqueRenderables","PlayerBorders",function()
	--stencil work is done in postdrawopaquerenderables, where surface doesn't work correctly
	--workaround via 3D2D
	local pos = LocalPlayer():EyePos()+LocalPlayer():EyeAngles():Forward()*10
	local ang = LocalPlayer():EyeAngles()
	ang = Angle(ang.p+90,ang.y,0)
	for k, v in pairs(npctable) do
		render.ClearStencil()
		render.SetStencilEnable(true)
			render.SetStencilWriteMask(255)
			render.SetStencilTestMask(255)
			render.SetStencilReferenceValue(15)
			render.SetStencilFailOperation(STENCILOPERATION_KEEP)
			render.SetStencilZFailOperation(STENCILOPERATION_REPLACE)
			render.SetStencilPassOperation(STENCILOPERATION_REPLACE)
			render.SetStencilCompareFunction(STENCILCOMPARISONFUNCTION_ALWAYS)
			render.SetBlend(0) --don't visually draw, just stencil
			v:SetModelScale(1.1,0)
			v:DrawModel()
			-- Remove the inner part of the stencil, so it only draws the outline
			render.SetStencilZFailOperation(STENCILOPERATION_ZERO)
			render.SetStencilPassOperation(STENCILOPERATION_ZERO)
			v:SetModelScale(1,0)
			v:DrawModel()
			render.SetBlend(1)
			render.SetStencilCompareFunction(STENCILCOMPARISONFUNCTION_EQUAL)
			cam.Start3D2D(pos,ang,1)
					surface.SetDrawColor(255,0,0,255)
					surface.DrawRect(-ScrW(),-ScrH(),ScrW()*2,ScrH()*2)
			cam.End3D2D()
			v:DrawModel()
		render.SetStencilEnable(false)
	end
end)

The problem is that this work fine for physics props, but not for NPC’s. For some reason, only the first “SetModelScale()” is executed, the rest are ignored. Instead of drawing an outline, it draws a bigger NPC model. I guess you can’t change an NPC model scale twice in the same draw tick? Is there any workaround?

Another thing. This code works fine for props, but I noticed that if I shoot them, it creates two hole decals. Is there a way to not draw decals over the outline model?

Replace



v:SetModelScale(1.1,0)


With



v:SetModelScale(1,0)


That’s why the NPC is getting bigger…

Eh… Thats what I did. I make it bigger to change the value of stencil pixels, and then I reset the scale to 1. However, the second “v:SetModelScale(1,0)” is ignored, the model keeps his 1.1 scale. This doesn’t happen with physics props, as they are redrawn with their original scale at the end of the stencil block.