PointCloudOctree.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  1. import * as THREE from "../libs/three.js/build/three.module.js";
  2. import {PointCloudTree, PointCloudTreeNode} from "./PointCloudTree.js";
  3. import {PointCloudOctreeGeometryNode} from "./PointCloudOctreeGeometry.js";
  4. import {Utils} from "./utils.js";
  5. import {PointCloudMaterial} from "./materials/PointCloudMaterial.js";
  6. //见ExtendPointCloudOctree
  7. export class PointCloudOctreeNode extends PointCloudTreeNode {
  8. constructor () {
  9. super();
  10. //this.children = {};
  11. this.children = [];
  12. this.sceneNode = null;
  13. this.octree = null;
  14. }
  15. getNumPoints () {
  16. return this.geometryNode.numPoints;
  17. }
  18. isLoaded () {
  19. return true;
  20. }
  21. isTreeNode () {
  22. return true;
  23. }
  24. isGeometryNode () {
  25. return false;
  26. }
  27. getLevel () {
  28. return this.geometryNode.level;
  29. }
  30. getBoundingSphere () {
  31. return this.geometryNode.boundingSphere;
  32. }
  33. getBoundingBox () {
  34. return this.geometryNode.boundingBox;
  35. }
  36. getChildren () {
  37. let children = [];
  38. for (let i = 0; i < 8; i++) {
  39. if (this.children[i]) {
  40. children.push(this.children[i]);
  41. }
  42. }
  43. return children;
  44. }
  45. getPointsInBox(boxNode){
  46. if(!this.sceneNode){
  47. return null;
  48. }
  49. let buffer = this.geometryNode.buffer;
  50. let posOffset = buffer.offset("position");
  51. let stride = buffer.stride;
  52. let view = new DataView(buffer.data);
  53. let worldToBox = boxNode.matrixWorld.clone().invert();
  54. let objectToBox = new THREE.Matrix4().multiplyMatrices(worldToBox, this.sceneNode.matrixWorld);
  55. let inBox = [];
  56. let pos = new THREE.Vector4();
  57. for(let i = 0; i < buffer.numElements; i++){
  58. let x = view.getFloat32(i * stride + posOffset + 0, true);
  59. let y = view.getFloat32(i * stride + posOffset + 4, true);
  60. let z = view.getFloat32(i * stride + posOffset + 8, true);
  61. pos.set(x, y, z, 1);
  62. pos.applyMatrix4(objectToBox);
  63. if(-0.5 < pos.x && pos.x < 0.5){
  64. if(-0.5 < pos.y && pos.y < 0.5){
  65. if(-0.5 < pos.z && pos.z < 0.5){
  66. pos.set(x, y, z, 1).applyMatrix4(this.sceneNode.matrixWorld);
  67. inBox.push(new THREE.Vector3(pos.x, pos.y, pos.z));
  68. }
  69. }
  70. }
  71. }
  72. return inBox;
  73. }
  74. get name () {
  75. return this.geometryNode.name;
  76. }
  77. };
  78. export class PointCloudOctree extends PointCloudTree {//base
  79. constructor (geometry, material) {
  80. super();
  81. this.pointBudget = Infinity; //一直是这个值
  82. this.pcoGeometry = geometry;
  83. this.boundingBox = this.pcoGeometry.boundingBox;
  84. this.boundingSphere = this.boundingBox.getBoundingSphere(new THREE.Sphere());
  85. this.material = material || new PointCloudMaterial();
  86. this.visiblePointsTarget = 2 * 1000 * 1000;
  87. this.minimumNodePixelSize = 150;
  88. this.level = 0;
  89. this.position.copy(geometry.offset);
  90. this.updateMatrix();
  91. {
  92. let priorityQueue = ["rgba", "rgb", "intensity", "classification"];
  93. let selected = "rgba";
  94. for(let attributeName of priorityQueue){
  95. let attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === attributeName);
  96. if(!attribute){
  97. continue;
  98. }
  99. let min = attribute.range[0].constructor.name === "Array" ? attribute.range[0] : [attribute.range[0]];
  100. let max = attribute.range[1].constructor.name === "Array" ? attribute.range[1] : [attribute.range[1]];
  101. let range_min = new THREE.Vector3(...min);
  102. let range_max = new THREE.Vector3(...max);
  103. let range = range_min.distanceTo(range_max);
  104. if(range === 0){
  105. continue;
  106. }
  107. selected = attributeName;
  108. break;
  109. }
  110. this.material.activeAttributeName = selected;
  111. }
  112. this.showBoundingBox = false;
  113. this.boundingBoxNodes = [];
  114. this.loadQueue = [];
  115. this.visibleBounds = new THREE.Box3();
  116. this.visibleNodes = [];
  117. this.visibleGeometry = [];
  118. this.generateDEM = false;
  119. this.profileRequests = [];
  120. this.name = '';
  121. this._visible = true;
  122. {
  123. let box = [this.pcoGeometry.tightBoundingBox, this.getBoundingBoxWorld()]
  124. .find(v => v !== undefined);
  125. this.updateMatrixWorld(true);
  126. box = Utils.computeTransformedBoundingBox(box, this.matrixWorld);
  127. let bMin = box.min.z;
  128. let bMax = box.max.z;
  129. this.material.heightMin = bMin;
  130. this.material.heightMax = bMax;
  131. }
  132. // TODO read projection from file instead
  133. this.projection = geometry.projection;
  134. this.fallbackProjection = geometry.fallbackProjection;
  135. this.root = this.pcoGeometry.root;
  136. }
  137. setName (name) {
  138. if (this.name !== name) {
  139. this.name = name;
  140. this.dispatchEvent({type: 'name_changed', name: name, pointcloud: this});
  141. }
  142. }
  143. getName () {
  144. return this.name;
  145. }
  146. getAttribute(name){
  147. const attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === name);
  148. if(attribute){
  149. return attribute;
  150. }else{
  151. return null;
  152. }
  153. }
  154. getAttributes(){
  155. return this.pcoGeometry.pointAttributes;
  156. }
  157. toTreeNode (geometryNode, parent) {
  158. let node = new PointCloudOctreeNode();
  159. // if(geometryNode.name === "r40206"){
  160. // console.log("creating node for r40206");
  161. // }
  162. let sceneNode = new THREE.Points(geometryNode.geometry, this.material);
  163. sceneNode.name = geometryNode.name;
  164. sceneNode.position.copy(geometryNode.boundingBox.min);
  165. sceneNode.frustumCulled = false;
  166. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  167. if (material.program) {
  168. _this.getContext().useProgram(material.program.program);
  169. if (material.program.getUniforms().map.level) {
  170. let level = geometryNode.getLevel();
  171. material.uniforms.level.value = level;
  172. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  173. }
  174. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  175. let vnStart = this.visibleNodeTextureOffsets.get(node);
  176. material.uniforms.vnStart.value = vnStart;
  177. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  178. }
  179. if (material.program.getUniforms().map.pcIndex) {
  180. let i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  181. material.uniforms.pcIndex.value = i;
  182. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  183. }
  184. }
  185. };
  186. // { // DEBUG
  187. // let sg = new THREE.SphereGeometry(1, 16, 16);
  188. // let sm = new THREE.MeshNormalMaterial();
  189. // let s = new THREE.Mesh(sg, sm);
  190. // s.scale.set(5, 5, 5);
  191. // s.position.copy(geometryNode.mean)
  192. // .add(this.position)
  193. // .add(geometryNode.boundingBox.min);
  194. //
  195. // viewer.scene.scene.add(s);
  196. // }
  197. node.geometryNode = geometryNode;
  198. node.sceneNode = sceneNode;
  199. node.pointcloud = this;
  200. node.children = [];
  201. //for (let key in geometryNode.children) {
  202. // node.children[key] = geometryNode.children[key];
  203. //}
  204. for(let i = 0; i < 8; i++){
  205. node.children[i] = geometryNode.children[i];
  206. }
  207. if (!parent) {
  208. this.root = node;
  209. this.add(sceneNode);
  210. } else {
  211. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  212. parent.sceneNode.add(sceneNode);
  213. parent.children[childIndex] = node;
  214. }
  215. let disposeListener = function () {
  216. let childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  217. parent.sceneNode.remove(node.sceneNode);
  218. parent.children[childIndex] = geometryNode;
  219. };
  220. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  221. return node;
  222. }
  223. updateVisibleBounds () {
  224. let leafNodes = [];
  225. for (let i = 0; i < this.visibleNodes.length; i++) {
  226. let node = this.visibleNodes[i];
  227. let isLeaf = true;
  228. for (let j = 0; j < node.children.length; j++) {
  229. let child = node.children[j];
  230. if (child instanceof PointCloudOctreeNode) {
  231. isLeaf = isLeaf && !child.sceneNode.visible;
  232. } else if (child instanceof PointCloudOctreeGeometryNode) {
  233. isLeaf = true;
  234. }
  235. }
  236. if (isLeaf) {
  237. leafNodes.push(node);
  238. }
  239. }
  240. this.visibleBounds.min = new THREE.Vector3(Infinity, Infinity, Infinity);
  241. this.visibleBounds.max = new THREE.Vector3(-Infinity, -Infinity, -Infinity);
  242. for (let i = 0; i < leafNodes.length; i++) {
  243. let node = leafNodes[i];
  244. this.visibleBounds.expandByPoint(node.getBoundingBox().min);
  245. this.visibleBounds.expandByPoint(node.getBoundingBox().max);
  246. }
  247. }
  248. updateMaterial (material, visibleNodes, camera, renderer) {
  249. material.fov = camera.fov * (Math.PI / 180);
  250. material.screenWidth = renderer.domElement.clientWidth;
  251. material.screenHeight = renderer.domElement.clientHeight;
  252. material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  253. material.near = camera.near;
  254. material.far = camera.far;
  255. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new THREE.Vector3()).x;
  256. }
  257. computeVisibilityTextureData(nodes, camera){
  258. if(Potree.measureTimings) performance.mark("computeVisibilityTextureData-start");
  259. let data = new Uint8Array(nodes.length * 4);
  260. let visibleNodeTextureOffsets = new Map();
  261. // copy array
  262. nodes = nodes.slice();
  263. // sort by level and index, e.g. r, r0, r3, r4, r01, r07, r30, ...
  264. let sort = function (a, b) {
  265. let na = a.geometryNode.name;
  266. let nb = b.geometryNode.name;
  267. if (na.length !== nb.length) return na.length - nb.length;
  268. if (na < nb) return -1;
  269. if (na > nb) return 1;
  270. return 0;
  271. };
  272. nodes.sort(sort);
  273. let worldDir = new THREE.Vector3();
  274. let nodeMap = new Map();
  275. let offsetsToChild = new Array(nodes.length).fill(Infinity);
  276. for(let i = 0; i < nodes.length; i++){
  277. let node = nodes[i];
  278. nodeMap.set(node.name, node);
  279. visibleNodeTextureOffsets.set(node, i);
  280. if(i > 0){
  281. let index = parseInt(node.name.slice(-1));
  282. let parentName = node.name.slice(0, -1);
  283. let parent = nodeMap.get(parentName);
  284. let parentOffset = visibleNodeTextureOffsets.get(parent);
  285. let parentOffsetToChild = (i - parentOffset);
  286. offsetsToChild[parentOffset] = Math.min(offsetsToChild[parentOffset], parentOffsetToChild);
  287. data[parentOffset * 4 + 0] = data[parentOffset * 4 + 0] | (1 << index);
  288. data[parentOffset * 4 + 1] = (offsetsToChild[parentOffset] >> 8);
  289. data[parentOffset * 4 + 2] = (offsetsToChild[parentOffset] % 256);
  290. }
  291. let density = node.geometryNode.density;
  292. if(typeof density === "number"){
  293. let lodOffset = Math.log2(density) / 2 - 1.5;
  294. let offsetUint8 = (lodOffset + 10) * 10;
  295. data[i * 4 + 3] = offsetUint8;
  296. }else{
  297. data[i * 4 + 3] = 100;
  298. }
  299. }
  300. if(Potree.measureTimings){
  301. performance.mark("computeVisibilityTextureData-end");
  302. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  303. }
  304. return {
  305. data: data,
  306. offsets: visibleNodeTextureOffsets
  307. };
  308. }
  309. nodeIntersectsProfile (node, profile) {
  310. let bbWorld = node.boundingBox.clone().applyMatrix4(this.matrixWorld);
  311. let bsWorld = bbWorld.getBoundingSphere(new THREE.Sphere());
  312. let intersects = false;
  313. for (let i = 0; i < profile.points.length - 1; i++) {
  314. let start = new THREE.Vector3(profile.points[i + 0].x, profile.points[i + 0].y, bsWorld.center.z);
  315. let end = new THREE.Vector3(profile.points[i + 1].x, profile.points[i + 1].y, bsWorld.center.z);
  316. let closest = new THREE.Line3(start, end).closestPointToPoint(bsWorld.center, true, new THREE.Vector3());
  317. let distance = closest.distanceTo(bsWorld.center);
  318. intersects = intersects || (distance < (bsWorld.radius + profile.width));
  319. }
  320. //console.log(`${node.name}: ${intersects}`);
  321. return intersects;
  322. }
  323. deepestNodeAt(position){
  324. const toObjectSpace = this.matrixWorld.clone().invert();
  325. const objPos = position.clone().applyMatrix4(toObjectSpace);
  326. let current = this.root;
  327. while(true){
  328. let containingChild = null;
  329. for(const child of current.children){
  330. if(child !== undefined){
  331. if(child.getBoundingBox().containsPoint(objPos)){
  332. containingChild = child;
  333. }
  334. }
  335. }
  336. if(containingChild !== null && containingChild instanceof PointCloudOctreeNode){
  337. current = containingChild;
  338. }else{
  339. break;
  340. }
  341. }
  342. const deepest = current;
  343. return deepest;
  344. }
  345. nodesOnRay (nodes, ray) {
  346. let nodesOnRay = [];
  347. let _ray = ray.clone();
  348. for (let i = 0; i < nodes.length; i++) {
  349. let node = nodes[i];
  350. let sphere = node.getBoundingSphere().clone().applyMatrix4(this.matrixWorld);
  351. if (_ray.intersectsSphere(sphere)) {
  352. nodesOnRay.push(node);
  353. }
  354. }
  355. return nodesOnRay;
  356. }
  357. updateMatrixWorld (force) {
  358. if (this.matrixAutoUpdate === true) this.updateMatrix();
  359. if (this.matrixWorldNeedsUpdate === true || force === true) {
  360. if (!this.parent) {
  361. this.matrixWorld.copy(this.matrix);
  362. } else {
  363. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  364. }
  365. this.matrixWorldNeedsUpdate = false;
  366. force = true;
  367. }
  368. }
  369. hideDescendants (object) {
  370. let stack = [];
  371. for (let i = 0; i < object.children.length; i++) {
  372. let child = object.children[i];
  373. if (child.visible) {
  374. stack.push(child);
  375. }
  376. }
  377. while (stack.length > 0) {
  378. let object = stack.shift();
  379. object.visible = false;
  380. for (let i = 0; i < object.children.length; i++) {
  381. let child = object.children[i];
  382. if (child.visible) {
  383. stack.push(child);
  384. }
  385. }
  386. }
  387. }
  388. moveToOrigin () {
  389. this.position.set(0, 0, 0);
  390. this.updateMatrixWorld(true);
  391. let box = this.boundingBox;
  392. let transform = this.matrixWorld;
  393. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  394. this.position.set(0, 0, 0).sub(tBox.getCenter(new THREE.Vector3()));
  395. };
  396. moveToGroundPlane () {
  397. this.updateMatrixWorld(true);
  398. let box = this.boundingBox;
  399. let transform = this.matrixWorld;
  400. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  401. this.position.y += -tBox.min.y;
  402. };
  403. getBoundingBoxWorld () {
  404. this.updateMatrixWorld(true);
  405. let box = this.boundingBox;
  406. let transform = this.matrixWorld;
  407. let tBox = Utils.computeTransformedBoundingBox(box, transform);
  408. return tBox;
  409. };
  410. /**
  411. * returns points inside the profile points
  412. *
  413. * maxDepth: search points up to the given octree depth
  414. *
  415. *
  416. * The return value is an array with all segments of the profile path
  417. * let segment = {
  418. * start: THREE.Vector3,
  419. * end: THREE.Vector3,
  420. * points: {}
  421. * project: function()
  422. * };
  423. *
  424. * The project() function inside each segment can be used to transform
  425. * that segments point coordinates to line up along the x-axis.
  426. *
  427. *
  428. */
  429. getPointsInProfile (profile, maxDepth, callback) {
  430. if (callback) {
  431. let request = new Potree.ProfileRequest(this, profile, maxDepth, callback);
  432. this.profileRequests.push(request);
  433. return request;
  434. }
  435. let points = {
  436. segments: [],
  437. boundingBox: new THREE.Box3(),
  438. projectedBoundingBox: new THREE.Box2()
  439. };
  440. // evaluate segments
  441. for (let i = 0; i < profile.points.length - 1; i++) {
  442. let start = profile.points[i];
  443. let end = profile.points[i + 1];
  444. let ps = this.getProfile(start, end, profile.width, maxDepth);
  445. let segment = {
  446. start: start,
  447. end: end,
  448. points: ps,
  449. project: null
  450. };
  451. points.segments.push(segment);
  452. points.boundingBox.expandByPoint(ps.boundingBox.min);
  453. points.boundingBox.expandByPoint(ps.boundingBox.max);
  454. }
  455. // add projection functions to the segments
  456. let mileage = new THREE.Vector3();
  457. for (let i = 0; i < points.segments.length; i++) {
  458. let segment = points.segments[i];
  459. let start = segment.start;
  460. let end = segment.end;
  461. let project = (function (_start, _end, _mileage, _boundingBox) {
  462. let start = _start;
  463. let end = _end;
  464. let mileage = _mileage;
  465. let boundingBox = _boundingBox;
  466. let xAxis = new THREE.Vector3(1, 0, 0);
  467. let dir = new THREE.Vector3().subVectors(end, start);
  468. dir.y = 0;
  469. dir.normalize();
  470. let alpha = Math.acos(xAxis.dot(dir));
  471. if (dir.z > 0) {
  472. alpha = -alpha;
  473. }
  474. return function (position) {
  475. let toOrigin = new THREE.Matrix4().makeTranslation(-start.x, -boundingBox.min.y, -start.z);
  476. let alignWithX = new THREE.Matrix4().makeRotationY(-alpha);
  477. let applyMileage = new THREE.Matrix4().makeTranslation(mileage.x, 0, 0);
  478. let pos = position.clone();
  479. pos.applyMatrix4(toOrigin);
  480. pos.applyMatrix4(alignWithX);
  481. pos.applyMatrix4(applyMileage);
  482. return pos;
  483. };
  484. }(start, end, mileage.clone(), points.boundingBox.clone()));
  485. segment.project = project;
  486. mileage.x += new THREE.Vector3(start.x, 0, start.z).distanceTo(new THREE.Vector3(end.x, 0, end.z));
  487. mileage.y += end.y - start.y;
  488. }
  489. points.projectedBoundingBox.min.x = 0;
  490. points.projectedBoundingBox.min.y = points.boundingBox.min.y;
  491. points.projectedBoundingBox.max.x = mileage.x;
  492. points.projectedBoundingBox.max.y = points.boundingBox.max.y;
  493. return points;
  494. }
  495. /**
  496. * returns points inside the given profile bounds.
  497. *
  498. * start:
  499. * end:
  500. * width:
  501. * depth: search points up to the given octree depth
  502. * callback: if specified, points are loaded before searching
  503. *
  504. *
  505. */
  506. getProfile (start, end, width, depth, callback) {
  507. let request = new Potree.ProfileRequest(start, end, width, depth, callback);
  508. this.profileRequests.push(request);
  509. };
  510. getVisibleExtent () {
  511. return this.visibleBounds.applyMatrix4(this.matrixWorld);
  512. };
  513. intersectsPoint(position){
  514. let rootAvailable = this.pcoGeometry.root && this.pcoGeometry.root.geometry;
  515. if(!rootAvailable){
  516. return false;
  517. }
  518. if(typeof this.signedDistanceField === "undefined"){
  519. const resolution = 32;
  520. const field = new Float32Array(resolution ** 3).fill(Infinity);
  521. const positions = this.pcoGeometry.root.geometry.attributes.position;
  522. const boundingBox = this.boundingBox;
  523. const n = positions.count;
  524. for(let i = 0; i < n; i = i + 3){
  525. const x = positions.array[3 * i + 0];
  526. const y = positions.array[3 * i + 1];
  527. const z = positions.array[3 * i + 2];
  528. const ix = parseInt(Math.min(resolution * (x / boundingBox.max.x), resolution - 1));
  529. const iy = parseInt(Math.min(resolution * (y / boundingBox.max.y), resolution - 1));
  530. const iz = parseInt(Math.min(resolution * (z / boundingBox.max.z), resolution - 1));
  531. const index = ix + iy * resolution + iz * resolution * resolution;
  532. field[index] = 0;
  533. }
  534. const sdf = {
  535. resolution: resolution,
  536. field: field,
  537. };
  538. this.signedDistanceField = sdf;
  539. }
  540. {
  541. const sdf = this.signedDistanceField;
  542. const boundingBox = this.boundingBox;
  543. const toObjectSpace = this.matrixWorld.clone().invert();
  544. const objPos = position.clone().applyMatrix4(toObjectSpace);
  545. const resolution = sdf.resolution;
  546. const ix = parseInt(resolution * (objPos.x / boundingBox.max.x));
  547. const iy = parseInt(resolution * (objPos.y / boundingBox.max.y));
  548. const iz = parseInt(resolution * (objPos.z / boundingBox.max.z));
  549. if(ix < 0 || iy < 0 || iz < 0){
  550. return false;
  551. }
  552. if(ix >= resolution || iy >= resolution || iz >= resolution){
  553. return false;
  554. }
  555. const index = ix + iy * resolution + iz * resolution * resolution;
  556. const value = sdf.field[index];
  557. if(value === 0){
  558. return true;
  559. }
  560. }
  561. return false;
  562. }
  563. /**
  564. *
  565. *
  566. *
  567. * params.pickWindowSize: Look for points inside a pixel window of this size.
  568. * Use odd values: 1, 3, 5, ...
  569. *
  570. *
  571. * TODO: only draw pixels that are actually read with readPixels().
  572. *
  573. */
  574. pick(viewer, camera, ray, params = {}){
  575. let renderer = viewer.renderer;
  576. let pRenderer = viewer.pRenderer;
  577. performance.mark("pick-start");
  578. let getVal = (a, b) => a !== undefined ? a : b;
  579. let pickWindowSize = getVal(params.pickWindowSize, 65);
  580. let pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  581. let size = renderer.getSize(new THREE.Vector2());
  582. let width = Math.ceil(getVal(params.width, size.width));
  583. let height = Math.ceil(getVal(params.height, size.height));
  584. let pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  585. let pointSize = getVal(params.pointSize, this.material.size);
  586. let nodes = this.nodesOnRay(this.visibleNodes, ray);
  587. if (nodes.length === 0) {
  588. return null;
  589. }
  590. if (!this.pickState) {
  591. let scene = new THREE.Scene();
  592. let material = new Potree.PointCloudMaterial();
  593. material.activeAttributeName = "indices";
  594. let renderTarget = new THREE.WebGLRenderTarget(
  595. 1, 1,
  596. { minFilter: THREE.LinearFilter,
  597. magFilter: THREE.NearestFilter,
  598. format: THREE.RGBAFormat }
  599. );
  600. this.pickState = {
  601. renderTarget: renderTarget,
  602. material: material,
  603. scene: scene
  604. };
  605. };
  606. let pickState = this.pickState;
  607. let pickMaterial = pickState.material;
  608. { // update pick material
  609. pickMaterial.pointSizeType = pointSizeType;
  610. //pickMaterial.shape = this.material.shape;
  611. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  612. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  613. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  614. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  615. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  616. pickMaterial.activeAttributeName = "indices";
  617. pickMaterial.size = pointSize;
  618. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  619. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  620. pickMaterial.classification = this.material.classification;
  621. pickMaterial.recomputeClassification();
  622. if(params.pickClipped){
  623. pickMaterial.clipBoxes = this.material.clipBoxes;
  624. pickMaterial.uniforms.clipBoxes = this.material.uniforms.clipBoxes;
  625. if(this.material.clipTask === Potree.ClipTask.HIGHLIGHT){
  626. pickMaterial.clipTask = Potree.ClipTask.NONE;
  627. }else{
  628. pickMaterial.clipTask = this.material.clipTask;
  629. }
  630. pickMaterial.clipMethod = this.material.clipMethod;
  631. }else{
  632. pickMaterial.clipBoxes = [];
  633. }
  634. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  635. }
  636. pickState.renderTarget.setSize(width, height);
  637. let pixelPos = new THREE.Vector2(params.x, params.y);
  638. let gl = renderer.getContext();
  639. gl.enable(gl.SCISSOR_TEST);
  640. gl.scissor(
  641. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  642. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  643. parseInt(pickWindowSize), parseInt(pickWindowSize));
  644. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  645. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  646. renderer.state.setBlending(THREE.NoBlending);
  647. { // RENDER
  648. renderer.setRenderTarget(pickState.renderTarget);
  649. gl.clearColor(0, 0, 0, 0);
  650. renderer.clear(true, true, true);
  651. let tmp = this.material;
  652. this.material = pickMaterial;
  653. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  654. this.material = tmp;
  655. }
  656. let clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  657. let x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  658. let y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  659. let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  660. let h = parseInt(Math.min(y + pickWindowSize, height) - y);
  661. let pixelCount = w * h;
  662. let buffer = new Uint8Array(4 * pixelCount);
  663. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  664. renderer.setRenderTarget(null);
  665. renderer.state.reset();
  666. renderer.setScissorTest(false);
  667. gl.disable(gl.SCISSOR_TEST);
  668. let pixels = buffer;
  669. let ibuffer = new Uint32Array(buffer.buffer);
  670. // find closest hit inside pixelWindow boundaries
  671. let min = Number.MAX_VALUE;
  672. let hits = [];
  673. for (let u = 0; u < pickWindowSize; u++) {
  674. for (let v = 0; v < pickWindowSize; v++) {
  675. let offset = (u + v * pickWindowSize);
  676. let distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  677. let pcIndex = pixels[4 * offset + 3];
  678. pixels[4 * offset + 3] = 0;
  679. let pIndex = ibuffer[offset];
  680. if(!(pcIndex === 0 && pIndex === 0) && (pcIndex !== undefined) && (pIndex !== undefined)){
  681. let hit = {
  682. pIndex: pIndex,
  683. pcIndex: pcIndex,
  684. distanceToCenter: distance
  685. };
  686. if(params.all){
  687. hits.push(hit);
  688. }else{
  689. if(hits.length > 0){
  690. if(distance < hits[0].distanceToCenter){
  691. hits[0] = hit;
  692. }
  693. }else{
  694. hits.push(hit);
  695. }
  696. }
  697. }
  698. }
  699. }
  700. // { // DEBUG: show panel with pick image
  701. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  702. // let screenshot = img.src;
  703. // if(!this.debugDIV){
  704. // this.debugDIV = $(`
  705. // <div id="pickDebug"
  706. // style="position: absolute;
  707. // right: 400px; width: 300px;
  708. // bottom: 44px; width: 300px;
  709. // z-index: 1000;
  710. // "></div>`);
  711. // $(document.body).append(this.debugDIV);
  712. // }
  713. // this.debugDIV.empty();
  714. // this.debugDIV.append($(`<img src="${screenshot}"
  715. // style="transform: scaleY(-1); width: 300px"/>`));
  716. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  717. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  718. // }
  719. for(let hit of hits){
  720. let point = {};
  721. if (!nodes[hit.pcIndex]) {
  722. return null;
  723. }
  724. let node = nodes[hit.pcIndex];
  725. let pc = node.sceneNode;
  726. let geometry = node.geometryNode.geometry;
  727. for(let attributeName in geometry.attributes){
  728. let attribute = geometry.attributes[attributeName];
  729. if (attributeName === 'position') {
  730. let x = attribute.array[3 * hit.pIndex + 0];
  731. let y = attribute.array[3 * hit.pIndex + 1];
  732. let z = attribute.array[3 * hit.pIndex + 2];
  733. let position = new THREE.Vector3(x, y, z);
  734. position.applyMatrix4(pc.matrixWorld);
  735. point[attributeName] = position;
  736. } else if (attributeName === 'indices') {
  737. } else {
  738. let values = attribute.array.slice(attribute.itemSize * hit.pIndex, attribute.itemSize * (hit.pIndex + 1)) ;
  739. if(attribute.potree){
  740. const {scale, offset} = attribute.potree;
  741. values = values.map(v => v / scale + offset);
  742. }
  743. point[attributeName] = values;
  744. //debugger;
  745. //if (values.itemSize === 1) {
  746. // point[attribute.name] = values.array[hit.pIndex];
  747. //} else {
  748. // let value = [];
  749. // for (let j = 0; j < values.itemSize; j++) {
  750. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  751. // }
  752. // point[attribute.name] = value;
  753. //}
  754. }
  755. }
  756. hit.point = point;
  757. }
  758. performance.mark("pick-end");
  759. performance.measure("pick", "pick-start", "pick-end");
  760. if(params.all){
  761. return hits.map(hit => hit.point);
  762. }else{
  763. if(hits.length === 0){
  764. return null;
  765. }else{
  766. return hits[0].point;
  767. //let sorted = hits.sort( (a, b) => a.distanceToCenter - b.distanceToCenter);
  768. //return sorted[0].point;
  769. }
  770. }
  771. };
  772. * getFittedBoxGen(boxNode){
  773. let start = performance.now();
  774. let shrinkedLocalBounds = new THREE.Box3();
  775. let worldToBox = boxNode.matrixWorld.clone().invert();
  776. for(let node of this.visibleNodes){
  777. if(!node.sceneNode){
  778. continue;
  779. }
  780. let buffer = node.geometryNode.buffer;
  781. let posOffset = buffer.offset("position");
  782. let stride = buffer.stride;
  783. let view = new DataView(buffer.data);
  784. let objectToBox = new THREE.Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  785. let pos = new THREE.Vector4();
  786. for(let i = 0; i < buffer.numElements; i++){
  787. let x = view.getFloat32(i * stride + posOffset + 0, true);
  788. let y = view.getFloat32(i * stride + posOffset + 4, true);
  789. let z = view.getFloat32(i * stride + posOffset + 8, true);
  790. pos.set(x, y, z, 1);
  791. pos.applyMatrix4(objectToBox);
  792. if(-0.5 < pos.x && pos.x < 0.5){
  793. if(-0.5 < pos.y && pos.y < 0.5){
  794. if(-0.5 < pos.z && pos.z < 0.5){
  795. shrinkedLocalBounds.expandByPoint(pos);
  796. }
  797. }
  798. }
  799. }
  800. yield;
  801. }
  802. let fittedPosition = shrinkedLocalBounds.getCenter(new THREE.Vector3()).applyMatrix4(boxNode.matrixWorld);
  803. let fitted = new THREE.Object3D();
  804. fitted.position.copy(fittedPosition);
  805. fitted.scale.copy(boxNode.scale);
  806. fitted.rotation.copy(boxNode.rotation);
  807. let ds = new THREE.Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  808. fitted.scale.multiply(ds);
  809. let duration = performance.now() - start;
  810. console.log("duration: ", duration);
  811. yield fitted;
  812. }
  813. getFittedBox(boxNode, maxLevel = Infinity){
  814. maxLevel = Infinity;
  815. let start = performance.now();
  816. let shrinkedLocalBounds = new THREE.Box3();
  817. let worldToBox = boxNode.matrixWorld.clone().invert();
  818. for(let node of this.visibleNodes){
  819. if(!node.sceneNode || node.getLevel() > maxLevel){
  820. continue;
  821. }
  822. let buffer = node.geometryNode.buffer;
  823. let posOffset = buffer.offset("position");
  824. let stride = buffer.stride;
  825. let view = new DataView(buffer.data);
  826. let objectToBox = new THREE.Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  827. let pos = new THREE.Vector4();
  828. for(let i = 0; i < buffer.numElements; i++){
  829. let x = view.getFloat32(i * stride + posOffset + 0, true);
  830. let y = view.getFloat32(i * stride + posOffset + 4, true);
  831. let z = view.getFloat32(i * stride + posOffset + 8, true);
  832. pos.set(x, y, z, 1);
  833. pos.applyMatrix4(objectToBox);
  834. if(-0.5 < pos.x && pos.x < 0.5){
  835. if(-0.5 < pos.y && pos.y < 0.5){
  836. if(-0.5 < pos.z && pos.z < 0.5){
  837. shrinkedLocalBounds.expandByPoint(pos);
  838. }
  839. }
  840. }
  841. }
  842. }
  843. let fittedPosition = shrinkedLocalBounds.getCenter(new THREE.Vector3()).applyMatrix4(boxNode.matrixWorld);
  844. let fitted = new THREE.Object3D();
  845. fitted.position.copy(fittedPosition);
  846. fitted.scale.copy(boxNode.scale);
  847. fitted.rotation.copy(boxNode.rotation);
  848. let ds = new THREE.Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  849. fitted.scale.multiply(ds);
  850. let duration = performance.now() - start;
  851. console.log("duration: ", duration);
  852. return fitted;
  853. }
  854. get progress () {
  855. return this.visibleNodes.length / this.visibleGeometry.length;
  856. }
  857. find(name){
  858. let node = null;
  859. for(let char of name){
  860. if(char === "r"){
  861. node = this.root;
  862. }else{
  863. node = node.children[char];
  864. }
  865. }
  866. return node;
  867. }
  868. get visible(){
  869. return this._visible;
  870. }
  871. set visible(value){
  872. if(value !== this._visible){
  873. this._visible = value;
  874. this.dispatchEvent({type: 'visibility_changed', pointcloud: this});
  875. }
  876. }
  877. }