BsScenePicking.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Scene/BsScenePicking.h"
  4. #include "Scene/BsSceneManager.h"
  5. #include "Image/BsColor.h"
  6. #include "Math/BsMatrix4.h"
  7. #include "Debug/BsDebug.h"
  8. #include "Math/BsMath.h"
  9. #include "Components/BsCRenderable.h"
  10. #include "Scene/BsSceneObject.h"
  11. #include "Mesh/BsMesh.h"
  12. #include "Math/BsConvexVolume.h"
  13. #include "Components/BsCCamera.h"
  14. #include "CoreThread/BsCoreThread.h"
  15. #include "RenderAPI/BsRenderAPI.h"
  16. #include "Material/BsMaterial.h"
  17. #include "Material/BsPass.h"
  18. #include "RenderAPI/BsRasterizerState.h"
  19. #include "RenderAPI/BsRenderTexture.h"
  20. #include "Image/BsPixelData.h"
  21. #include "RenderAPI/BsGpuParams.h"
  22. #include "Material/BsGpuParamsSet.h"
  23. #include "Utility/BsBuiltinEditorResources.h"
  24. #include "Material/BsShader.h"
  25. #include "Renderer/BsRenderer.h"
  26. #include "Scene/BsGizmoManager.h"
  27. #include "Renderer/BsRendererUtility.h"
  28. using namespace std::placeholders;
  29. namespace bs
  30. {
  31. ScenePicking::ScenePicking()
  32. {
  33. mCore = bs_new<ct::ScenePicking>();
  34. for (UINT32 i = 0; i < 3; i++)
  35. {
  36. HMaterial matPicking = BuiltinEditorResources::instance().createPicking((CullingMode)i);
  37. HMaterial matPickingAlpha = BuiltinEditorResources::instance().createPickingAlpha((CullingMode)i);
  38. mCore->mMaterials[i] = matPicking->getCore();
  39. mCore->mMaterials[3 + i] = matPickingAlpha->getCore();
  40. }
  41. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::initialize, mCore));
  42. }
  43. ScenePicking::~ScenePicking()
  44. {
  45. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::destroy, mCore));
  46. }
  47. HSceneObject ScenePicking::pickClosestObject(const SPtr<Camera>& cam, const Vector2I& position, const Vector2I& area,
  48. Vector<HSceneObject>& ignoreRenderables, SnapData* data)
  49. {
  50. Vector<HSceneObject> selectedObjects = pickObjects(cam, position, area, ignoreRenderables, data);
  51. if (selectedObjects.size() == 0)
  52. return HSceneObject();
  53. if (data != nullptr)
  54. {
  55. Matrix3 rotation;
  56. selectedObjects[0]->getWorldRotation().toRotationMatrix(rotation);
  57. data->normal = rotation.inverse().transpose().transform(data->normal);
  58. }
  59. return selectedObjects[0];
  60. }
  61. Vector<HSceneObject> ScenePicking::pickObjects(const SPtr<Camera>& cam, const Vector2I& position, const Vector2I& area,
  62. Vector<HSceneObject>& ignoreRenderables, SnapData* data)
  63. {
  64. auto comparePickElement = [&] (const ScenePicking::RenderablePickData& a, const ScenePicking::RenderablePickData& b)
  65. {
  66. // Sort by alpha setting first, then by cull mode, then by index
  67. if (a.alpha == b.alpha)
  68. {
  69. if (a.cullMode == b.cullMode)
  70. return a.index > b.index;
  71. else
  72. return (UINT32)a.cullMode > (UINT32)b.cullMode;
  73. }
  74. else
  75. return (UINT32)a.alpha > (UINT32)b.alpha;
  76. };
  77. Matrix4 viewProjMatrix = cam->getProjectionMatrixRS() * cam->getViewMatrix();
  78. const Map<Renderable*, SceneRenderableData>& renderables = SceneManager::instance().getAllRenderables();
  79. RenderableSet pickData(comparePickElement);
  80. Map<UINT32, HSceneObject> idxToRenderable;
  81. for (auto& renderableData : renderables)
  82. {
  83. SPtr<Renderable> renderable = renderableData.second.renderable;
  84. HSceneObject so = renderableData.second.sceneObject;
  85. if (!so->getActive())
  86. continue;
  87. HMesh mesh = renderable->getMesh();
  88. if (!mesh.isLoaded())
  89. continue;
  90. bool found = false;
  91. for (UINT32 i = 0; i < (UINT32)ignoreRenderables.size(); i++)
  92. {
  93. if (ignoreRenderables[i] == so)
  94. {
  95. found = true;
  96. break;
  97. }
  98. }
  99. if (found)
  100. continue;
  101. Bounds worldBounds = mesh->getProperties().getBounds();
  102. Matrix4 worldTransform = so->getWorldTfrm();
  103. worldBounds.transformAffine(worldTransform);
  104. const ConvexVolume& frustum = cam->getWorldFrustum();
  105. if (frustum.intersects(worldBounds.getSphere()))
  106. {
  107. // More precise with the box
  108. if (frustum.intersects(worldBounds.getBox()))
  109. {
  110. for (UINT32 i = 0; i < mesh->getProperties().getNumSubMeshes(); i++)
  111. {
  112. UINT32 idx = (UINT32)pickData.size();
  113. bool useAlphaShader = false;
  114. SPtr<RasterizerState> rasterizerState;
  115. HMaterial originalMat = renderable->getMaterial(i);
  116. if (originalMat != nullptr && originalMat->getNumPasses() > 0)
  117. {
  118. SPtr<Pass> firstPass = originalMat->getPass(0); // Note: We only ever check the first pass, problem?
  119. useAlphaShader = firstPass->hasBlending();
  120. if (firstPass->getRasterizerState() == nullptr)
  121. rasterizerState = RasterizerState::getDefault();
  122. else
  123. rasterizerState = firstPass->getRasterizerState();
  124. }
  125. else
  126. rasterizerState = RasterizerState::getDefault();
  127. CullingMode cullMode = rasterizerState->getProperties().getCullMode();
  128. HTexture mainTexture;
  129. if (useAlphaShader)
  130. mainTexture = originalMat->getTexture("gAlbedoTex");
  131. idxToRenderable[idx] = so;
  132. Matrix4 wvpTransform = viewProjMatrix * worldTransform;
  133. pickData.insert({ mesh->getCore(), idx, wvpTransform, useAlphaShader, cullMode, mainTexture });
  134. }
  135. }
  136. }
  137. }
  138. UINT32 firstGizmoIdx = (UINT32)pickData.size();
  139. SPtr<ct::RenderTarget> target = cam->getViewport()->getTarget()->getCore();
  140. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::corePickingBegin, mCore, target,
  141. cam->getViewport()->getArea(), std::cref(pickData), position, area));
  142. GizmoManager::instance().renderForPicking(cam, [&](UINT32 inputIdx) { return encodeIndex(firstGizmoIdx + inputIdx); });
  143. AsyncOp op = gCoreThread().queueReturnCommand(std::bind(&ct::ScenePicking::corePickingEnd, mCore, target,
  144. cam->getViewport()->getArea(), position, area, data != nullptr, _1));
  145. gCoreThread().submit(true);
  146. assert(op.hasCompleted());
  147. PickResults pickResults = op.getReturnValue<PickResults>();
  148. if (data != nullptr)
  149. {
  150. data->pickPosition = cam->screenToWorldPointDeviceDepth(position, pickResults.depth);
  151. data->normal = pickResults.normal;
  152. }
  153. Vector<UINT32> selectedObjects = pickResults.objects;
  154. Vector<HSceneObject> results;
  155. for (auto& selectedObjectIdx : selectedObjects)
  156. {
  157. if (selectedObjectIdx < firstGizmoIdx)
  158. {
  159. auto iterFind = idxToRenderable.find(selectedObjectIdx);
  160. if (iterFind != idxToRenderable.end())
  161. results.push_back(iterFind->second);
  162. }
  163. else
  164. {
  165. UINT32 gizmoIdx = selectedObjectIdx - firstGizmoIdx;
  166. HSceneObject so = GizmoManager::instance().getSceneObject(gizmoIdx);
  167. if (so)
  168. results.push_back(so);
  169. }
  170. }
  171. return results;
  172. }
  173. Color ScenePicking::encodeIndex(UINT32 index)
  174. {
  175. Color encoded;
  176. encoded.r = (index & 0xFF) / 255.0f;
  177. encoded.g = ((index >> 8) & 0xFF) / 255.0f;
  178. encoded.b = ((index >> 16) & 0xFF) / 255.0f;
  179. encoded.a = 1.0f;
  180. if (((index >> 24) & 0xFF))
  181. LOGERR("Index when picking out of valid range.");
  182. return encoded;
  183. }
  184. UINT32 ScenePicking::decodeIndex(Color color)
  185. {
  186. UINT32 r = Math::roundToInt(color.r * 255.0f);
  187. UINT32 g = Math::roundToInt(color.g * 255.0f);
  188. UINT32 b = Math::roundToInt(color.b * 255.0f);
  189. return (r & 0xFF) | ((g & 0xFF) << 8) | ((b & 0xFF) << 16);
  190. }
  191. namespace ct
  192. {
  193. const float ScenePicking::ALPHA_CUTOFF = 0.5f;
  194. PickingParamBlockDef gPickingParamBlockDef;
  195. void ScenePicking::initialize()
  196. {
  197. // Do nothing
  198. }
  199. void ScenePicking::destroy()
  200. {
  201. bs_delete(this);
  202. }
  203. void ScenePicking::corePickingBegin(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  204. const bs::ScenePicking::RenderableSet& renderables, const Vector2I& position, const Vector2I& area)
  205. {
  206. RenderAPI& rs = RenderAPI::instance();
  207. SPtr<RenderTexture> rtt = std::static_pointer_cast<RenderTexture>(target);
  208. SPtr<Texture> outputTexture = rtt->getColorTexture(0);
  209. TextureProperties outputTextureProperties = outputTexture->getProperties();
  210. TEXTURE_DESC normalTexDesc;
  211. normalTexDesc.type = TEX_TYPE_2D;
  212. normalTexDesc.width = outputTextureProperties.getWidth();
  213. normalTexDesc.height = outputTextureProperties.getHeight();
  214. normalTexDesc.format = PF_RG11B10F;
  215. normalTexDesc.usage = TU_RENDERTARGET;
  216. SPtr<Texture> normalsTexture = Texture::create(normalTexDesc);
  217. SPtr<Texture> depthTexture = rtt->getDepthStencilTexture();
  218. RENDER_TEXTURE_DESC pickingMRT;
  219. pickingMRT.colorSurfaces[0].face = 0;
  220. pickingMRT.colorSurfaces[0].texture = outputTexture;
  221. pickingMRT.colorSurfaces[1].face = 0;
  222. pickingMRT.colorSurfaces[1].texture = normalsTexture;
  223. pickingMRT.depthStencilSurface.face = 0;
  224. pickingMRT.depthStencilSurface.texture = depthTexture;
  225. mPickingTexture = RenderTexture::create(pickingMRT);
  226. rs.setRenderTarget(mPickingTexture);
  227. rs.setViewport(viewportArea);
  228. rs.clearRenderTarget(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::White);
  229. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  230. gRendererUtility().setPass(mMaterials[0]);
  231. UINT32 numEntries = (UINT32)renderables.size();
  232. UINT32* renderableIndices = bs_stack_alloc<UINT32>(numEntries);
  233. UINT32 typeCounters[6];
  234. bs_zero_out(typeCounters);
  235. UINT32 idx = 0;
  236. for (auto& renderable : renderables)
  237. {
  238. UINT32 typeIdx;
  239. if (!renderable.alpha)
  240. typeIdx = 0;
  241. else
  242. typeIdx = 3;
  243. typeIdx += (UINT32)renderable.cullMode;
  244. UINT32 renderableIdx = typeCounters[typeIdx];
  245. renderableIndices[idx] = renderableIdx;
  246. SPtr<GpuParamsSet> paramsSet;
  247. if (renderableIdx >= mParamSets[typeIdx].size())
  248. {
  249. paramsSet = mMaterials[typeIdx]->createParamsSet();
  250. mParamSets[typeIdx].push_back(paramsSet);
  251. }
  252. else
  253. paramsSet = mParamSets[typeIdx][renderableIdx];
  254. SPtr<GpuParamBlockBuffer> paramBuffer;
  255. if (idx >= mParamBuffers.size())
  256. {
  257. paramBuffer = gPickingParamBlockDef.createBuffer();
  258. mParamBuffers.push_back(paramBuffer);
  259. }
  260. else
  261. paramBuffer = mParamBuffers[idx];
  262. paramsSet->setParamBlockBuffer("Uniforms", paramBuffer, true);
  263. Color color = bs::ScenePicking::encodeIndex(renderable.index);
  264. gPickingParamBlockDef.gMatViewProj.set(paramBuffer, renderable.wvpTransform);
  265. gPickingParamBlockDef.gAlphaCutoff.set(paramBuffer, ALPHA_CUTOFF);
  266. gPickingParamBlockDef.gColorIndex.set(paramBuffer, color);
  267. typeCounters[typeIdx]++;
  268. idx++;
  269. }
  270. UINT32 activeMaterialIdx = 0;
  271. idx = 0;
  272. for (auto& renderable : renderables)
  273. {
  274. UINT32 typeIdx;
  275. if (!renderable.alpha)
  276. typeIdx = 0;
  277. else
  278. typeIdx = 3;
  279. typeIdx += (UINT32)renderable.cullMode;
  280. if (activeMaterialIdx != typeIdx)
  281. {
  282. gRendererUtility().setPass(mMaterials[typeIdx]);
  283. activeMaterialIdx = typeIdx;
  284. }
  285. UINT32 renderableIdx = renderableIndices[idx];
  286. gRendererUtility().setPassParams(mParamSets[typeIdx][renderableIdx]);
  287. UINT32 numSubmeshes = renderable.mesh->getProperties().getNumSubMeshes();
  288. for (UINT32 i = 0; i < numSubmeshes; i++)
  289. gRendererUtility().draw(renderable.mesh, renderable.mesh->getProperties().getSubMesh(i));
  290. idx++;
  291. }
  292. bs_stack_free(renderableIndices);
  293. }
  294. void ScenePicking::corePickingEnd(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  295. const Vector2I& position, const Vector2I& area, bool gatherSnapData, AsyncOp& asyncOp)
  296. {
  297. const RenderTargetProperties& rtProps = target->getProperties();
  298. RenderAPI& rs = RenderAPI::instance();
  299. rs.setRenderTarget(nullptr);
  300. rs.submitCommandBuffer(nullptr);
  301. if (rtProps.isWindow)
  302. {
  303. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  304. }
  305. SPtr<Texture> outputTexture = mPickingTexture->getColorTexture(0);
  306. SPtr<Texture> normalsTexture = mPickingTexture->getColorTexture(1);
  307. SPtr<Texture> depthTexture = mPickingTexture->getDepthStencilTexture();
  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().allocBuffer(0, 0);
  316. SPtr<PixelData> normalsPixelData;
  317. SPtr<PixelData> depthPixelData;
  318. if (gatherSnapData)
  319. {
  320. normalsPixelData = normalsTexture->getProperties().allocBuffer(0, 0);
  321. depthPixelData = depthTexture->getProperties().allocBuffer(0, 0);
  322. }
  323. outputTexture->readData(*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();
  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 = bs::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 = bs::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->readData(*depthPixelData);
  384. normalsTexture->readData(*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. }
  402. }