BsScenePicking.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsScenePicking.h"
  4. #include "BsSceneManager.h"
  5. #include "BsColor.h"
  6. #include "BsMatrix4.h"
  7. #include "BsDebug.h"
  8. #include "BsMath.h"
  9. #include "BsCRenderable.h"
  10. #include "BsSceneObject.h"
  11. #include "BsMesh.h"
  12. #include "BsConvexVolume.h"
  13. #include "BsCCamera.h"
  14. #include "BsCoreThread.h"
  15. #include "BsRenderAPI.h"
  16. #include "BsMaterial.h"
  17. #include "BsPass.h"
  18. #include "BsRasterizerState.h"
  19. #include "BsRenderTarget.h"
  20. #include "BsMultiRenderTexture.h"
  21. #include "BsPixelData.h"
  22. #include "BsGpuParams.h"
  23. #include "BsGpuParamsSet.h"
  24. #include "BsBuiltinEditorResources.h"
  25. #include "BsShader.h"
  26. #include "BsCoreRenderer.h"
  27. #include "BsGizmoManager.h"
  28. #include "BsRendererUtility.h"
  29. using namespace std::placeholders;
  30. namespace BansheeEngine
  31. {
  32. const float ScenePickingCore::ALPHA_CUTOFF = 0.5f;
  33. ScenePicking::ScenePicking()
  34. {
  35. mCore = bs_new<ScenePickingCore>();
  36. for (UINT32 i = 0; i < 3; i++)
  37. {
  38. HMaterial matPicking = BuiltinEditorResources::instance().createPicking((CullingMode)i);
  39. HMaterial matPickingAlpha = BuiltinEditorResources::instance().createPickingAlpha((CullingMode)i);
  40. mCore->mMaterialData[i].mMatPickingCore = matPicking->getCore();
  41. mCore->mMaterialData[i].mMatPickingAlphaCore = matPickingAlpha->getCore();
  42. }
  43. gCoreAccessor().queueCommand(std::bind(&ScenePickingCore::initialize, mCore));
  44. }
  45. ScenePicking::~ScenePicking()
  46. {
  47. gCoreAccessor().queueCommand(std::bind(&ScenePickingCore::destroy, mCore));
  48. }
  49. HSceneObject ScenePicking::pickClosestObject(const SPtr<Camera>& cam, const Vector2I& position, const Vector2I& area,
  50. Vector<HSceneObject>& ignoreRenderables, SnapData* data)
  51. {
  52. Vector<HSceneObject> selectedObjects = pickObjects(cam, position, area, ignoreRenderables, data);
  53. if (selectedObjects.size() == 0)
  54. return HSceneObject();
  55. if (data != nullptr)
  56. {
  57. Matrix3 rotation;
  58. selectedObjects[0]->getWorldRotation().toRotationMatrix(rotation);
  59. data->normal = rotation.inverse().transpose().transform(data->normal);
  60. }
  61. return selectedObjects[0];
  62. }
  63. Vector<HSceneObject> ScenePicking::pickObjects(const SPtr<Camera>& cam, const Vector2I& position, const Vector2I& area,
  64. Vector<HSceneObject>& ignoreRenderables, SnapData* data)
  65. {
  66. auto comparePickElement = [&] (const ScenePicking::RenderablePickData& a, const ScenePicking::RenderablePickData& b)
  67. {
  68. // Sort by alpha setting first, then by cull mode, then by index
  69. if (a.alpha == b.alpha)
  70. {
  71. if (a.cullMode == b.cullMode)
  72. return a.index > b.index;
  73. else
  74. return (UINT32)a.cullMode > (UINT32)b.cullMode;
  75. }
  76. else
  77. return (UINT32)a.alpha > (UINT32)b.alpha;
  78. };
  79. Matrix4 viewProjMatrix = cam->getProjectionMatrixRS() * cam->getViewMatrix();
  80. const Map<Renderable*, SceneRenderableData>& renderables = SceneManager::instance().getAllRenderables();
  81. RenderableSet pickData(comparePickElement);
  82. Map<UINT32, HSceneObject> idxToRenderable;
  83. for (auto& renderableData : renderables)
  84. {
  85. SPtr<Renderable> renderable = renderableData.second.renderable;
  86. HSceneObject so = renderableData.second.sceneObject;
  87. if (!so->getActive())
  88. continue;
  89. HMesh mesh = renderable->getMesh();
  90. if (!mesh.isLoaded())
  91. continue;
  92. bool found = false;
  93. for (int i = 0; i < ignoreRenderables.size(); i++)
  94. {
  95. if (ignoreRenderables[i] == so)
  96. {
  97. found = true;
  98. break;
  99. }
  100. }
  101. if (found)
  102. continue;
  103. Bounds worldBounds = mesh->getProperties().getBounds();
  104. Matrix4 worldTransform = so->getWorldTfrm();
  105. worldBounds.transformAffine(worldTransform);
  106. // TODO - I could limit the frustum to the visible area we're rendering for a speed boost
  107. // but this is unlikely to be a performance bottleneck
  108. const ConvexVolume& frustum = cam->getWorldFrustum();
  109. if (frustum.intersects(worldBounds.getSphere()))
  110. {
  111. // More precise with the box
  112. if (frustum.intersects(worldBounds.getBox()))
  113. {
  114. for (UINT32 i = 0; i < mesh->getProperties().getNumSubMeshes(); i++)
  115. {
  116. UINT32 idx = (UINT32)pickData.size();
  117. bool useAlphaShader = false;
  118. SPtr<RasterizerState> rasterizerState;
  119. HMaterial originalMat = renderable->getMaterial(i);
  120. if (originalMat != nullptr && originalMat->getNumPasses() > 0)
  121. {
  122. SPtr<Pass> firstPass = originalMat->getPass(0); // Note: We only ever check the first pass, problem?
  123. useAlphaShader = firstPass->hasBlending();
  124. if (firstPass->getRasterizerState() == nullptr)
  125. rasterizerState = RasterizerState::getDefault();
  126. else
  127. rasterizerState = firstPass->getRasterizerState();
  128. }
  129. else
  130. rasterizerState = RasterizerState::getDefault();
  131. CullingMode cullMode = rasterizerState->getProperties().getCullMode();
  132. HTexture mainTexture;
  133. if (useAlphaShader)
  134. {
  135. const Map<String, SHADER_OBJECT_PARAM_DESC>& textureParams = originalMat->getShader()->getTextureParams();
  136. for (auto& objectParam : textureParams)
  137. {
  138. if (objectParam.second.rendererSemantic == RPS_Diffuse)
  139. {
  140. mainTexture = originalMat->getTexture(objectParam.first);
  141. break;
  142. }
  143. }
  144. }
  145. idxToRenderable[idx] = so;
  146. Matrix4 wvpTransform = viewProjMatrix * worldTransform;
  147. pickData.insert({ mesh->getCore(), idx, wvpTransform, useAlphaShader, cullMode, mainTexture });
  148. }
  149. }
  150. }
  151. }
  152. UINT32 firstGizmoIdx = (UINT32)pickData.size();
  153. SPtr<RenderTargetCore> target = cam->getViewport()->getTarget()->getCore();
  154. gCoreAccessor().queueCommand(std::bind(&ScenePickingCore::corePickingBegin, mCore, target,
  155. cam->getViewport()->getNormArea(), std::cref(pickData), position, area));
  156. GizmoManager::instance().renderForPicking(cam, [&](UINT32 inputIdx) { return encodeIndex(firstGizmoIdx + inputIdx); });
  157. AsyncOp op = gCoreAccessor().queueReturnCommand(std::bind(&ScenePickingCore::corePickingEnd, mCore, target,
  158. cam->getViewport()->getNormArea(), position, area, data != nullptr, _1));
  159. gCoreAccessor().submitToCoreThread(true);
  160. assert(op.hasCompleted());
  161. PickResults pickResults = op.getReturnValue<PickResults>();
  162. if (data != nullptr)
  163. {
  164. data->pickPosition = cam->screenToWorldPointDeviceDepth(position, pickResults.depth);
  165. data->normal = pickResults.normal;
  166. }
  167. Vector<UINT32> selectedObjects = pickResults.objects;
  168. Vector<HSceneObject> results;
  169. for (auto& selectedObjectIdx : selectedObjects)
  170. {
  171. if (selectedObjectIdx < firstGizmoIdx)
  172. {
  173. auto iterFind = idxToRenderable.find(selectedObjectIdx);
  174. if (iterFind != idxToRenderable.end())
  175. results.push_back(iterFind->second);
  176. }
  177. else
  178. {
  179. UINT32 gizmoIdx = selectedObjectIdx - firstGizmoIdx;
  180. HSceneObject so = GizmoManager::instance().getSceneObject(gizmoIdx);
  181. if (so)
  182. results.push_back(so);
  183. }
  184. }
  185. return results;
  186. }
  187. Color ScenePicking::encodeIndex(UINT32 index)
  188. {
  189. Color encoded;
  190. encoded.r = (index & 0xFF) / 255.0f;
  191. encoded.g = ((index >> 8) & 0xFF) / 255.0f;
  192. encoded.b = ((index >> 16) & 0xFF) / 255.0f;
  193. encoded.a = 1.0f;
  194. if (((index >> 24) & 0xFF))
  195. LOGERR("Index when picking out of valid range.");
  196. return encoded;
  197. }
  198. UINT32 ScenePicking::decodeIndex(Color color)
  199. {
  200. UINT32 r = Math::roundToInt(color.r * 255.0f);
  201. UINT32 g = Math::roundToInt(color.g * 255.0f);
  202. UINT32 b = Math::roundToInt(color.b * 255.0f);
  203. return (r & 0xFF) | ((g & 0xFF) << 8) | ((b & 0xFF) << 16);
  204. }
  205. void ScenePickingCore::initialize()
  206. {
  207. for (UINT32 i = 0; i < 3; i++)
  208. {
  209. MaterialData& md = mMaterialData[i];
  210. {
  211. md.mPickingParams = md.mMatPickingCore->createParamsSet();
  212. SPtr<GpuParamsCore> vertParams = md.mPickingParams->getGpuParams(GPT_VERTEX_PROGRAM);
  213. SPtr<GpuParamsCore> fragParams = md.mPickingParams->getGpuParams(GPT_FRAGMENT_PROGRAM);
  214. vertParams->getParam("matWorldViewProj", md.mParamPickingWVP);
  215. fragParams->getParam("colorIndex", md.mParamPickingColor);
  216. }
  217. {
  218. md.mPickingAlphaParams = md.mMatPickingAlphaCore->createParamsSet();
  219. SPtr<GpuParamsCore> vertParams = md.mPickingAlphaParams->getGpuParams(GPT_VERTEX_PROGRAM);
  220. SPtr<GpuParamsCore> fragParams = md.mPickingAlphaParams->getGpuParams(GPT_FRAGMENT_PROGRAM);
  221. vertParams->getParam("matWorldViewProj", md.mParamPickingAlphaWVP);
  222. fragParams->getParam("colorIndex", md.mParamPickingAlphaColor);
  223. fragParams->getTextureParam("mainTexture", md.mParamPickingAlphaTexture);
  224. GpuParamFloatCore alphaCutoffParam;
  225. fragParams->getParam("alphaCutoff", alphaCutoffParam);
  226. alphaCutoffParam.set(ALPHA_CUTOFF);
  227. }
  228. }
  229. }
  230. void ScenePickingCore::destroy()
  231. {
  232. bs_delete(this);
  233. }
  234. void ScenePickingCore::corePickingBegin(const SPtr<RenderTargetCore>& target, const Rect2& viewportArea,
  235. const ScenePicking::RenderableSet& renderables, const Vector2I& position, const Vector2I& area)
  236. {
  237. RenderAPICore& rs = RenderAPICore::instance();
  238. SPtr<RenderTextureCore> rtt = std::static_pointer_cast<RenderTextureCore>(target);
  239. SPtr<TextureCore> outputTexture = rtt->getBindableColorTexture();
  240. TextureProperties outputTextureProperties = outputTexture->getProperties();
  241. SPtr<TextureCore> normalsTexture = TextureCore::create(TEX_TYPE_2D, outputTextureProperties.getWidth(),
  242. outputTextureProperties.getHeight(), 0, PF_R8G8B8A8, TU_RENDERTARGET, false, 1);
  243. SPtr<TextureCore> depthTexture = rtt->getBindableDepthStencilTexture();
  244. MULTI_RENDER_TEXTURE_CORE_DESC pickingMRT;
  245. pickingMRT.colorSurfaces.resize(2);
  246. pickingMRT.colorSurfaces[0].face = 0;
  247. pickingMRT.colorSurfaces[0].texture = outputTexture;
  248. pickingMRT.colorSurfaces[1].face = 0;
  249. pickingMRT.colorSurfaces[1].texture = normalsTexture;
  250. pickingMRT.depthStencilSurface.face = 0;
  251. pickingMRT.depthStencilSurface.texture = depthTexture;
  252. mPickingTexture = MultiRenderTextureCore::create(pickingMRT);
  253. rs.beginFrame();
  254. rs.setRenderTarget(mPickingTexture);
  255. rs.setViewport(viewportArea);
  256. rs.clearRenderTarget(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::White);
  257. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  258. gRendererUtility().setPass(mMaterialData[0].mMatPickingCore, 0);
  259. gRendererUtility().setPassParams(mMaterialData[0].mPickingParams, 0);
  260. bool activeMaterialIsAlpha = false;
  261. CullingMode activeMaterialCull = (CullingMode)0;
  262. for (auto& renderable : renderables)
  263. {
  264. if (activeMaterialIsAlpha != renderable.alpha || activeMaterialCull != renderable.cullMode)
  265. {
  266. activeMaterialIsAlpha = renderable.alpha;
  267. activeMaterialCull = renderable.cullMode;
  268. if (activeMaterialIsAlpha)
  269. gRendererUtility().setPass(mMaterialData[(UINT32)activeMaterialCull].mMatPickingAlphaCore, 0);
  270. else
  271. gRendererUtility().setPass(mMaterialData[(UINT32)activeMaterialCull].mMatPickingCore, 0);
  272. }
  273. Color color = ScenePicking::encodeIndex(renderable.index);
  274. MaterialData& md = mMaterialData[(UINT32)activeMaterialCull];
  275. if (activeMaterialIsAlpha)
  276. {
  277. md.mParamPickingAlphaWVP.set(renderable.wvpTransform);
  278. md.mParamPickingAlphaColor.set(color);
  279. md.mParamPickingAlphaTexture.set(renderable.mainTexture->getCore());
  280. gRendererUtility().setPassParams(md.mPickingAlphaParams);
  281. }
  282. else
  283. {
  284. md.mParamPickingWVP.set(renderable.wvpTransform);
  285. md.mParamPickingColor.set(color);
  286. gRendererUtility().setPassParams(md.mPickingParams);
  287. }
  288. UINT32 numSubmeshes = renderable.mesh->getProperties().getNumSubMeshes();
  289. for (UINT32 i = 0; i < numSubmeshes; i++)
  290. gRendererUtility().draw(renderable.mesh, renderable.mesh->getProperties().getSubMesh(i));
  291. }
  292. }
  293. void ScenePickingCore::corePickingEnd(const SPtr<RenderTargetCore>& target, const Rect2& viewportArea, const Vector2I& position,
  294. const Vector2I& area, bool gatherSnapData, AsyncOp& asyncOp)
  295. {
  296. const RenderTargetProperties& rtProps = target->getProperties();
  297. RenderAPICore& rs = RenderAPICore::instance();
  298. rs.endFrame();
  299. rs.setRenderTarget(nullptr);
  300. if (rtProps.isWindow())
  301. {
  302. // TODO: When I do implement this then I will likely want a method in RenderTarget that unifies both render window and render texture readback
  303. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  304. }
  305. SPtr<TextureCore> outputTexture = mPickingTexture->getBindableColorTexture(0)->getTexture();
  306. SPtr<TextureCore> normalsTexture = mPickingTexture->getBindableColorTexture(1)->getTexture();
  307. SPtr<TextureCore> depthTexture = mPickingTexture->getBindableDepthStencilTexture()->getTexture();
  308. if (position.x < 0 || position.x >= (INT32)outputTexture->getProperties().getWidth() ||
  309. position.y < 0 || position.y >= (INT32)outputTexture->getProperties().getHeight())
  310. {
  311. mPickingTexture = nullptr;
  312. asyncOp._completeOperation(Vector<UINT32>());
  313. return;
  314. }
  315. SPtr<PixelData> outputPixelData = outputTexture->getProperties().allocateSubresourceBuffer(0);
  316. SPtr<PixelData> normalsPixelData;
  317. SPtr<PixelData> depthPixelData;
  318. if (gatherSnapData)
  319. {
  320. normalsPixelData = normalsTexture->getProperties().allocateSubresourceBuffer(0);
  321. depthPixelData = depthTexture->getProperties().allocateSubresourceBuffer(0);
  322. }
  323. outputTexture->readSubresource(0, *outputPixelData);
  324. Map<UINT32, UINT32> selectionScores;
  325. UINT32 maxWidth = std::min((UINT32)(position.x + area.x), outputPixelData->getWidth());
  326. UINT32 maxHeight = std::min((UINT32)(position.y + area.y), outputPixelData->getHeight());
  327. if (rtProps.requiresTextureFlipping())
  328. {
  329. UINT32 vertOffset = outputPixelData->getHeight() - 1;
  330. for (UINT32 y = maxHeight; y > (UINT32)position.y; y--)
  331. {
  332. for (UINT32 x = (UINT32)position.x; x < maxWidth; x++)
  333. {
  334. Color color = outputPixelData->getColorAt(x, vertOffset - y);
  335. UINT32 index = ScenePicking::decodeIndex(color);
  336. if (index == 0x00FFFFFF) // Nothing selected
  337. continue;
  338. auto iterFind = selectionScores.find(index);
  339. if (iterFind == selectionScores.end())
  340. selectionScores[index] = 1;
  341. else
  342. iterFind->second++;
  343. }
  344. }
  345. }
  346. else
  347. {
  348. for (UINT32 y = (UINT32)position.y; y < maxHeight; y++)
  349. {
  350. for (UINT32 x = (UINT32)position.x; x < maxWidth; x++)
  351. {
  352. Color color = outputPixelData->getColorAt(x, y);
  353. UINT32 index = ScenePicking::decodeIndex(color);
  354. if (index == 0x00FFFFFF) // Nothing selected
  355. continue;
  356. auto iterFind = selectionScores.find(index);
  357. if (iterFind == selectionScores.end())
  358. selectionScores[index] = 1;
  359. else
  360. iterFind->second++;
  361. }
  362. }
  363. }
  364. // Sort by score
  365. struct SelectedObject { UINT32 index; UINT32 score; };
  366. Vector<SelectedObject> selectedObjects(selectionScores.size());
  367. UINT32 idx = 0;
  368. for (auto& selectionScore : selectionScores)
  369. {
  370. selectedObjects[idx++] = { selectionScore.first, selectionScore.second };
  371. }
  372. std::sort(selectedObjects.begin(), selectedObjects.end(),
  373. [&](const SelectedObject& a, const SelectedObject& b)
  374. {
  375. return b.score < a.score;
  376. });
  377. Vector<UINT32> objects;
  378. for (auto& selectedObject : selectedObjects)
  379. objects.push_back(selectedObject.index);
  380. PickResults result;
  381. if (gatherSnapData)
  382. {
  383. depthTexture->readSubresource(0, *depthPixelData);
  384. normalsTexture->readSubresource(0, *normalsPixelData);
  385. Vector2I samplePixel = position;
  386. if (rtProps.requiresTextureFlipping())
  387. samplePixel.y = depthPixelData->getHeight() - samplePixel.y;
  388. float depth = depthPixelData->getDepthAt(samplePixel.x, samplePixel.y);
  389. Color normal = normalsPixelData->getColorAt(samplePixel.x, samplePixel.y);
  390. const RenderAPIInfo& rapiInfo = rs.getAPIInfo();
  391. float max = rapiInfo.getMaximumDepthInputValue();
  392. float min = rapiInfo.getMinimumDepthInputValue();
  393. depth = depth * Math::abs(max - min) + min;
  394. result.depth = depth;
  395. result.normal = Vector3((normal.r * 2) - 1, (normal.g * 2) - 1, (normal.b * 2) - 1);
  396. }
  397. mPickingTexture = nullptr;
  398. result.objects = objects;
  399. asyncOp._completeOperation(result);
  400. }
  401. }