BsScenePicking.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 "BsRenderTexture.h"
  20. #include "BsPixelData.h"
  21. #include "BsGpuParams.h"
  22. #include "BsGpuParamsSet.h"
  23. #include "BsBuiltinEditorResources.h"
  24. #include "BsShader.h"
  25. #include "BsCoreRenderer.h"
  26. #include "BsGizmoManager.h"
  27. #include "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 (int i = 0; i < 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. {
  131. const Map<String, SHADER_OBJECT_PARAM_DESC>& textureParams = originalMat->getShader()->getTextureParams();
  132. for (auto& objectParam : textureParams)
  133. {
  134. if (objectParam.second.rendererSemantic == ct::RPS_Diffuse)
  135. {
  136. mainTexture = originalMat->getTexture(objectParam.first);
  137. break;
  138. }
  139. }
  140. }
  141. idxToRenderable[idx] = so;
  142. Matrix4 wvpTransform = viewProjMatrix * worldTransform;
  143. pickData.insert({ mesh->getCore(), idx, wvpTransform, useAlphaShader, cullMode, mainTexture });
  144. }
  145. }
  146. }
  147. }
  148. UINT32 firstGizmoIdx = (UINT32)pickData.size();
  149. SPtr<ct::RenderTarget> target = cam->getViewport()->getTarget()->getCore();
  150. gCoreThread().queueCommand(std::bind(&ct::ScenePicking::corePickingBegin, mCore, target,
  151. cam->getViewport()->getNormArea(), std::cref(pickData), position, area));
  152. GizmoManager::instance().renderForPicking(cam, [&](UINT32 inputIdx) { return encodeIndex(firstGizmoIdx + inputIdx); });
  153. AsyncOp op = gCoreThread().queueReturnCommand(std::bind(&ct::ScenePicking::corePickingEnd, mCore, target,
  154. cam->getViewport()->getNormArea(), position, area, data != nullptr, _1));
  155. gCoreThread().submit(true);
  156. assert(op.hasCompleted());
  157. PickResults pickResults = op.getReturnValue<PickResults>();
  158. if (data != nullptr)
  159. {
  160. data->pickPosition = cam->screenToWorldPointDeviceDepth(position, pickResults.depth);
  161. data->normal = pickResults.normal;
  162. }
  163. Vector<UINT32> selectedObjects = pickResults.objects;
  164. Vector<HSceneObject> results;
  165. for (auto& selectedObjectIdx : selectedObjects)
  166. {
  167. if (selectedObjectIdx < firstGizmoIdx)
  168. {
  169. auto iterFind = idxToRenderable.find(selectedObjectIdx);
  170. if (iterFind != idxToRenderable.end())
  171. results.push_back(iterFind->second);
  172. }
  173. else
  174. {
  175. UINT32 gizmoIdx = selectedObjectIdx - firstGizmoIdx;
  176. HSceneObject so = GizmoManager::instance().getSceneObject(gizmoIdx);
  177. if (so)
  178. results.push_back(so);
  179. }
  180. }
  181. return results;
  182. }
  183. Color ScenePicking::encodeIndex(UINT32 index)
  184. {
  185. Color encoded;
  186. encoded.r = (index & 0xFF) / 255.0f;
  187. encoded.g = ((index >> 8) & 0xFF) / 255.0f;
  188. encoded.b = ((index >> 16) & 0xFF) / 255.0f;
  189. encoded.a = 1.0f;
  190. if (((index >> 24) & 0xFF))
  191. LOGERR("Index when picking out of valid range.");
  192. return encoded;
  193. }
  194. UINT32 ScenePicking::decodeIndex(Color color)
  195. {
  196. UINT32 r = Math::roundToInt(color.r * 255.0f);
  197. UINT32 g = Math::roundToInt(color.g * 255.0f);
  198. UINT32 b = Math::roundToInt(color.b * 255.0f);
  199. return (r & 0xFF) | ((g & 0xFF) << 8) | ((b & 0xFF) << 16);
  200. }
  201. namespace ct
  202. {
  203. const float ScenePicking::ALPHA_CUTOFF = 0.5f;
  204. PickingParamBlockDef gPickingParamBlockDef;
  205. void ScenePicking::initialize()
  206. {
  207. // Do nothing
  208. }
  209. void ScenePicking::destroy()
  210. {
  211. bs_delete(this);
  212. }
  213. void ScenePicking::corePickingBegin(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  214. const bs::ScenePicking::RenderableSet& renderables, const Vector2I& position, const Vector2I& area)
  215. {
  216. RenderAPI& rs = RenderAPI::instance();
  217. SPtr<RenderTexture> rtt = std::static_pointer_cast<RenderTexture>(target);
  218. SPtr<Texture> outputTexture = rtt->getColorTexture(0);
  219. TextureProperties outputTextureProperties = outputTexture->getProperties();
  220. TEXTURE_DESC normalTexDesc;
  221. normalTexDesc.type = TEX_TYPE_2D;
  222. normalTexDesc.width = outputTextureProperties.getWidth();
  223. normalTexDesc.height = outputTextureProperties.getHeight();
  224. normalTexDesc.format = PF_R8G8B8A8;
  225. normalTexDesc.usage = TU_RENDERTARGET;
  226. SPtr<Texture> normalsTexture = Texture::create(normalTexDesc);
  227. SPtr<Texture> depthTexture = rtt->getDepthStencilTexture();
  228. RENDER_TEXTURE_DESC pickingMRT;
  229. pickingMRT.colorSurfaces[0].face = 0;
  230. pickingMRT.colorSurfaces[0].texture = outputTexture;
  231. pickingMRT.colorSurfaces[1].face = 0;
  232. pickingMRT.colorSurfaces[1].texture = normalsTexture;
  233. pickingMRT.depthStencilSurface.face = 0;
  234. pickingMRT.depthStencilSurface.texture = depthTexture;
  235. mPickingTexture = RenderTexture::create(pickingMRT);
  236. rs.setRenderTarget(mPickingTexture);
  237. rs.setViewport(viewportArea);
  238. rs.clearRenderTarget(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::White);
  239. rs.setScissorRect(position.x, position.y, position.x + area.x, position.y + area.y);
  240. gRendererUtility().setPass(mMaterials[0]);
  241. UINT32 numEntries = (UINT32)renderables.size();
  242. UINT32* renderableIndices = bs_stack_alloc<UINT32>(numEntries);
  243. UINT32 typeCounters[6];
  244. bs_zero_out(typeCounters);
  245. UINT32 idx = 0;
  246. for (auto& renderable : renderables)
  247. {
  248. UINT32 typeIdx;
  249. if (!renderable.alpha)
  250. typeIdx = 0;
  251. else
  252. typeIdx = 3;
  253. typeIdx += (UINT32)renderable.cullMode;
  254. UINT32 renderableIdx = typeCounters[typeIdx];
  255. renderableIndices[idx] = renderableIdx;
  256. SPtr<GpuParamsSet> paramsSet;
  257. if (renderableIdx >= mParamSets[typeIdx].size())
  258. {
  259. paramsSet = mMaterials[typeIdx]->createParamsSet();
  260. mParamSets[typeIdx].push_back(paramsSet);
  261. }
  262. else
  263. paramsSet = mParamSets[typeIdx][renderableIdx];
  264. SPtr<GpuParamBlockBuffer> paramBuffer;
  265. if (idx >= mParamBuffers.size())
  266. {
  267. paramBuffer = gPickingParamBlockDef.createBuffer();
  268. mParamBuffers.push_back(paramBuffer);
  269. }
  270. else
  271. paramBuffer = mParamBuffers[idx];
  272. paramsSet->setParamBlockBuffer("Uniforms", paramBuffer, true);
  273. Color color = bs::ScenePicking::encodeIndex(renderable.index);
  274. gPickingParamBlockDef.gMatViewProj.set(paramBuffer, renderable.wvpTransform);
  275. gPickingParamBlockDef.gAlphaCutoff.set(paramBuffer, ALPHA_CUTOFF);
  276. gPickingParamBlockDef.gColorIndex.set(paramBuffer, color);
  277. typeCounters[typeIdx]++;
  278. idx++;
  279. }
  280. UINT32 activeMaterialIdx = 0;
  281. idx = 0;
  282. for (auto& renderable : renderables)
  283. {
  284. UINT32 typeIdx;
  285. if (!renderable.alpha)
  286. typeIdx = 0;
  287. else
  288. typeIdx = 3;
  289. typeIdx += (UINT32)renderable.cullMode;
  290. if (activeMaterialIdx != typeIdx)
  291. {
  292. gRendererUtility().setPass(mMaterials[typeIdx]);
  293. activeMaterialIdx = typeIdx;
  294. }
  295. UINT32 renderableIdx = renderableIndices[idx];
  296. gRendererUtility().setPassParams(mParamSets[typeIdx][renderableIdx]);
  297. UINT32 numSubmeshes = renderable.mesh->getProperties().getNumSubMeshes();
  298. for (UINT32 i = 0; i < numSubmeshes; i++)
  299. gRendererUtility().draw(renderable.mesh, renderable.mesh->getProperties().getSubMesh(i));
  300. idx++;
  301. }
  302. bs_stack_free(renderableIndices);
  303. }
  304. void ScenePicking::corePickingEnd(const SPtr<RenderTarget>& target, const Rect2& viewportArea,
  305. const Vector2I& position, const Vector2I& area, bool gatherSnapData, AsyncOp& asyncOp)
  306. {
  307. const RenderTargetProperties& rtProps = target->getProperties();
  308. RenderAPI& rs = RenderAPI::instance();
  309. rs.setRenderTarget(nullptr);
  310. rs.submitCommandBuffer(nullptr);
  311. if (rtProps.isWindow())
  312. {
  313. BS_EXCEPT(NotImplementedException, "Picking is not supported on render windows as framebuffer readback methods aren't implemented");
  314. }
  315. SPtr<Texture> outputTexture = mPickingTexture->getColorTexture(0);
  316. SPtr<Texture> normalsTexture = mPickingTexture->getColorTexture(1);
  317. SPtr<Texture> depthTexture = mPickingTexture->getDepthStencilTexture();
  318. if (position.x < 0 || position.x >= (INT32)outputTexture->getProperties().getWidth() ||
  319. position.y < 0 || position.y >= (INT32)outputTexture->getProperties().getHeight())
  320. {
  321. mPickingTexture = nullptr;
  322. asyncOp._completeOperation(Vector<UINT32>());
  323. return;
  324. }
  325. SPtr<PixelData> outputPixelData = outputTexture->getProperties().allocBuffer(0, 0);
  326. SPtr<PixelData> normalsPixelData;
  327. SPtr<PixelData> depthPixelData;
  328. if (gatherSnapData)
  329. {
  330. normalsPixelData = normalsTexture->getProperties().allocBuffer(0, 0);
  331. depthPixelData = depthTexture->getProperties().allocBuffer(0, 0);
  332. }
  333. outputTexture->readData(*outputPixelData);
  334. Map<UINT32, UINT32> selectionScores;
  335. UINT32 maxWidth = std::min((UINT32)(position.x + area.x), outputPixelData->getWidth());
  336. UINT32 maxHeight = std::min((UINT32)(position.y + area.y), outputPixelData->getHeight());
  337. if (rtProps.requiresTextureFlipping())
  338. {
  339. UINT32 vertOffset = outputPixelData->getHeight();
  340. for (UINT32 y = maxHeight; y > (UINT32)position.y; y--)
  341. {
  342. for (UINT32 x = (UINT32)position.x; x < maxWidth; x++)
  343. {
  344. Color color = outputPixelData->getColorAt(x, vertOffset - y);
  345. UINT32 index = bs::ScenePicking::decodeIndex(color);
  346. if (index == 0x00FFFFFF) // Nothing selected
  347. continue;
  348. auto iterFind = selectionScores.find(index);
  349. if (iterFind == selectionScores.end())
  350. selectionScores[index] = 1;
  351. else
  352. iterFind->second++;
  353. }
  354. }
  355. }
  356. else
  357. {
  358. for (UINT32 y = (UINT32)position.y; y < maxHeight; y++)
  359. {
  360. for (UINT32 x = (UINT32)position.x; x < maxWidth; x++)
  361. {
  362. Color color = outputPixelData->getColorAt(x, y);
  363. UINT32 index = bs::ScenePicking::decodeIndex(color);
  364. if (index == 0x00FFFFFF) // Nothing selected
  365. continue;
  366. auto iterFind = selectionScores.find(index);
  367. if (iterFind == selectionScores.end())
  368. selectionScores[index] = 1;
  369. else
  370. iterFind->second++;
  371. }
  372. }
  373. }
  374. // Sort by score
  375. struct SelectedObject { UINT32 index; UINT32 score; };
  376. Vector<SelectedObject> selectedObjects(selectionScores.size());
  377. UINT32 idx = 0;
  378. for (auto& selectionScore : selectionScores)
  379. {
  380. selectedObjects[idx++] = { selectionScore.first, selectionScore.second };
  381. }
  382. std::sort(selectedObjects.begin(), selectedObjects.end(),
  383. [&](const SelectedObject& a, const SelectedObject& b)
  384. {
  385. return b.score < a.score;
  386. });
  387. Vector<UINT32> objects;
  388. for (auto& selectedObject : selectedObjects)
  389. objects.push_back(selectedObject.index);
  390. PickResults result;
  391. if (gatherSnapData)
  392. {
  393. depthTexture->readData(*depthPixelData);
  394. normalsTexture->readData(*normalsPixelData);
  395. Vector2I samplePixel = position;
  396. if (rtProps.requiresTextureFlipping())
  397. samplePixel.y = depthPixelData->getHeight() - samplePixel.y;
  398. float depth = depthPixelData->getDepthAt(samplePixel.x, samplePixel.y);
  399. Color normal = normalsPixelData->getColorAt(samplePixel.x, samplePixel.y);
  400. const RenderAPIInfo& rapiInfo = rs.getAPIInfo();
  401. float max = rapiInfo.getMaximumDepthInputValue();
  402. float min = rapiInfo.getMinimumDepthInputValue();
  403. depth = depth * Math::abs(max - min) + min;
  404. result.depth = depth;
  405. result.normal = Vector3((normal.r * 2) - 1, (normal.g * 2) - 1, (normal.b * 2) - 1);
  406. }
  407. mPickingTexture = nullptr;
  408. result.objects = objects;
  409. asyncOp._completeOperation(result);
  410. }
  411. }
  412. }