BsScenePicking.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. #include "BsScenePicking.h"
  2. #include "BsSceneManager.h"
  3. #include "BsColor.h"
  4. #include "BsMatrix4.h"
  5. #include "BsDebug.h"
  6. #include "BsMath.h"
  7. #include "BsRenderable.h"
  8. #include "BsSceneObject.h"
  9. #include "BsMesh.h"
  10. #include "BsConvexVolume.h"
  11. #include "BsCamera.h"
  12. #include "BsCoreThread.h"
  13. #include "BsRenderSystem.h"
  14. #include "BsMaterial.h"
  15. #include "BsPass.h"
  16. #include "BsBlendState.h"
  17. #include "BsDepthStencilState.h"
  18. #include "BsRasterizerState.h"
  19. #include "BsRenderTarget.h"
  20. #include "BsPixelData.h"
  21. #include "BsGpuParams.h"
  22. #include "BsBuiltinEditorResources.h"
  23. #include "BsShader.h"
  24. #include "BsRenderer.h"
  25. using namespace std::placeholders;
  26. namespace BansheeEngine
  27. {
  28. const float ScenePicking::ALPHA_CUTOFF = 0.5f;
  29. ScenePicking::ScenePicking()
  30. {
  31. for (UINT32 i = 0; i < 3; i++)
  32. {
  33. mMaterialData[i].mMatPicking = BuiltinEditorResources::instance().createPicking((CullingMode)i);
  34. mMaterialData[i].mMatPickingAlpha = BuiltinEditorResources::instance().createPickingAlpha((CullingMode)i);
  35. mMaterialData[i].mMatPickingProxy = mMaterialData[i].mMatPicking->_createProxy();
  36. mMaterialData[i].mMatPickingAlphaProxy = mMaterialData[i].mMatPickingAlpha->_createProxy();
  37. }
  38. gCoreAccessor().queueCommand(std::bind(&ScenePicking::initializeCore, this));
  39. }
  40. void ScenePicking::initializeCore()
  41. {
  42. for (UINT32 i = 0; i < 3; i++)
  43. {
  44. MaterialData& md = mMaterialData[i];
  45. {
  46. // TODO - Make a better interface when dealing with parameters through proxies?
  47. MaterialProxyPtr proxy = md.mMatPickingProxy;
  48. md.mParamPickingVertParams = proxy->params[proxy->passes[0].vertexProgParamsIdx];
  49. md.mParamPickingVertParams->getParam("matWorldViewProj", md.mParamPickingWVP);
  50. md.mParamPickingFragParams = proxy->params[proxy->passes[0].fragmentProgParamsIdx];
  51. md.mParamPickingFragParams->getParam("colorIndex", md.mParamPickingColor);
  52. }
  53. {
  54. MaterialProxyPtr proxy = md.mMatPickingAlphaProxy;
  55. md.mParamPickingAlphaVertParams = proxy->params[proxy->passes[0].vertexProgParamsIdx];
  56. md.mParamPickingAlphaVertParams->getParam("matWorldViewProj", md.mParamPickingAlphaWVP);
  57. md.mParamPickingAlphaFragParams = proxy->params[proxy->passes[0].fragmentProgParamsIdx];
  58. md.mParamPickingAlphaFragParams->getParam("colorIndex", md.mParamPickingAlphaColor);
  59. md.mParamPickingAlphaFragParams->getTextureParam("mainTexture", md.mParamPickingAlphaTexture);
  60. GpuParamFloat alphaCutoffParam;
  61. md.mParamPickingAlphaFragParams->getParam("alphaCutoff", alphaCutoffParam);
  62. alphaCutoffParam.set(ALPHA_CUTOFF);
  63. }
  64. }
  65. }
  66. HSceneObject ScenePicking::pickClosestSceneObject(const HCamera& cam, const Vector2I& position, const Vector2I& area)
  67. {
  68. Vector<PickResult> selectedObjects = pickObjects(cam, position, area);
  69. for (auto& object : selectedObjects)
  70. {
  71. if (object.type == PickResult::Type::SceneObject)
  72. return object.sceneObject;
  73. }
  74. return HSceneObject();
  75. }
  76. PickResult ScenePicking::pickClosestObject(const HCamera& cam, const Vector2I& position, const Vector2I& area)
  77. {
  78. Vector<PickResult> selectedObjects = pickObjects(cam, position, area);
  79. if (selectedObjects.size() == 0)
  80. return { HSceneObject(), 0, PickResult::Type::None };
  81. return selectedObjects[0];
  82. }
  83. Vector<HSceneObject> ScenePicking::pickSceneObjects(const HCamera& cam, const Vector2I& position, const Vector2I& area)
  84. {
  85. Vector<HSceneObject> results;
  86. Vector<PickResult> selectedObjects = pickObjects(cam, position, area);
  87. for (auto& object : selectedObjects)
  88. {
  89. if (object.type == PickResult::Type::SceneObject)
  90. results.push_back(object.sceneObject);
  91. }
  92. return results;
  93. }
  94. Vector<PickResult> ScenePicking::pickObjects(const HCamera& cam, const Vector2I& position, const Vector2I& area)
  95. {
  96. auto comparePickElement = [&] (const ScenePicking::RenderablePickData& a, const ScenePicking::RenderablePickData& b)
  97. {
  98. // Sort by alpha setting first, then by cull mode, then by index
  99. if (a.alpha == b.alpha)
  100. {
  101. if (a.cullMode == b.cullMode)
  102. return a.index > b.index;
  103. else
  104. return (UINT32)a.cullMode > (UINT32)b.cullMode;
  105. }
  106. else
  107. return (UINT32)a.alpha > (UINT32)b.alpha;
  108. };
  109. Matrix4 viewProjMatrix = cam->getProjectionMatrix() * cam->getViewMatrix();
  110. const Vector<HRenderable>& renderables = SceneManager::instance().getAllRenderables();
  111. RenderableSet pickData(comparePickElement);
  112. Map<UINT32, HRenderable> idxToRenderable;
  113. for (auto& renderable : renderables)
  114. {
  115. HSceneObject so = renderable->SO();
  116. if (!so->getActive())
  117. continue;
  118. HMesh mesh = renderable->getMesh();
  119. if (!mesh)
  120. continue;
  121. Bounds worldBounds = mesh->getBounds();
  122. Matrix4 worldTransform = so->getWorldTfrm();
  123. worldBounds.transformAffine(worldTransform);
  124. // TODO - I could limit the frustum to the visible area we're rendering for a speed boost
  125. // but this is unlikely to be a performance bottleneck
  126. const ConvexVolume& frustum = cam->getWorldFrustum();
  127. if (frustum.intersects(worldBounds.getSphere()))
  128. {
  129. // More precise with the box
  130. if (frustum.intersects(worldBounds.getBox()))
  131. {
  132. for (UINT32 i = 0; i < mesh->getNumSubMeshes(); i++)
  133. {
  134. UINT32 idx = (UINT32)pickData.size();
  135. HMaterial originalMat = renderable->getMaterial(i);
  136. if (!originalMat)
  137. continue;
  138. PassPtr firstPass;
  139. if (originalMat->getNumPasses() == 0)
  140. continue;
  141. firstPass = originalMat->getPass(0); // Note: We only ever check the first pass, problem?
  142. bool useAlphaShader = firstPass->hasBlending();
  143. RasterizerStatePtr rasterizerState;
  144. if (firstPass->getRasterizerState() == nullptr)
  145. rasterizerState = RasterizerState::getDefault();
  146. else
  147. rasterizerState = firstPass->getRasterizerState().getInternalPtr();
  148. CullingMode cullMode = rasterizerState->getCullMode();
  149. MeshProxyPtr meshProxy;
  150. if (mesh->_isCoreDirty(MeshDirtyFlag::Proxy))
  151. meshProxy = mesh->_createProxy(i);
  152. else
  153. meshProxy = mesh->_getActiveProxy(i);
  154. HTexture mainTexture;
  155. if (useAlphaShader)
  156. {
  157. const Map<String, SHADER_OBJECT_PARAM_DESC>& objectParams = originalMat->getShader()->_getObjectParams();
  158. for (auto& objectParam : objectParams)
  159. {
  160. if (objectParam.second.rendererSemantic == RPS_MainTex)
  161. {
  162. mainTexture = originalMat->getTexture(objectParam.first);
  163. break;
  164. }
  165. }
  166. }
  167. idxToRenderable[idx] = renderable;
  168. Matrix4 wvpTransform = viewProjMatrix * worldTransform;
  169. pickData.insert({ meshProxy, idx, wvpTransform, useAlphaShader, cullMode, mainTexture });
  170. }
  171. }
  172. }
  173. }
  174. Viewport vp = cam->getViewport()->clone();
  175. AsyncOp op = gCoreAccessor().queueReturnCommand(std::bind(&ScenePicking::corePickObjects, this, vp, std::cref(pickData), position, area, _1));
  176. gCoreAccessor().submitToCoreThread(true);
  177. assert(op.hasCompleted());
  178. Vector<UINT32>& selectedObjects = op.getReturnValue<Vector<UINT32>>();
  179. Vector<PickResult> results;
  180. for (auto& selectedObject : selectedObjects)
  181. {
  182. auto iterFind = idxToRenderable.find(selectedObject);
  183. if (iterFind != idxToRenderable.end())
  184. results.push_back({ iterFind->second->SO(), 0, PickResult::Type::SceneObject });
  185. }
  186. return results;
  187. }
  188. void ScenePicking::corePickObjects(const Viewport& vp, const RenderableSet& renderables, const Vector2I& position,
  189. const Vector2I& area, AsyncOp& asyncOp)
  190. {
  191. RenderSystem& rs = RenderSystem::instance();
  192. RenderTargetPtr rt = vp.getTarget();
  193. if (rt->getCore()->getProperties().isWindow())
  194. {
  195. // TODO: When I do implement this then I will likely want a method in RenderTarget that unifies both render window and render texture readback
  196. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  197. }
  198. RenderTexturePtr rtt = std::static_pointer_cast<RenderTexture>(rt);
  199. TexturePtr outputTexture = rtt->getBindableColorTexture().getInternalPtr();
  200. if (position.x < 0 || position.x >= (INT32)outputTexture->getWidth() ||
  201. position.y < 0 || position.y >= (INT32)outputTexture->getHeight())
  202. {
  203. asyncOp._completeOperation(Vector<UINT32>());
  204. return;
  205. }
  206. rs.beginFrame();
  207. rs.setViewport(vp);
  208. rs.clearRenderTarget(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::White);
  209. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  210. Renderer::setPass(*mMaterialData[0].mMatPickingProxy, 0);
  211. bool activeMaterialIsAlpha = false;
  212. CullingMode activeMaterialCull = (CullingMode)0;
  213. for (auto& renderable : renderables)
  214. {
  215. if (activeMaterialIsAlpha != renderable.alpha || activeMaterialCull != renderable.cullMode)
  216. {
  217. activeMaterialIsAlpha = renderable.alpha;
  218. activeMaterialCull = renderable.cullMode;
  219. if (activeMaterialIsAlpha)
  220. Renderer::setPass(*mMaterialData[(UINT32)activeMaterialCull].mMatPickingAlphaProxy, 0);
  221. else
  222. Renderer::setPass(*mMaterialData[(UINT32)activeMaterialCull].mMatPickingProxy, 0);
  223. }
  224. Color color = encodeIndex(renderable.index);
  225. MaterialData& md = mMaterialData[(UINT32)activeMaterialCull];
  226. if (activeMaterialIsAlpha)
  227. {
  228. md.mParamPickingAlphaWVP.set(renderable.wvpTransform);
  229. md.mParamPickingAlphaColor.set(color);
  230. md.mParamPickingAlphaTexture.set(renderable.mainTexture);
  231. rs.bindGpuParams(GPT_VERTEX_PROGRAM, md.mParamPickingAlphaVertParams);
  232. rs.bindGpuParams(GPT_FRAGMENT_PROGRAM, md.mParamPickingAlphaFragParams);
  233. }
  234. else
  235. {
  236. md.mParamPickingWVP.set(renderable.wvpTransform);
  237. md.mParamPickingColor.set(color);
  238. rs.bindGpuParams(GPT_VERTEX_PROGRAM, md.mParamPickingVertParams);
  239. rs.bindGpuParams(GPT_FRAGMENT_PROGRAM, md.mParamPickingFragParams);
  240. }
  241. Renderer::draw(*renderable.mesh);
  242. }
  243. rs.endFrame();
  244. PixelDataPtr outputPixelData = outputTexture->allocateSubresourceBuffer(0);
  245. GpuResourceDataPtr outputData = outputPixelData;
  246. AsyncOp unused;
  247. rs.readSubresource(outputTexture, 0, outputData, unused);
  248. Map<UINT32, UINT32> selectionScores;
  249. UINT32 numPixels = outputPixelData->getWidth() * outputPixelData->getHeight();
  250. UINT32 maxWidth = std::min((UINT32)(position.x + area.x), outputPixelData->getWidth());
  251. UINT32 maxHeight = std::min((UINT32)(position.y + area.y), outputPixelData->getHeight());
  252. if (rt->requiresTextureFlipping())
  253. {
  254. UINT32 vertOffset = outputPixelData->getHeight() - 1;
  255. for (UINT32 y = maxHeight; y > (UINT32)position.y; y--)
  256. {
  257. for (UINT32 x = (UINT32)position.x; x < maxWidth; x++)
  258. {
  259. Color color = outputPixelData->getColorAt(x, vertOffset - y);
  260. UINT32 index = decodeIndex(color);
  261. if (index == 0x00FFFFFF) // Nothing selected
  262. continue;
  263. auto iterFind = selectionScores.find(index);
  264. if (iterFind == selectionScores.end())
  265. selectionScores[index] = 1;
  266. else
  267. iterFind->second++;
  268. }
  269. }
  270. }
  271. else
  272. {
  273. for (UINT32 y = (UINT32)position.y; y < maxHeight; y++)
  274. {
  275. for (UINT32 x = (UINT32)position.x; x < maxWidth; x++)
  276. {
  277. Color color = outputPixelData->getColorAt(x, y);
  278. UINT32 index = decodeIndex(color);
  279. if (index == 0x00FFFFFF) // Nothing selected
  280. continue;
  281. auto iterFind = selectionScores.find(index);
  282. if (iterFind == selectionScores.end())
  283. selectionScores[index] = 1;
  284. else
  285. iterFind->second++;
  286. }
  287. }
  288. }
  289. // Sort by score
  290. struct SelectedObject { UINT32 index; UINT32 score; };
  291. Vector<SelectedObject> selectedObjects(selectionScores.size());
  292. UINT32 idx = 0;
  293. for (auto& selectionScore : selectionScores)
  294. {
  295. selectedObjects[idx++] = { selectionScore.first, selectionScore.second };
  296. }
  297. std::sort(selectedObjects.begin(), selectedObjects.end(),
  298. [&](const SelectedObject& a, const SelectedObject& b)
  299. {
  300. return b.score < a.score;
  301. });
  302. Vector<UINT32> results;
  303. for (auto& selectedObject : selectedObjects)
  304. results.push_back(selectedObject.index);
  305. asyncOp._completeOperation(results);
  306. }
  307. Color ScenePicking::encodeIndex(UINT32 index)
  308. {
  309. Color encoded;
  310. encoded.r = (index & 0xFF) / 255.0f;
  311. encoded.g = ((index >> 8) & 0xFF) / 255.0f;
  312. encoded.b = ((index >> 16) & 0xFF) / 255.0f;
  313. encoded.a = 1.0f;
  314. if (((index >> 24) & 0xFF))
  315. LOGERR("Index when picking out of valid range.");
  316. return encoded;
  317. }
  318. UINT32 ScenePicking::decodeIndex(Color color)
  319. {
  320. UINT32 r = Math::roundToInt(color.r * 255.0f);
  321. UINT32 g = Math::roundToInt(color.g * 255.0f);
  322. UINT32 b = Math::roundToInt(color.b * 255.0f);
  323. return (r & 0xFF) | ((g & 0xFF) << 8) | ((b & 0xFF) << 16);
  324. }
  325. }