viewer.js 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978
  1. import * as THREE from "../../libs/three.js/build/three.module.js";
  2. import {ClipTask, ClipMethod, CameraMode, LengthUnits, ElevationGradientRepeat} from "../defines.js";
  3. import {Renderer} from "../PotreeRenderer.js";
  4. import {PotreeRenderer} from "./PotreeRenderer.js";
  5. import {EDLRenderer} from "./EDLRenderer.js";
  6. import {HQSplatRenderer} from "./HQSplatRenderer.js";
  7. import {Scene} from "./Scene.js";
  8. import {ClippingTool} from "../utils/ClippingTool.js";
  9. import {TransformationTool} from "../utils/TransformationTool.js";
  10. import {Utils} from "../utils.js";
  11. import {MapView} from "./map.js";
  12. import {MapViewer} from "./map/MapViewer.js";
  13. import {ProfileWindow, ProfileWindowController} from "./profile.js";
  14. import {BoxVolume} from "../utils/Volume.js";
  15. import {Features} from "../Features.js";
  16. import {Message} from "../utils/Message.js";
  17. import {Sidebar} from "./sidebar.js";
  18. import {AnnotationTool} from "../utils/AnnotationTool.js";
  19. import {MeasuringTool} from "../utils/MeasuringTool.js";
  20. import {ProfileTool} from "../utils/ProfileTool.js";
  21. import {VolumeTool} from "../utils/VolumeTool.js";
  22. import {InputHandler} from "../navigation/InputHandler.js";
  23. import {NavigationCube} from "./NavigationCube.js";
  24. import {Compass} from "../utils/Compass.js";
  25. import {OrbitControls} from "../navigation/OrbitControls.js";
  26. import {FirstPersonControls} from "../navigation/FirstPersonControls.js";
  27. import {EarthControls} from "../navigation/EarthControls.js";
  28. import {DeviceOrientationControls} from "../navigation/DeviceOrientationControls.js";
  29. import {VRControls} from "../navigation/VRControls.js";
  30. import { ClassificationScheme } from "../materials/ClassificationScheme.js";
  31. import { VRButton } from '../../libs/three.js/extra/VRButton.js';
  32. import {transitions, easing, lerp} from '../utils/transitions.js'
  33. import JSON5 from "../../libs/json5-2.1.3/json5.mjs";
  34. import CursorDeal from '../utils/CursorDeal'
  35. import Common from '../utils/Common'
  36. import {Clip} from '../modules/clipModel/Clip'
  37. import {Alignment} from "../modules/datasetAlignment/Alignment.js";
  38. import {SiteModel} from "../modules/siteModel/SiteModel.js";
  39. import Magnifier from "../utils/Magnifier.js";
  40. import Reticule from "../navigation/Reticule.js";
  41. import Viewport from "./Viewport.js"
  42. import {ViewerBase} from "./viewerBase.js"
  43. import SplitScreen from '../utils/SplitScreen'
  44. import cameraLight from "../utils/cameraLight.js";
  45. import math from "../utils/math.js";
  46. import {UoMService} from '../utils/UnitConvert'
  47. import {RouteGuider} from '../navigation/RouteGuider'
  48. let mapArea;
  49. export class Viewer extends ViewerBase{
  50. constructor(domElement, mapArea_, args = {}){
  51. super(domElement,args);
  52. window.viewer = this
  53. this.modules = { //add
  54. Clip : Clip,
  55. Alignment : Alignment,
  56. SiteModel : SiteModel,
  57. RouteGuider : new RouteGuider,
  58. }
  59. //add --------
  60. this.navigateMode = 'free' // 'panorama'; 'free'自由模式是只显示点云或者未进入到漫游点,
  61. this.isEdit = true
  62. this.waitQueue = []
  63. this.unitConvert = new UoMService();
  64. mapArea = mapArea_
  65. //-------------
  66. this.guiLoaded = false;
  67. this.guiLoadTasks = [];
  68. this.onVrListeners = [];
  69. this.messages = [];
  70. this.elMessages = $(`
  71. <div id="message_listing"
  72. style="position: absolute; z-index: 1000; left: 10px; bottom: 10px">
  73. </div>`);
  74. $(domElement).append(this.elMessages);
  75. try{
  76. if(!Potree.settings.isOfficial)
  77. { // generate missing dom hierarchy
  78. if ($(domElement).find('#potree_map').length === 0) {
  79. let potreeMap = $(`
  80. <div id="potree_map" class="mapBox" style="position: absolute; left: 50px; top: 50px; width: 400px; height: 400px; display: none">
  81. <div id="potree_map_header" style="position: absolute; width: 100%; height: 25px; top: 0px; background-color: rgba(0,0,0,0.5); z-index: 1000; border-top-left-radius: 3px; border-top-right-radius: 3px;">
  82. </div>
  83. <div id="potree_map_content" class="map" style="position: absolute; z-index: 100; top: 25px; width: 100%; height: calc(100% - 25px); border: 2px solid rgba(0,0,0,0.5); box-sizing: border-box;"></div>
  84. </div>
  85. `);
  86. $(domElement).append(potreeMap);
  87. }
  88. if ($(domElement).find('#potree_description').length === 0) {
  89. let potreeDescription = $(`<div id="potree_description" class="potree_info_text"></div>`);
  90. $(domElement).append(potreeDescription);
  91. }
  92. if ($(domElement).find('#potree_annotations').length === 0) {
  93. let potreeAnnotationContainer = $(`
  94. <div id="potree_annotation_container"
  95. style="position: absolute; z-index: 100000; width: 100%; height: 100%; pointer-events: none;"></div>`);
  96. $(domElement).append(potreeAnnotationContainer);
  97. }
  98. if ($(domElement).find('#potree_quick_buttons').length === 0) {
  99. let potreeMap = $(`
  100. <div id="potree_quick_buttons" class="quick_buttons_container" style="">
  101. </div>
  102. `);
  103. $(domElement).append(potreeMap);
  104. }
  105. //add
  106. {
  107. if(!mapArea){
  108. $(domElement).append($("<div id='potree_labels'></div>"))
  109. mapArea = $("<div id='mapGaode'></div>")
  110. $(domElement).append(mapArea)
  111. mapArea = mapArea[0]
  112. }
  113. }
  114. let domRoot = this.renderer.domElement.parentElement;
  115. let elAttach = $("<input type='button' value='test'></input>");
  116. elAttach.css({
  117. position : "absolute",
  118. right : '10%',
  119. bottom: '20px',
  120. zIndex: "10000",
  121. fontSize:'1em', color:"black",
  122. background:'rgba(255,255,255,0.8)',
  123. })
  124. let state = false
  125. elAttach.on("click", () => {
  126. window.buttonFunction && window.buttonFunction()
  127. });
  128. domRoot.appendChild(elAttach[0]);
  129. }
  130. this.pointCloudLoadedCallback = args.onPointCloudLoaded || function () {};
  131. // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  132. // defaultSettings.navigation = "Orbit";
  133. // }
  134. this.server = null;
  135. this.fov = 60;
  136. this.isFlipYZ = false;
  137. this.useDEMCollisions = false;
  138. this.generateDEM = false;
  139. this.minNodeSize = 30;
  140. this.edlStrength = 1.0;
  141. this.edlRadius = 1.4;
  142. this.edlOpacity = 1.0;
  143. this.useEDL = false;
  144. this.description = "";
  145. this.classifications = ClassificationScheme.DEFAULT;
  146. this.moveSpeed = 10;
  147. this.lengthUnit = LengthUnits.METER;
  148. this.lengthUnitDisplay = LengthUnits.METER;
  149. this.showBoundingBox = false;
  150. this.showAnnotations = true;
  151. this.freeze = false;
  152. this.clipTask = ClipTask.HIGHLIGHT;
  153. this.clipMethod = ClipMethod.INSIDE_ANY;
  154. this.elevationGradientRepeat = ElevationGradientRepeat.CLAMP;
  155. this.filterReturnNumberRange = [0, 7];
  156. this.filterNumberOfReturnsRange = [0, 7];
  157. this.filterGPSTimeRange = [-Infinity, Infinity];
  158. this.filterPointSourceIDRange = [0, 65535];
  159. this.potreeRenderer = null;
  160. this.edlRenderer = null;
  161. this.pRenderer = null;
  162. this.scene = null;
  163. this.sceneVR = null;
  164. this.overlay = null;
  165. this.overlayCamera = null;
  166. this.inputHandler = null;
  167. this.controls = null;
  168. this.clippingTool = null;
  169. this.transformationTool = null;
  170. this.navigationCube = null;
  171. this.compass = null;
  172. this.skybox = null;
  173. this.clock = new THREE.Clock();
  174. this.background = null;
  175. if(args.noDragAndDrop){
  176. }else{
  177. this.initDragAndDrop();
  178. }
  179. if(typeof Stats !== "undefined"){
  180. this.stats = new Stats();
  181. this.stats.showPanel( 0 ); // 0: fps, 1: ms, 2: mb, 3+: custom
  182. document.body.appendChild( this.stats.dom );
  183. }
  184. {
  185. let canvas = this.renderer.domElement;
  186. canvas.addEventListener("webglcontextlost", (e) => {
  187. console.log(e);
  188. this.postMessage("WebGL context lost. \u2639");
  189. let gl = this.renderer.getContext();
  190. let error = gl.getError();
  191. console.log(error);
  192. }, false);
  193. }
  194. {
  195. this.overlay = new THREE.Scene();
  196. this.overlayCamera = new THREE.OrthographicCamera(
  197. 0, 1,
  198. 1, 0,
  199. -1000, 1000
  200. );
  201. }
  202. this.pRenderer = new Renderer(this.renderer);
  203. {
  204. let near = 2.5;
  205. let far = 10.0;
  206. let fov = 90;
  207. this.shadowTestCam = new THREE.PerspectiveCamera(90, 1, near, far);
  208. this.shadowTestCam.position.set(3.50, -2.80, 8.561);
  209. this.shadowTestCam.lookAt(new THREE.Vector3(0, 0, 4.87));
  210. }
  211. let scene = new Scene(this.renderer);
  212. { // create VR scene
  213. this.sceneVR = new THREE.Scene();
  214. // let texture = new THREE.TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  215. // let plane = new THREE.PlaneBufferGeometry(1, 1, 1, 1);
  216. // let infoMaterial = new THREE.MeshBasicMaterial({map: texture});
  217. // let infoNode = new THREE.Mesh(plane, infoMaterial);
  218. // infoNode.position.set(-0.5, 1, 0);
  219. // infoNode.scale.set(0.4, 0.3, 1);
  220. // infoNode.lookAt(0, 1, 0)
  221. // this.sceneVR.add(infoNode);
  222. // window.infoNode = infoNode;
  223. }
  224. this.setScene(scene);
  225. {
  226. this.inputHandler = new InputHandler(this, this.scene.scene);
  227. //this.inputHandler.setScene(this.scene);
  228. //this.inputHandler.addInputListener(this);//add
  229. this.clippingTool = new ClippingTool(this);
  230. this.transformationTool = new TransformationTool(this);
  231. this.navigationCube = new NavigationCube(this);
  232. this.navigationCube.visible = false;
  233. this.compass = new Compass(this);
  234. //add----------
  235. this.magnifier = new Magnifier(this);
  236. this.reticule = new Reticule(this)
  237. this.scene.scene.add(this.magnifier)
  238. this.scene.scene.add(this.reticule)
  239. this.mainViewport = new Viewport( this.scene.view, this.scene.cameraP, {
  240. left:0, bottom:0, width:1, height: 1, name:'MainView'
  241. })
  242. this.viewports = [this.mainViewport]
  243. this.mapViewer = new MapViewer(mapArea/* $('#mapGaode')[0] */)
  244. CursorDeal.init(this)//ADD
  245. this.modules.SiteModel.init()
  246. //-----------
  247. this.createControls();
  248. this.clippingTool.setScene(this.scene);
  249. let onPointcloudAdded = (e) => {
  250. if (this.scene.pointclouds.length === 1) {
  251. let speed = e.pointcloud.boundingBox.getSize(new THREE.Vector3()).length();
  252. speed = speed / 2000;
  253. this.setMoveSpeed(speed);
  254. }
  255. };
  256. let onVolumeRemoved = (e) => {
  257. this.inputHandler.deselect(e.volume);
  258. };
  259. this.addEventListener('scene_changed', (e) => {
  260. this.inputHandler.setScene(e.scene);
  261. this.clippingTool.setScene(this.scene);
  262. if(!e.scene.hasEventListener("pointcloud_added", onPointcloudAdded)){
  263. e.scene.addEventListener("pointcloud_added", onPointcloudAdded);
  264. }
  265. if(!e.scene.hasEventListener("volume_removed", onPointcloudAdded)){
  266. e.scene.addEventListener("volume_removed", onVolumeRemoved);
  267. }
  268. });
  269. this.scene.addEventListener("volume_removed", onVolumeRemoved);
  270. this.scene.addEventListener('pointcloud_added', onPointcloudAdded);
  271. }
  272. { // set defaults
  273. this.setFOV(60);
  274. this.setEDLEnabled(false);
  275. this.setEDLRadius(1.4);
  276. this.setEDLStrength(0.4);
  277. this.setEDLOpacity(1.0);
  278. this.setClipTask(ClipTask.HIGHLIGHT);
  279. this.setClipMethod(ClipMethod.INSIDE_ANY);
  280. this.setPointBudget(1*1000*1000);
  281. this.setShowBoundingBox(false);
  282. this.setFreeze(false);
  283. this.setControls(this.fpControls/* orbitControls */);
  284. this.setBackground('gradient');
  285. this.scaleFactor = 1;
  286. this.loadSettingsFromURL();
  287. }
  288. // start rendering!
  289. //if(args.useDefaultRenderLoop === undefined || args.useDefaultRenderLoop === true){
  290. //requestAnimationFrame(this.loop.bind(this));
  291. //}
  292. this.renderer.setAnimationLoop(this.loop.bind(this));
  293. this.loadGUI = this.loadGUI.bind(this);
  294. this.annotationTool = new AnnotationTool(this);
  295. this.measuringTool = new MeasuringTool(this);
  296. this.profileTool = new ProfileTool(this);
  297. this.volumeTool = new VolumeTool(this);
  298. }catch(e){
  299. this.onCrash(e);
  300. }
  301. {//add
  302. let pointDensity = ''
  303. Object.defineProperty(Potree.settings , "pointDensity",{
  304. get: function() {
  305. return pointDensity
  306. },
  307. set: (density)=>{
  308. if(pointDensity != density){
  309. var config = Potree.config.pointDensity[density];
  310. viewer.setPointBudget(config.pointBudget );
  311. Potree.maxPointLevel = config.maxLevel
  312. viewer.scene.pointclouds.forEach(e=>{
  313. e.maxLevel = config.maxLevel
  314. })
  315. }
  316. }
  317. })
  318. }
  319. {
  320. let cameraFar = Potree.settings.cameraFar
  321. Object.defineProperty(Potree.settings , "cameraFar",{
  322. get: function() {
  323. return cameraFar
  324. },
  325. set: (far)=>{
  326. if(far != cameraFar){
  327. if(Potree.settings.displayMode != 'showPanos'){
  328. this.mainViewport.camera.far = far;
  329. this.mainViewport.camera.updateProjectionMatrix()
  330. }
  331. }
  332. }
  333. })
  334. }
  335. }
  336. onCrash(error){
  337. $(this.renderArea).empty();
  338. if ($(this.renderArea).find('#potree_failpage').length === 0) {
  339. let elFailPage = $(`
  340. <div id="#potree_failpage" class="potree_failpage">
  341. <h1>Potree Encountered An Error </h1>
  342. <p>
  343. This may happen if your browser or graphics card is not supported.
  344. <br>
  345. We recommend to use
  346. <a href="https://www.google.com/chrome/browser" target="_blank" style="color:initial">Chrome</a>
  347. or
  348. <a href="https://www.mozilla.org/" target="_blank">Firefox</a>.
  349. </p>
  350. <p>
  351. Please also visit <a href="http://webglreport.com/" target="_blank">webglreport.com</a> and
  352. check whether your system supports WebGL.
  353. </p>
  354. <p>
  355. If you are already using one of the recommended browsers and WebGL is enabled,
  356. consider filing an issue report at <a href="https://github.com/potree/potree/issues" target="_blank">github</a>,<br>
  357. including your operating system, graphics card, browser and browser version, as well as the
  358. error message below.<br>
  359. Please do not report errors on unsupported browsers.
  360. </p>
  361. <pre id="potree_error_console" style="width: 100%; height: 100%"></pre>
  362. </div>`);
  363. let elErrorMessage = elFailPage.find('#potree_error_console');
  364. elErrorMessage.html(error.stack);
  365. $(this.renderArea).append(elFailPage);
  366. }
  367. throw error;
  368. }
  369. // ------------------------------------------------------------------------------------
  370. // Viewer API
  371. // ------------------------------------------------------------------------------------
  372. setScene (scene) {
  373. if (scene === this.scene) {
  374. return;
  375. }
  376. let oldScene = this.scene;
  377. this.scene = scene;
  378. this.dispatchEvent({
  379. type: 'scene_changed',
  380. oldScene: oldScene,
  381. scene: scene
  382. });
  383. { // Annotations
  384. $('.annotation').detach();
  385. // for(let annotation of this.scene.annotations){
  386. // this.renderArea.appendChild(annotation.domElement[0]);
  387. // }
  388. this.scene.annotations.traverse(annotation => {
  389. this.renderArea.appendChild(annotation.domElement[0]);
  390. });
  391. if (!this.onAnnotationAdded) {
  392. this.onAnnotationAdded = e => {
  393. // console.log("annotation added: " + e.annotation.title);
  394. e.annotation.traverse(node => {
  395. $("#potree_annotation_container").append(node.domElement);
  396. //this.renderArea.appendChild(node.domElement[0]);
  397. node.scene = this.scene;
  398. });
  399. };
  400. }
  401. if (oldScene) {
  402. oldScene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  403. }
  404. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  405. }
  406. };
  407. setControls(controls/* , setSpeed */){
  408. if (controls !== this.controls) {
  409. if (this.controls) {
  410. this.controls.setEnable(false)
  411. //this.inputHandler.removeInputListener(this.controls);
  412. this.controls.moveSpeed = this.moveSpeed; //记录 (因为orbit的radius很大,转为firstPerson时要缩小)
  413. }
  414. this.controls = controls;
  415. controls.moveSpeed && this.setMoveSpeed(controls.moveSpeed) //add
  416. this.controls.setEnable(true)
  417. //this.inputHandler.addInputListener(this.controls);
  418. }
  419. }
  420. getControls () {
  421. if(this.renderer.xr.isPresenting){
  422. return this.vrControls;
  423. }else{
  424. return this.controls;
  425. }
  426. }
  427. getMinNodeSize () {
  428. return this.minNodeSize;
  429. };
  430. setMinNodeSize (value) {
  431. if (this.minNodeSize !== value) {
  432. this.minNodeSize = value;
  433. this.dispatchEvent({'type': 'minnodesize_changed', 'viewer': this});
  434. }
  435. };
  436. getBackground () {
  437. return this.background;
  438. }
  439. setBackground(bg){
  440. if (this.background === bg) {
  441. return;
  442. }
  443. if(bg === "skybox"){
  444. this.skybox = Utils.loadSkybox(new URL(Potree.resourcePath + '/textures/skybox2/').href);
  445. }
  446. this.background = bg;
  447. this.backgroundOpacity = 1//add
  448. this.dispatchEvent({'type': 'background_changed', 'viewer': this});
  449. }
  450. setDescription (value) {
  451. this.description = value;
  452. $('#potree_description').html(value);
  453. //$('#potree_description').text(value);
  454. }
  455. getDescription(){
  456. return this.description;
  457. }
  458. setShowBoundingBox (value) {
  459. if (this.showBoundingBox !== value) {
  460. this.showBoundingBox = value;
  461. this.dispatchEvent({'type': 'show_boundingbox_changed', 'viewer': this});
  462. }
  463. };
  464. getShowBoundingBox () {
  465. return this.showBoundingBox;
  466. };
  467. setMoveSpeed (value) {
  468. if (this.getMoveSpeed() !== value) {
  469. this.mainViewport.setMoveSpeed(value)
  470. this.dispatchEvent({'type': 'move_speed_changed', 'viewer': this, 'speed': value});
  471. }
  472. };
  473. getMoveSpeed () {
  474. return this.mainViewport.moveSpeed;
  475. };
  476. setWeightClassification (w) {
  477. for (let i = 0; i < this.scene.pointclouds.length; i++) {
  478. this.scene.pointclouds[i].material.weightClassification = w;
  479. this.dispatchEvent({'type': 'attribute_weights_changed' + i, 'viewer': this});
  480. }
  481. };
  482. setFreeze (value) {
  483. value = Boolean(value);
  484. if (this.freeze !== value) {
  485. this.freeze = value;
  486. this.dispatchEvent({'type': 'freeze_changed', 'viewer': this});
  487. }
  488. };
  489. getFreeze () {
  490. return this.freeze;
  491. };
  492. getClipTask(){
  493. return this.clipTask;
  494. }
  495. getClipMethod(){
  496. return this.clipMethod;
  497. }
  498. setClipTask(value){
  499. if(this.clipTask !== value){
  500. this.clipTask = value;
  501. this.dispatchEvent({
  502. type: "cliptask_changed",
  503. viewer: this});
  504. }
  505. }
  506. setClipMethod(value){
  507. if(this.clipMethod !== value){
  508. this.clipMethod = value;
  509. this.dispatchEvent({
  510. type: "clipmethod_changed",
  511. viewer: this});
  512. }
  513. }
  514. setElevationGradientRepeat(value){
  515. if(this.elevationGradientRepeat !== value){
  516. this.elevationGradientRepeat = value;
  517. this.dispatchEvent({
  518. type: "elevation_gradient_repeat_changed",
  519. viewer: this});
  520. }
  521. }
  522. setPointBudget (value) {
  523. if (Potree.pointBudget !== value) {
  524. Potree.pointBudget = parseInt(value);
  525. this.dispatchEvent({'type': 'point_budget_changed', 'viewer': this});
  526. }
  527. };
  528. getPointBudget () {
  529. return Potree.pointBudget;
  530. };
  531. setShowAnnotations (value) {
  532. if (this.showAnnotations !== value) {
  533. this.showAnnotations = value;
  534. this.dispatchEvent({'type': 'show_annotations_changed', 'viewer': this});
  535. }
  536. }
  537. getShowAnnotations () {
  538. return this.showAnnotations;
  539. }
  540. setDEMCollisionsEnabled(value){
  541. if(this.useDEMCollisions !== value){
  542. this.useDEMCollisions = value;
  543. this.dispatchEvent({'type': 'use_demcollisions_changed', 'viewer': this});
  544. };
  545. };
  546. getDEMCollisionsEnabled () {
  547. return this.useDEMCollisions;
  548. };
  549. setEDLEnabled (value) {
  550. value = Boolean(value) && Features.SHADER_EDL.isSupported();
  551. if (this.useEDL !== value) {
  552. this.useEDL = value;
  553. this.dispatchEvent({'type': 'use_edl_changed', 'viewer': this});
  554. }
  555. };
  556. getEDLEnabled () {
  557. return this.useEDL;
  558. };
  559. setEDLRadius (value) {
  560. if (this.edlRadius !== value) {
  561. this.edlRadius = value;
  562. this.dispatchEvent({'type': 'edl_radius_changed', 'viewer': this});
  563. }
  564. };
  565. getEDLRadius () {
  566. return this.edlRadius;
  567. };
  568. setEDLStrength (value) {
  569. if (this.edlStrength !== value) {
  570. this.edlStrength = value;
  571. this.dispatchEvent({'type': 'edl_strength_changed', 'viewer': this});
  572. }
  573. };
  574. getEDLStrength () {
  575. return this.edlStrength;
  576. };
  577. setEDLOpacity (value) {
  578. if (this.edlOpacity !== value) {
  579. this.edlOpacity = value;
  580. this.dispatchEvent({'type': 'edl_opacity_changed', 'viewer': this});
  581. }
  582. };
  583. getEDLOpacity () {
  584. return this.edlOpacity;
  585. };
  586. setFOV (value) {
  587. if (this.fov !== value) {
  588. this.fov = value;
  589. this.scene.cameraP.fov = this.fov;
  590. this.scene.cameraP.updateProjectionMatrix()
  591. this.dispatchEvent({'type': 'fov_changed', 'viewer': this});
  592. }
  593. };
  594. getFOV () {
  595. return this.fov;
  596. };
  597. disableAnnotations () {
  598. this.scene.annotations.traverse(annotation => {
  599. annotation.domElement.css('pointer-events', 'none');
  600. // return annotation.visible;
  601. });
  602. };
  603. enableAnnotations () {
  604. this.scene.annotations.traverse(annotation => {
  605. annotation.domElement.css('pointer-events', 'auto');
  606. // return annotation.visible;
  607. });
  608. }
  609. setClassifications(classifications){
  610. this.classifications = classifications;
  611. this.dispatchEvent({'type': 'classifications_changed', 'viewer': this});
  612. }
  613. setClassificationVisibility (key, value) {
  614. if (!this.classifications[key]) {
  615. this.classifications[key] = {visible: value, name: 'no name'};
  616. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  617. } else if (this.classifications[key].visible !== value) {
  618. this.classifications[key].visible = value;
  619. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  620. }
  621. }
  622. toggleAllClassificationsVisibility(){
  623. let numVisible = 0;
  624. let numItems = 0;
  625. for(const key of Object.keys(this.classifications)){
  626. if(this.classifications[key].visible){
  627. numVisible++;
  628. }
  629. numItems++;
  630. }
  631. let visible = true;
  632. if(numVisible === numItems){
  633. visible = false;
  634. }
  635. let somethingChanged = false;
  636. for(const key of Object.keys(this.classifications)){
  637. if(this.classifications[key].visible !== visible){
  638. this.classifications[key].visible = visible;
  639. somethingChanged = true;
  640. }
  641. }
  642. if(somethingChanged){
  643. this.dispatchEvent({'type': 'classification_visibility_changed', 'viewer': this});
  644. }
  645. }
  646. setFilterReturnNumberRange(from, to){
  647. this.filterReturnNumberRange = [from, to];
  648. this.dispatchEvent({'type': 'filter_return_number_range_changed', 'viewer': this});
  649. }
  650. setFilterNumberOfReturnsRange(from, to){
  651. this.filterNumberOfReturnsRange = [from, to];
  652. this.dispatchEvent({'type': 'filter_number_of_returns_range_changed', 'viewer': this});
  653. }
  654. setFilterGPSTimeRange(from, to){
  655. this.filterGPSTimeRange = [from, to];
  656. this.dispatchEvent({'type': 'filter_gps_time_range_changed', 'viewer': this});
  657. }
  658. setFilterPointSourceIDRange(from, to){
  659. this.filterPointSourceIDRange = [from, to]
  660. this.dispatchEvent({'type': 'filter_point_source_id_range_changed', 'viewer': this});
  661. }
  662. setLengthUnit (value) {
  663. switch (value) {
  664. case 'm':
  665. this.lengthUnit = LengthUnits.METER;
  666. this.lengthUnitDisplay = LengthUnits.METER;
  667. break;
  668. case 'ft':
  669. this.lengthUnit = LengthUnits.FEET;
  670. this.lengthUnitDisplay = LengthUnits.FEET;
  671. break;
  672. case 'in':
  673. this.lengthUnit = LengthUnits.INCH;
  674. this.lengthUnitDisplay = LengthUnits.INCH;
  675. break;
  676. }
  677. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: value});
  678. };
  679. setLengthUnitAndDisplayUnit(lengthUnitValue, lengthUnitDisplayValue) {
  680. switch (lengthUnitValue) {
  681. case 'm':
  682. this.lengthUnit = LengthUnits.METER;
  683. break;
  684. case 'ft':
  685. this.lengthUnit = LengthUnits.FEET;
  686. break;
  687. case 'in':
  688. this.lengthUnit = LengthUnits.INCH;
  689. break;
  690. }
  691. switch (lengthUnitDisplayValue) {
  692. case 'm':
  693. this.lengthUnitDisplay = LengthUnits.METER;
  694. break;
  695. case 'ft':
  696. this.lengthUnitDisplay = LengthUnits.FEET;
  697. break;
  698. case 'in':
  699. this.lengthUnitDisplay = LengthUnits.INCH;
  700. break;
  701. }
  702. this.dispatchEvent({ 'type': 'length_unit_changed', 'viewer': this, value: lengthUnitValue });
  703. };
  704. zoomTo(node, factor, animationDuration = 0){
  705. let view = this.scene.view;
  706. let camera = this.scene.cameraP.clone();
  707. camera.rotation.copy(this.scene.cameraP.rotation);
  708. camera.rotation.order = "ZXY";
  709. camera.rotation.x = Math.PI / 2 + view.pitch;
  710. camera.rotation.z = view.yaw;
  711. camera.updateMatrix();
  712. camera.updateMatrixWorld();
  713. camera.zoomTo(node, factor);
  714. let bs;
  715. if (node.boundingSphere) {
  716. bs = node.boundingSphere;
  717. } else if (node.geometry && node.geometry.boundingSphere) {
  718. bs = node.geometry.boundingSphere;
  719. } else {
  720. bs = node.boundingBox.getBoundingSphere(new THREE.Sphere());
  721. }
  722. bs = bs.clone().applyMatrix4(node.matrixWorld);
  723. let startPosition = view.position.clone();
  724. let endPosition = camera.position.clone();
  725. let startTarget = view.getPivot();
  726. let endTarget = bs.center;
  727. let startRadius = view.radius;
  728. let endRadius = endPosition.distanceTo(endTarget);
  729. let easing = TWEEN.Easing.Quartic.Out;
  730. { // animate camera position
  731. let pos = startPosition.clone();
  732. let tween = new TWEEN.Tween(pos).to(endPosition, animationDuration);
  733. tween.easing(easing);
  734. tween.onUpdate(() => {
  735. view.position.copy(pos);
  736. });
  737. tween.start();
  738. }
  739. { // animate camera target
  740. let target = startTarget.clone();
  741. let tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  742. tween.easing(easing);
  743. tween.onUpdate(() => {
  744. view.lookAt(target);
  745. });
  746. tween.onComplete(() => {
  747. view.lookAt(target);
  748. this.dispatchEvent({type: 'focusing_finished', target: this});
  749. });
  750. this.dispatchEvent({type: 'focusing_started', target: this});
  751. tween.start();
  752. }
  753. };
  754. moveToGpsTimeVicinity(time){
  755. const result = Potree.Utils.findClosestGpsTime(time, viewer);
  756. const box = result.node.pointcloud.deepestNodeAt(result.position).getBoundingBox();
  757. const diameter = box.min.distanceTo(box.max);
  758. const camera = this.scene.getActiveCamera();
  759. const offset = camera.getWorldDirection(new THREE.Vector3()).multiplyScalar(diameter);
  760. const newCamPos = result.position.clone().sub(offset);
  761. this.scene.view.position.copy(newCamPos);
  762. this.scene.view.lookAt(result.position);
  763. }
  764. showAbout () {
  765. $(function () {
  766. $('#about-panel').dialog();
  767. });
  768. };
  769. getGpsTimeExtent(){
  770. const range = [Infinity, -Infinity];
  771. for(const pointcloud of this.scene.pointclouds){
  772. const attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  773. const aGpsTime = attributes.find(a => a.name === "gps-time");
  774. if(aGpsTime){
  775. range[0] = Math.min(range[0], aGpsTime.range[0]);
  776. range[1] = Math.max(range[1], aGpsTime.range[1]);
  777. }
  778. }
  779. return range;
  780. }
  781. fitToScreen (factor = 1, animationDuration = 0) {
  782. let box = this.getBoundingBox(this.scene.pointclouds);
  783. let node = new THREE.Object3D();
  784. node.boundingBox = box;
  785. this.zoomTo(node, factor, animationDuration);
  786. this.controls.stop();
  787. };
  788. toggleNavigationCube() {
  789. this.navigationCube.visible = !this.navigationCube.visible;
  790. }
  791. /* setView(pos, view) {
  792. if(!pos) return;
  793. switch(pos) {
  794. case "F":
  795. this.setFrontView(view);
  796. break;
  797. case "B":
  798. this.setBackView(view);
  799. break;
  800. case "L":
  801. this.setLeftView(view);
  802. break;
  803. case "R":
  804. this.setRightView(view);
  805. break;
  806. case "U":
  807. this.setTopView(view);
  808. break;
  809. case "D":
  810. this.setBottomView(view);
  811. break;
  812. }
  813. } */
  814. setTopView(view){
  815. view = view || this.scene.view
  816. view.setCubeView("Top")
  817. this.fitToScreen();
  818. };
  819. setBottomView(){
  820. this.scene.view.yaw = -Math.PI;
  821. this.scene.view.pitch = Math.PI / 2;
  822. this.fitToScreen();
  823. };
  824. setFrontView(view){
  825. view = view || this.scene.view
  826. view.yaw = 0;
  827. view.pitch = 0;
  828. this.fitToScreen();
  829. };
  830. setBackView(view){
  831. view = view || this.scene.view
  832. view.yaw = Math.PI;
  833. view.pitch = 0;
  834. this.fitToScreen();
  835. };
  836. setLeftView(){
  837. this.scene.view.yaw = -Math.PI / 2;
  838. this.scene.view.pitch = 0;
  839. this.fitToScreen();
  840. };
  841. setRightView () {
  842. this.scene.view.yaw = Math.PI / 2;
  843. this.scene.view.pitch = 0;
  844. this.fitToScreen();
  845. };
  846. flipYZ () {
  847. this.isFlipYZ = !this.isFlipYZ;
  848. // TODO flipyz
  849. console.log('TODO');
  850. }
  851. setCameraMode(mode){
  852. this.scene.cameraMode = mode;
  853. for(let pointcloud of this.scene.pointclouds) {
  854. pointcloud.material.useOrthographicCamera = mode == CameraMode.ORTHOGRAPHIC;
  855. }
  856. }
  857. getProjection(){
  858. const pointcloud = this.scene.pointclouds[0];
  859. if(pointcloud){
  860. return pointcloud.projection;
  861. }else{
  862. return null;
  863. }
  864. }
  865. async loadProject(url){
  866. const response = await fetch(url);
  867. if(response.ok){
  868. const text = await response.text();
  869. const json = JSON5.parse(text);
  870. // const json = JSON.parse(text);
  871. if(json.type === "Potree"){
  872. Potree.loadProject(viewer, json);
  873. }
  874. }else{
  875. console.warn("未能加载:"+url )
  876. }
  877. }
  878. saveProject(){
  879. return Potree.saveProject(this);
  880. }
  881. loadSettingsFromURL(){
  882. if(Utils.getParameterByName("pointSize")){
  883. this.setPointSize(parseFloat(Utils.getParameterByName("pointSize")));
  884. }
  885. if(Utils.getParameterByName("FOV")){
  886. this.setFOV(parseFloat(Utils.getParameterByName("FOV")));
  887. }
  888. if(Utils.getParameterByName("opacity")){
  889. this.setOpacity(parseFloat(Utils.getParameterByName("opacity")));
  890. }
  891. if(Utils.getParameterByName("edlEnabled")){
  892. let enabled = Utils.getParameterByName("edlEnabled") === "true";
  893. this.setEDLEnabled(enabled);
  894. }
  895. if (Utils.getParameterByName('edlRadius')) {
  896. this.setEDLRadius(parseFloat(Utils.getParameterByName('edlRadius')));
  897. }
  898. if (Utils.getParameterByName('edlStrength')) {
  899. this.setEDLStrength(parseFloat(Utils.getParameterByName('edlStrength')));
  900. }
  901. if (Utils.getParameterByName('pointBudget')) {
  902. this.setPointBudget(parseFloat(Utils.getParameterByName('pointBudget')));
  903. }
  904. if (Utils.getParameterByName('showBoundingBox')) {
  905. let enabled = Utils.getParameterByName('showBoundingBox') === 'true';
  906. if (enabled) {
  907. this.setShowBoundingBox(true);
  908. } else {
  909. this.setShowBoundingBox(false);
  910. }
  911. }
  912. if (Utils.getParameterByName('material')) {
  913. let material = Utils.getParameterByName('material');
  914. this.setMaterial(material);
  915. }
  916. if (Utils.getParameterByName('pointSizing')) {
  917. let sizing = Utils.getParameterByName('pointSizing');
  918. this.setPointSizing(sizing);
  919. }
  920. if (Utils.getParameterByName('quality')) {
  921. let quality = Utils.getParameterByName('quality');
  922. this.setQuality(quality);
  923. }
  924. if (Utils.getParameterByName('position')) {
  925. let value = Utils.getParameterByName('position');
  926. value = value.replace('[', '').replace(']', '');
  927. let tokens = value.split(';');
  928. let x = parseFloat(tokens[0]);
  929. let y = parseFloat(tokens[1]);
  930. let z = parseFloat(tokens[2]);
  931. this.scene.view.position.set(x, y, z);
  932. }
  933. if (Utils.getParameterByName('target')) {
  934. let value = Utils.getParameterByName('target');
  935. value = value.replace('[', '').replace(']', '');
  936. let tokens = value.split(';');
  937. let x = parseFloat(tokens[0]);
  938. let y = parseFloat(tokens[1]);
  939. let z = parseFloat(tokens[2]);
  940. this.scene.view.lookAt(new THREE.Vector3(x, y, z));
  941. }
  942. if (Utils.getParameterByName('background')) {
  943. let value = Utils.getParameterByName('background');
  944. this.setBackground(value);
  945. }
  946. // if(Utils.getParameterByName("elevationRange")){
  947. // let value = Utils.getParameterByName("elevationRange");
  948. // value = value.replace("[", "").replace("]", "");
  949. // let tokens = value.split(";");
  950. // let x = parseFloat(tokens[0]);
  951. // let y = parseFloat(tokens[1]);
  952. //
  953. // this.setElevationRange(x, y);
  954. // //this.scene.view.target.set(x, y, z);
  955. // }
  956. };
  957. // ------------------------------------------------------------------------------------
  958. // Viewer Internals
  959. // ------------------------------------------------------------------------------------
  960. createControls () {
  961. { // create FIRST PERSON CONTROLS
  962. this.fpControls = new FirstPersonControls(this, this.mainViewport);
  963. this.fpControls.enabled = false;
  964. this.fpControls.addEventListener('start', this.disableAnnotations.bind(this));
  965. this.fpControls.addEventListener('end', this.enableAnnotations.bind(this));
  966. this.addEventListener("loadPointCloudDone", ()=>{
  967. let boundPlane = new THREE.Box3()
  968. boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低
  969. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度
  970. FirstPersonControls.boundPlane = boundPlane
  971. FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  972. })
  973. }
  974. // { // create GEO CONTROLS
  975. // this.geoControls = new GeoControls(this.scene.camera, this.renderer.domElement);
  976. // this.geoControls.enabled = false;
  977. // this.geoControls.addEventListener("start", this.disableAnnotations.bind(this));
  978. // this.geoControls.addEventListener("end", this.enableAnnotations.bind(this));
  979. // this.geoControls.addEventListener("move_speed_changed", (event) => {
  980. // this.setMoveSpeed(this.geoControls.moveSpeed);
  981. // });
  982. // }
  983. { // create ORBIT CONTROLS
  984. this.orbitControls = new OrbitControls(this);
  985. this.orbitControls.enabled = false;
  986. this.orbitControls.addEventListener('start', this.disableAnnotations.bind(this));
  987. this.orbitControls.addEventListener('end', this.enableAnnotations.bind(this));
  988. }
  989. { // create EARTH CONTROLS
  990. this.earthControls = new EarthControls(this);
  991. this.earthControls.enabled = false;
  992. this.earthControls.addEventListener('start', this.disableAnnotations.bind(this));
  993. this.earthControls.addEventListener('end', this.enableAnnotations.bind(this));
  994. }
  995. { // create DEVICE ORIENTATION CONTROLS
  996. this.deviceControls = new DeviceOrientationControls(this);
  997. this.deviceControls.enabled = false;
  998. this.deviceControls.addEventListener('start', this.disableAnnotations.bind(this));
  999. this.deviceControls.addEventListener('end', this.enableAnnotations.bind(this));
  1000. }
  1001. { // create VR CONTROLS
  1002. this.vrControls = new VRControls(this);
  1003. this.vrControls.enabled = false;
  1004. this.vrControls.addEventListener('start', this.disableAnnotations.bind(this));
  1005. this.vrControls.addEventListener('end', this.enableAnnotations.bind(this));
  1006. }
  1007. };
  1008. toggleSidebar () {
  1009. let renderArea = $('#potree_render_area');
  1010. let isVisible = renderArea.css('left') !== '0px';
  1011. if (isVisible) {
  1012. renderArea.css('left', '0px');
  1013. } else {
  1014. renderArea.css('left', '300px');
  1015. }
  1016. };
  1017. toggleMap () {
  1018. // let map = $('#potree_map');
  1019. // map.toggle(100);
  1020. if (this.mapView) {
  1021. this.mapView.toggle();
  1022. }
  1023. };
  1024. onGUILoaded(callback){
  1025. if(this.guiLoaded){
  1026. callback();
  1027. }else{
  1028. this.guiLoadTasks.push(callback);
  1029. }
  1030. }
  1031. promiseGuiLoaded(){
  1032. return new Promise( resolve => {
  1033. if(this.guiLoaded){
  1034. resolve();
  1035. }else{
  1036. this.guiLoadTasks.push(resolve);
  1037. }
  1038. });
  1039. }
  1040. loadGUI(callback){
  1041. if(callback){
  1042. this.onGUILoaded(callback);
  1043. }
  1044. let viewer = this;
  1045. let sidebarContainer = $('#potree_sidebar_container');
  1046. sidebarContainer.load(new URL(Potree.scriptPath + '/sidebar.html').href, () => {
  1047. sidebarContainer.css('width', '300px');
  1048. sidebarContainer.css('height', '100%');
  1049. let imgMenuToggle = document.createElement('img');
  1050. imgMenuToggle.src = new URL(Potree.resourcePath + '/icons/menu_button.svg').href;
  1051. imgMenuToggle.onclick = this.toggleSidebar;
  1052. imgMenuToggle.classList.add('potree_menu_toggle');
  1053. let imgMapToggle = document.createElement('img');
  1054. imgMapToggle.src = new URL(Potree.resourcePath + '/icons/map_icon.png').href;
  1055. imgMapToggle.style.display = 'none';
  1056. imgMapToggle.onclick = e => { this.toggleMap(); };
  1057. imgMapToggle.id = 'potree_map_toggle';
  1058. let elButtons = $("#potree_quick_buttons").get(0);
  1059. elButtons.append(imgMenuToggle);
  1060. elButtons.append(imgMapToggle);
  1061. /*
  1062. VRButton.createButton(this.renderer).then(vrButton => {
  1063. if(vrButton == null){
  1064. console.log("VR not supported or active.");
  1065. return;
  1066. }
  1067. this.renderer.xr.enabled = true;
  1068. let element = vrButton.element;
  1069. element.style.position = "";
  1070. element.style.bottom = "";
  1071. element.style.left = "";
  1072. element.style.margin = "4px";
  1073. element.style.fontSize = "100%";
  1074. element.style.width = "2.5em";
  1075. element.style.height = "2.5em";
  1076. element.style.padding = "0";
  1077. element.style.textShadow = "black 2px 2px 2px";
  1078. element.style.display = "block";
  1079. elButtons.append(element);
  1080. vrButton.onStart(() => {
  1081. this.dispatchEvent({type: "vr_start"});
  1082. });
  1083. vrButton.onEnd(() => {
  1084. this.dispatchEvent({type: "vr_end"});
  1085. });
  1086. });
  1087. this.mapView = new MapView(this);
  1088. this.mapView.init(); */
  1089. i18n.init({
  1090. lng: 'en',
  1091. resGetPath: Potree.resourcePath + '/lang/__lng__/__ns__.json',
  1092. preload: ['en', 'fr', 'de', 'jp', 'se', 'es', 'zh'],
  1093. getAsync: true,
  1094. debug: false
  1095. }, function (t) {
  1096. // Start translation once everything is loaded
  1097. $('body').i18n();
  1098. });
  1099. $(() => {
  1100. //initSidebar(this);
  1101. let sidebar = new Sidebar(this);
  1102. sidebar.init();
  1103. this.sidebar = sidebar;
  1104. //if (callback) {
  1105. // $(callback);
  1106. //}
  1107. let elProfile = $('<div>').load(new URL(Potree.scriptPath + '/profile.html').href, () => {
  1108. $(document.body).append(elProfile.children());
  1109. this.profileWindow = new ProfileWindow(this);
  1110. this.profileWindowController = new ProfileWindowController(this);
  1111. $('#profile_window').draggable({
  1112. handle: $('#profile_titlebar'),
  1113. containment: $(document.body)
  1114. });
  1115. $('#profile_window').resizable({
  1116. containment: $(document.body),
  1117. handles: 'n, e, s, w'
  1118. });
  1119. $(() => {
  1120. this.guiLoaded = true;
  1121. for(let task of this.guiLoadTasks){
  1122. task();
  1123. }
  1124. });
  1125. });
  1126. });
  1127. });
  1128. return this.promiseGuiLoaded();
  1129. }
  1130. setLanguage (lang) {
  1131. i18n.setLng(lang);
  1132. $('body').i18n();
  1133. }
  1134. setServer (server) {
  1135. this.server = server;
  1136. }
  1137. initDragAndDrop(){
  1138. function allowDrag(e) {
  1139. e.dataTransfer.dropEffect = 'copy';
  1140. e.preventDefault();
  1141. }
  1142. let dropHandler = async (event) => {
  1143. console.log(event);
  1144. event.preventDefault();
  1145. for(const item of event.dataTransfer.items){
  1146. console.log(item);
  1147. if(item.kind !== "file"){
  1148. continue;
  1149. }
  1150. const file = item.getAsFile();
  1151. const isJson = file.name.toLowerCase().endsWith(".json");
  1152. const isGeoPackage = file.name.toLowerCase().endsWith(".gpkg");
  1153. if(isJson){
  1154. try{
  1155. const text = await file.text();
  1156. const json = JSON.parse(text);
  1157. if(json.type === "Potree"){
  1158. Potree.loadProject(viewer, json);
  1159. }
  1160. }catch(e){
  1161. console.error("failed to parse the dropped file as JSON");
  1162. console.error(e);
  1163. }
  1164. }else if(isGeoPackage){
  1165. const hasPointcloud = viewer.scene.pointclouds.length > 0;
  1166. if(!hasPointcloud){
  1167. let msg = "At least one point cloud is needed that specifies the ";
  1168. msg += "coordinate reference system before loading vector data.";
  1169. console.error(msg);
  1170. }else{
  1171. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  1172. proj4.defs("pointcloud", this.getProjection());
  1173. let transform = proj4("WGS84", "pointcloud");
  1174. const buffer = await file.arrayBuffer();
  1175. const params = {
  1176. transform: transform,
  1177. source: file.name,
  1178. };
  1179. const geo = await Potree.GeoPackageLoader.loadBuffer(buffer, params);
  1180. viewer.scene.addGeopackage(geo);
  1181. }
  1182. }
  1183. }
  1184. };
  1185. $("body")[0].addEventListener("dragenter", allowDrag);
  1186. $("body")[0].addEventListener("dragover", allowDrag);
  1187. $("body")[0].addEventListener("drop", dropHandler);
  1188. }
  1189. updateAnnotations () {
  1190. if(!this.visibleAnnotations){
  1191. this.visibleAnnotations = new Set();
  1192. }
  1193. this.scene.annotations.updateBounds();
  1194. this.scene.cameraP.updateMatrixWorld();
  1195. this.scene.cameraO.updateMatrixWorld();
  1196. let distances = [];
  1197. let renderAreaSize = this.renderer.getSize(new THREE.Vector2());
  1198. let viewer = this;
  1199. let visibleNow = [];
  1200. this.scene.annotations.traverse(annotation => {
  1201. if (annotation === this.scene.annotations) {
  1202. return true;
  1203. }
  1204. if (!annotation.visible) {
  1205. return false;
  1206. }
  1207. annotation.scene = this.scene;
  1208. let element = annotation.domElement;
  1209. let position = annotation.position.clone();
  1210. position.add(annotation.offset);
  1211. if (!position) {
  1212. position = annotation.boundingBox.getCenter(new THREE.Vector3());
  1213. }
  1214. let distance = viewer.scene.cameraP.position.distanceTo(position);
  1215. let radius = annotation.boundingBox.getBoundingSphere(new THREE.Sphere()).radius;
  1216. let screenPos = new THREE.Vector3();
  1217. let screenSize = 0;
  1218. {
  1219. // SCREEN POS
  1220. screenPos.copy(position).project(this.scene.getActiveCamera());
  1221. screenPos.x = renderAreaSize.x * (screenPos.x + 1) / 2;
  1222. screenPos.y = renderAreaSize.y * (1 - (screenPos.y + 1) / 2);
  1223. // SCREEN SIZE
  1224. if(viewer.scene.cameraMode == CameraMode.PERSPECTIVE) {
  1225. let fov = Math.PI * viewer.scene.cameraP.fov / 180;
  1226. let slope = Math.tan(fov / 2.0);
  1227. let projFactor = 0.5 * renderAreaSize.y / (slope * distance);
  1228. screenSize = radius * projFactor;
  1229. } else {
  1230. screenSize = Utils.projectedRadiusOrtho(radius, viewer.scene.cameraO.projectionMatrix, renderAreaSize.x, renderAreaSize.y);
  1231. }
  1232. }
  1233. element.css("left", screenPos.x + "px");
  1234. element.css("top", screenPos.y + "px");
  1235. //element.css("display", "block");
  1236. let zIndex = 10000000 - distance * (10000000 / this.scene.cameraP.far);
  1237. if(annotation.descriptionVisible){
  1238. zIndex += 10000000;
  1239. }
  1240. element.css("z-index", parseInt(zIndex));
  1241. if(annotation.children.length > 0){
  1242. let expand = screenSize > annotation.collapseThreshold || annotation.boundingBox.containsPoint(this.scene.getActiveCamera().position);
  1243. annotation.expand = expand;
  1244. if (!expand) {
  1245. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  1246. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  1247. if(inFrustum){
  1248. visibleNow.push(annotation);
  1249. }
  1250. }
  1251. return expand;
  1252. } else {
  1253. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  1254. let inFrustum = (screenPos.z >= -1 && screenPos.z <= 1);
  1255. if(inFrustum){
  1256. visibleNow.push(annotation);
  1257. }
  1258. }
  1259. });
  1260. let notVisibleAnymore = new Set(this.visibleAnnotations);
  1261. for(let annotation of visibleNow){
  1262. annotation.display = true;
  1263. notVisibleAnymore.delete(annotation);
  1264. }
  1265. this.visibleAnnotations = visibleNow;
  1266. for(let annotation of notVisibleAnymore){
  1267. annotation.display = false;
  1268. }
  1269. }
  1270. updateMaterialDefaults(pointcloud){
  1271. // PROBLEM STATEMENT:
  1272. // * [min, max] of intensity, source id, etc. are computed as point clouds are loaded
  1273. // * the point cloud material won't know the range it should use until some data is loaded
  1274. // * users can modify the range at runtime, but sensible default ranges should be
  1275. // applied even if no GUI is present
  1276. // * display ranges shouldn't suddenly change even if the actual range changes over time.
  1277. // e.g. the root node has intensity range [1, 478]. One of the descendants increases range to
  1278. // [0, 2047]. We should not automatically change to the new range because that would result
  1279. // in sudden and drastic changes of brightness. We should adjust the min/max of the sidebar slider.
  1280. const material = pointcloud.material;
  1281. const attIntensity = pointcloud.getAttribute("intensity");
  1282. if(attIntensity != null && material.intensityRange[0] === Infinity){
  1283. material.intensityRange = [...attIntensity.range];
  1284. }
  1285. // const attIntensity = pointcloud.getAttribute("intensity");
  1286. // if(attIntensity && material.intensityRange[0] === Infinity){
  1287. // material.intensityRange = [...attIntensity.range];
  1288. // }
  1289. // let attributes = pointcloud.getAttributes();
  1290. // for(let attribute of attributes.attributes){
  1291. // if(attribute.range){
  1292. // let range = [...attribute.range];
  1293. // material.computedRange.set(attribute.name, range);
  1294. // //material.setRange(attribute.name, range);
  1295. // }
  1296. // }
  1297. }
  1298. update(delta, timestamp){
  1299. if(Potree.measureTimings) performance.mark("update-start");
  1300. this.dispatchEvent({
  1301. type: 'update_start',
  1302. delta: delta,
  1303. timestamp: timestamp});
  1304. this.updateScreenSize() //判断是否改变canvas大小
  1305. const scene = this.scene;
  1306. const camera = scene.getActiveCamera();
  1307. const visiblePointClouds = this.scene.pointclouds.filter(pc => pc.visible)
  1308. Potree.pointLoadLimit = Potree.pointBudget * 2;
  1309. const lTarget = camera.position.clone().add(camera.getWorldDirection(new THREE.Vector3()).multiplyScalar(1000));
  1310. this.scene.directionalLight.position.copy(camera.position);
  1311. this.scene.directionalLight.lookAt(lTarget);
  1312. for (let pointcloud of visiblePointClouds) {
  1313. pointcloud.showBoundingBox = this.showBoundingBox;
  1314. pointcloud.generateDEM = this.generateDEM;
  1315. pointcloud.minimumNodePixelSize = this.minNodeSize;
  1316. let material = pointcloud.material;
  1317. material.uniforms.uFilterReturnNumberRange.value = this.filterReturnNumberRange;
  1318. material.uniforms.uFilterNumberOfReturnsRange.value = this.filterNumberOfReturnsRange;
  1319. material.uniforms.uFilterGPSTimeClipRange.value = this.filterGPSTimeRange;
  1320. material.uniforms.uFilterPointSourceIDClipRange.value = this.filterPointSourceIDRange;
  1321. material.classification = this.classifications;
  1322. material.recomputeClassification();
  1323. this.updateMaterialDefaults(pointcloud);
  1324. }
  1325. {
  1326. if(this.showBoundingBox){
  1327. let bbRoot = this.scene.scene.getObjectByName("potree_bounding_box_root");
  1328. if(!bbRoot){
  1329. let node = new THREE.Object3D();
  1330. node.name = "potree_bounding_box_root";
  1331. this.scene.scene.add(node);
  1332. bbRoot = node;
  1333. }
  1334. let visibleBoxes = [];
  1335. for(let pointcloud of this.scene.pointclouds){
  1336. for(let node of pointcloud.visibleNodes.filter(vn => vn.boundingBoxNode !== undefined)){
  1337. let box = node.boundingBoxNode;
  1338. visibleBoxes.push(box);
  1339. }
  1340. }
  1341. bbRoot.children = visibleBoxes;
  1342. }
  1343. }
  1344. if (!this.freeze) {
  1345. /*let cameraGroup = []
  1346. let size = this.renderer.getSize(new THREE.Vector2())
  1347. if(this.viewports){
  1348. this.viewports.forEach(viewport=>{
  1349. if(!viewport.active)return
  1350. cameraGroup.push({camera:viewport.camera, areaSize:new THREE.Vector2(Math.floor(size.x * viewport.width), Math.floor(size.y * viewport.height))})
  1351. })
  1352. }else{
  1353. cameraGroup.push({camera, areaSize:size})
  1354. }
  1355. let result = Potree.updatePointClouds(scene.pointclouds, cameraGroup );
  1356. */
  1357. // DEBUG - ONLY DISPLAY NODES THAT INTERSECT MOUSE
  1358. //if(false){
  1359. // let renderer = viewer.renderer;
  1360. // let mouse = viewer.inputHandler.mouse;
  1361. // let nmouse = {
  1362. // x: (mouse.x / renderer.domElement.clientWidth) * 2 - 1,
  1363. // y: -(mouse.y / renderer.domElement.clientHeight) * 2 + 1
  1364. // };
  1365. // let pickParams = {};
  1366. // //if(params.pickClipped){
  1367. // // pickParams.pickClipped = params.pickClipped;
  1368. // //}
  1369. // pickParams.x = mouse.x;
  1370. // pickParams.y = renderer.domElement.clientHeight - mouse.y;
  1371. // let raycaster = new THREE.Raycaster();
  1372. // raycaster.setFromCamera(nmouse, camera);
  1373. // let ray = raycaster.ray;
  1374. // for(let pointcloud of scene.pointclouds){
  1375. // let nodes = pointcloud.nodesOnRay(pointcloud.visibleNodes, ray);
  1376. // pointcloud.visibleNodes = nodes;
  1377. // }
  1378. //}
  1379. // const tStart = performance.now();
  1380. // const worldPos = new THREE.Vector3();
  1381. // const camPos = viewer.scene.getActiveCamera().getWorldPosition(new THREE.Vector3());
  1382. // let lowestDistance = Infinity;
  1383. // let numNodes = 0;
  1384. // viewer.scene.scene.traverse(node => {
  1385. // node.getWorldPosition(worldPos);
  1386. // const distance = worldPos.distanceTo(camPos);
  1387. // lowestDistance = Math.min(lowestDistance, distance);
  1388. // numNodes++;
  1389. // if(Number.isNaN(distance)){
  1390. // console.error(":(");
  1391. // }
  1392. // });
  1393. // const duration = (performance.now() - tStart).toFixed(2);
  1394. // Potree.debug.computeNearDuration = duration;
  1395. // Potree.debug.numNodes = numNodes;
  1396. //console.log(lowestDistance.toString(2), duration);
  1397. //搬走
  1398. /* const tStart = performance.now();
  1399. const campos = camera.position;
  1400. let closestImage = Infinity;
  1401. for(const images of this.scene.orientedImages){
  1402. for(const image of images.images){
  1403. const distance = image.mesh.position.distanceTo(campos);
  1404. closestImage = Math.min(closestImage, distance);
  1405. }
  1406. }
  1407. const tEnd = performance.now();
  1408. if(result.lowestSpacing !== Infinity){
  1409. let near = result.lowestSpacing * 10.0;
  1410. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  1411. far = Math.max(far * 1.5, 10000);
  1412. near = Math.min(100.0, Math.max(0.01, near));
  1413. near = Math.min(near, closestImage);
  1414. far = Math.max(far, near + 10000);
  1415. if(near === Infinity){
  1416. near = 0.1;
  1417. }
  1418. camera.near = near;
  1419. camera.far = far;
  1420. }else{
  1421. // don't change near and far in this case
  1422. }
  1423. if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {
  1424. camera.near = -camera.far;
  1425. }*/
  1426. }
  1427. this.scene.cameraP.fov = this.fov;
  1428. let controls = this.getControls();
  1429. if (controls === this.deviceControls) {
  1430. this.controls.setScene(scene);
  1431. this.controls.update(delta);
  1432. this.scene.cameraP.position.copy(scene.view.position);
  1433. this.scene.cameraO.position.copy(scene.view.position);
  1434. } else if (controls !== null) {
  1435. controls.setScene(scene);
  1436. controls.update(delta);
  1437. //更新camera
  1438. this.viewports.forEach(viewport=>{
  1439. if(!viewport.active)return
  1440. viewport.view.applyToCamera(viewport.camera)
  1441. })
  1442. }
  1443. /* this.viewports.forEach(e=>{//判断camera画面是否改变
  1444. if(e.cameraChanged()){
  1445. this.dispatchEvent({
  1446. type: "camera_changed",
  1447. camera: e.camera,
  1448. viewport : e
  1449. })
  1450. }
  1451. }) */
  1452. this.cameraChanged()//判断camera画面是否改变
  1453. /* {//判断camera画面是否改变
  1454. if(this._previousCamera === undefined){
  1455. this._previousCamera = this.scene.getActiveCamera().clone();
  1456. this._previousCamera.rotation.copy(this.scene.getActiveCamera().rotation);
  1457. }
  1458. if(!this._previousCamera.matrixWorld.equals(camera.matrixWorld) ||
  1459. !this._previousCamera.projectionMatrix.equals(camera.projectionMatrix)
  1460. ){
  1461. this.dispatchEvent({
  1462. type: "camera_changed",
  1463. previous: this._previousCamera,
  1464. camera: camera
  1465. });
  1466. }
  1467. this._previousCamera = this.scene.getActiveCamera().clone();
  1468. this._previousCamera.rotation.copy(this.scene.getActiveCamera().rotation);
  1469. } */
  1470. { // update clip boxes
  1471. let boxes = [];
  1472. // volumes with clipping enabled
  1473. //boxes.push(...this.scene.volumes.filter(v => (v.clip)));
  1474. boxes.push(...this.scene.volumes.filter(v => (v.clip && v instanceof BoxVolume)));
  1475. // profile segments
  1476. for(let profile of this.scene.profiles){
  1477. boxes.push(...profile.boxes);
  1478. }
  1479. // Needed for .getInverse(), pre-empt a determinant of 0, see #815 / #816
  1480. let degenerate = (box) => box.matrixWorld.determinant() !== 0;
  1481. let clipBoxes = boxes.filter(degenerate).map( box => {
  1482. box.updateMatrixWorld();
  1483. let boxInverse = box.matrixWorld.clone().invert();
  1484. let boxPosition = box.getWorldPosition(new THREE.Vector3());
  1485. return {box: box, inverse: boxInverse, position: boxPosition};
  1486. });
  1487. let clipPolygons = this.scene.polygonClipVolumes.filter(vol => vol.initialized);
  1488. // set clip volumes in material
  1489. for(let pointcloud of visiblePointClouds){
  1490. pointcloud.material.setClipBoxes(clipBoxes);
  1491. pointcloud.material.setClipPolygons(clipPolygons, this.clippingTool.maxPolygonVertices);
  1492. pointcloud.material.clipTask = this.clipTask;
  1493. pointcloud.material.clipMethod = this.clipMethod;
  1494. }
  1495. }
  1496. {
  1497. for(let pointcloud of visiblePointClouds){
  1498. pointcloud.material.elevationGradientRepeat = this.elevationGradientRepeat;
  1499. }
  1500. }
  1501. { // update navigation cube
  1502. this.navigationCube.update(camera.rotation);
  1503. }
  1504. this.updateAnnotations();
  1505. if(this.mapView){
  1506. this.mapView.update(delta);
  1507. if(this.mapView.sceneProjection){
  1508. $( "#potree_map_toggle" ).css("display", "block");
  1509. }
  1510. }
  1511. TWEEN.update(timestamp);
  1512. transitions.update(delta);
  1513. this.dispatchEvent({
  1514. type: 'update',
  1515. delta: delta,
  1516. timestamp: timestamp});
  1517. if(Potree.measureTimings) {
  1518. performance.mark("update-end");
  1519. performance.measure("update", "update-start", "update-end");
  1520. }
  1521. //add ------
  1522. this.reticule.updateVisible()
  1523. this.mapViewer.update(delta)
  1524. }
  1525. updateViewPointcloud(camera, areaSize, isViewport){
  1526. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, areaSize );
  1527. //if(isViewport)return
  1528. const tStart = performance.now();
  1529. const campos = camera.position;
  1530. let closestImage = Infinity;
  1531. for(const images of this.scene.orientedImages){
  1532. for(const image of images.images){
  1533. const distance = image.mesh.position.distanceTo(campos);
  1534. closestImage = Math.min(closestImage, distance);
  1535. }
  1536. }
  1537. const tEnd = performance.now();
  1538. //改:不根据点云修改视野near far
  1539. var near = camera.near, far = camera.far
  1540. if(!camera.limitFar && result.lowestSpacing !== Infinity){
  1541. let near = result.lowestSpacing * 10.0;
  1542. let far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  1543. far = Math.max(far * 1.5, 10000);
  1544. near = Math.min(100.0, Math.max(0.01, near));
  1545. near = Math.min(near, closestImage);
  1546. far = Math.max(far, near + 10000);
  1547. if(near === Infinity){
  1548. near = 0.1;
  1549. }
  1550. camera.near = near;
  1551. camera.far = far;
  1552. }
  1553. if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {//???
  1554. camera.near = -camera.far;
  1555. }
  1556. if(near != camera.near || far != camera.far){
  1557. camera.updateProjectionMatrix()
  1558. }
  1559. //注:pointcloud.visibleNodes会随着near far自动更新
  1560. }
  1561. getPRenderer(){
  1562. if(this.useHQ){
  1563. if (!this.hqRenderer) {
  1564. this.hqRenderer = new HQSplatRenderer(this);
  1565. }
  1566. this.hqRenderer.useEDL = this.useEDL;
  1567. return this.hqRenderer;
  1568. }else{
  1569. /* if (this.useEDL && Features.SHADER_EDL.isSupported()) {
  1570. if (!this.edlRenderer) {
  1571. this.edlRenderer = new EDLRenderer(this);
  1572. }
  1573. return this.edlRenderer;
  1574. } else {
  1575. if (!this.potreeRenderer) {
  1576. this.potreeRenderer = new PotreeRenderer(this);
  1577. }
  1578. return this.potreeRenderer;
  1579. } */
  1580. if (!this.edlRenderer) {
  1581. this.edlRenderer = new EDLRenderer(this);
  1582. }
  1583. return this.edlRenderer;
  1584. }
  1585. }
  1586. renderVR(){
  1587. let renderer = this.renderer;
  1588. renderer.setClearColor(0x550000, 0);
  1589. renderer.clear();
  1590. let xr = renderer.xr;
  1591. let dbg = new THREE.PerspectiveCamera();
  1592. let xrCameras = xr.getCamera(dbg);
  1593. if(xrCameras.cameras.length !== 2){
  1594. return;
  1595. }
  1596. let makeCam = this.vrControls.getCamera.bind(this.vrControls);
  1597. { // clear framebuffer
  1598. if(viewer.background === "skybox"){
  1599. renderer.setClearColor(0xff0000, 1);
  1600. }else if(viewer.background === "gradient"){
  1601. renderer.setClearColor(0x112233, 1);
  1602. }else if(viewer.background === "black"){
  1603. renderer.setClearColor(0x000000, 1);
  1604. }else if(viewer.background === "white"){
  1605. renderer.setClearColor(0xFFFFFF, 1);
  1606. }else{
  1607. renderer.setClearColor(0x000000, 0);
  1608. }
  1609. renderer.clear();
  1610. }
  1611. // render background
  1612. if(this.background === "skybox"){
  1613. let {skybox} = this;
  1614. let cam = makeCam();
  1615. skybox.camera.rotation.copy(cam.rotation);
  1616. skybox.camera.fov = cam.fov;
  1617. skybox.camera.aspect = cam.aspect;
  1618. // let dbg = new THREE.Object3D();
  1619. let dbg = skybox.parent;
  1620. // dbg.up.set(0, 0, 1);
  1621. dbg.rotation.x = Math.PI / 2;
  1622. // skybox.camera.parent = dbg;
  1623. // dbg.children.push(skybox.camera);
  1624. dbg.updateMatrix();
  1625. dbg.updateMatrixWorld();
  1626. skybox.camera.updateMatrix();
  1627. skybox.camera.updateMatrixWorld();
  1628. skybox.camera.updateProjectionMatrix();
  1629. renderer.render(skybox.scene, skybox.camera);
  1630. // renderer.render(skybox.scene, cam);
  1631. }else if(this.background === "gradient"){
  1632. // renderer.render(this.scene.sceneBG, this.scene.cameraBG);
  1633. }
  1634. this.renderer.xr.getSession().updateRenderState({
  1635. depthNear: 0.1,
  1636. depthFar: 10000
  1637. });
  1638. let cam = null;
  1639. let view = null;
  1640. { // render world scene
  1641. cam = makeCam();
  1642. cam.position.z -= 0.8 * cam.scale.x;
  1643. cam.parent = null;
  1644. // cam.near = 0.05;
  1645. cam.near = viewer.scene.getActiveCamera().near;
  1646. cam.far = viewer.scene.getActiveCamera().far;
  1647. cam.updateMatrix();
  1648. cam.updateMatrixWorld();
  1649. this.scene.scene.updateMatrix();
  1650. this.scene.scene.updateMatrixWorld();
  1651. this.scene.scene.matrixAutoUpdate = false;
  1652. let camWorld = cam.matrixWorld.clone();
  1653. view = camWorld.clone().invert();
  1654. this.scene.scene.matrix.copy(view);
  1655. this.scene.scene.matrixWorld.copy(view);
  1656. cam.matrix.identity();
  1657. cam.matrixWorld.identity();
  1658. cam.matrixWorldInverse.identity();
  1659. renderer.render(this.scene.scene, cam);
  1660. this.scene.scene.matrixWorld.identity();
  1661. }
  1662. for(let pointcloud of this.scene.pointclouds){
  1663. let viewport = xrCameras.cameras[0].viewport;
  1664. pointcloud.material.useEDL = false;
  1665. pointcloud.screenHeight = viewport.height;
  1666. pointcloud.screenWidth = viewport.width;
  1667. // automatically switch to paraboloids because they cause far less flickering in VR,
  1668. // when point sizes are larger than around 2 pixels
  1669. // if(Features.SHADER_INTERPOLATION.isSupported()){
  1670. // pointcloud.material.shape = Potree.PointShape.PARABOLOID;
  1671. // }
  1672. }
  1673. // render point clouds
  1674. for(let xrCamera of xrCameras.cameras){
  1675. let v = xrCamera.viewport;
  1676. renderer.setViewport(v.x, v.y, v.width, v.height);
  1677. // xrCamera.fov = 90;
  1678. { // estimate VR fov
  1679. let proj = xrCamera.projectionMatrix;
  1680. let inv = proj.clone().invert();
  1681. let p1 = new THREE.Vector4(0, 1, -1, 1).applyMatrix4(inv);
  1682. let rad = p1.y
  1683. let fov = 180 * (rad / Math.PI);
  1684. xrCamera.fov = fov;
  1685. }
  1686. for(let pointcloud of this.scene.pointclouds){
  1687. const {material} = pointcloud;
  1688. material.useEDL = false;
  1689. }
  1690. let vrWorld = view.clone().invert();
  1691. vrWorld.multiply(xrCamera.matrixWorld);
  1692. let vrView = vrWorld.clone().invert();
  1693. this.pRenderer.render(this.scene.scenePointCloud, xrCamera, null, {
  1694. viewOverride: vrView,
  1695. });
  1696. }
  1697. { // render VR scene
  1698. let cam = makeCam();
  1699. cam.parent = null;
  1700. renderer.render(this.sceneVR, cam);
  1701. }
  1702. renderer.resetState();
  1703. }
  1704. clear(params={}){
  1705. let background = params.background || this.background;
  1706. let backgroundOpacity = params.backgroundOpacity == void 0 ? this.backgroundOpacity : params.backgroundOpacity//如果想完全透明,只需要backgroundOpacity为0
  1707. let renderer = this.renderer
  1708. //let gl = renderer.getContext()
  1709. if(background instanceof THREE.Color){ //add
  1710. renderer.setClearColor(background, backgroundOpacity);
  1711. }else if(background === "skybox"){
  1712. renderer.setClearColor(0x000000, 0);
  1713. } else if (background === 'gradient') {
  1714. renderer.setClearColor(0x000000, 0);
  1715. } else if (background === 'black') {
  1716. renderer.setClearColor(0x000000, 1);
  1717. } else if (background === 'white') {
  1718. renderer.setClearColor(0xFFFFFF, 1);
  1719. } else {
  1720. renderer.setClearColor(0x000000, 0);
  1721. }
  1722. params.target || renderer.clear();
  1723. }
  1724. renderDefault(params_={}){
  1725. let pRenderer = this.getPRenderer();
  1726. let renderSize
  1727. if(params_.target){
  1728. renderSize = new THREE.Vector2(params_.target.width, params_.target.height)
  1729. if(!params_.viewports){
  1730. console.warn('必须指定target的viewport! 且target大小和viewport.resolution2相同')
  1731. }
  1732. }else{
  1733. renderSize = this.renderer.getSize(new THREE.Vector2());
  1734. }
  1735. var viewports = params_.viewports || this.viewports
  1736. let needSResize = viewports.filter(e=>e.active).length > 1 || params_.resize
  1737. viewports.forEach(view=>{
  1738. let params = $.extend({},params_);
  1739. //if(!params.target){
  1740. params.camera = params.camera || view.camera;
  1741. params.extraEnableLayers = view.extraEnableLayers
  1742. //}
  1743. if(!view.active)return
  1744. var left,bottom,width,height
  1745. {
  1746. left = Math.floor(renderSize.x * view.left)
  1747. bottom = Math.floor(renderSize.y * view.bottom)
  1748. /* if(params_.target){//有target时最好viewport是专门建出来的
  1749. width = Math.floor(renderSize.x * view.width)
  1750. height = Math.floor(renderSize.y * view.height)
  1751. }else{ */
  1752. width = view.resolution.x // 用的是client的width和height
  1753. height = view.resolution.y
  1754. //}
  1755. if(width == 0 || height == 0)return
  1756. let scissorTest = view.width<1 || view.height<1
  1757. if(params_.target){
  1758. params_.target.viewport.set(left, bottom, width, height);
  1759. scissorTest && params_.target.scissor.set(left, bottom, width, height);
  1760. params_.target.scissorTest = scissorTest
  1761. }else{
  1762. this.renderer.setViewport(left, bottom, width, height) //规定视口,影响图形变换
  1763. scissorTest && this.renderer.setScissor( left, bottom, width, height );//规定渲染范围
  1764. this.renderer.setScissorTest( scissorTest );//开启WebGL剪裁测试功能,如果不开启,.setScissor方法设置的范围不起作用 | width==1且height==1时开启会只有鼠标的地方刷新,很奇怪
  1765. }
  1766. }
  1767. if(needSResize){
  1768. this.emitResizeMsg( { viewport:view} )
  1769. }
  1770. //needSResize && this.emitResizeMsg({resolution: params_.target ? new THREE.Vector2(width,height) : view.resolution2, left:view.left, bottom:view.bottom })//resize everything such as lines targets
  1771. viewer.dispatchEvent({type: "render.begin", viewer: viewer, viewport:view, params });
  1772. if(view.render){
  1773. view.render({
  1774. target: params_.target, renderer:this.renderer, clear:this.clear.bind(this),
  1775. renderOverlay: this.renderOverlay.bind(this), force:!view.noPointcloud //如果要渲染点云,必须也一直渲染地图,否则地图会被覆盖(点云目前未能获取是否改变,也可能有其他动态物体,所以还是一直渲染的好)
  1776. })
  1777. }
  1778. if(!view.noPointcloud ){
  1779. //if(!params.target){
  1780. params.width = width; params.height = height;
  1781. //}
  1782. if(view.render){
  1783. params.noBG = true
  1784. }
  1785. view.beforeRender && view.beforeRender(view)
  1786. this.updateViewPointcloud(params.camera, new THREE.Vector2(params.width,params.height), true)
  1787. params.background = view.background
  1788. params.backgroundColor = view.backgroundColor
  1789. params.backgroundOpacity = view.backgroundOpacity
  1790. view.render || this.clear(params)
  1791. pRenderer.clearTargets(params);
  1792. pRenderer.render(params);
  1793. this.renderOverlay(params)
  1794. }
  1795. this.dispatchEvent({type: "render.end", viewer: this, viewport:view });
  1796. })
  1797. this.renderer.setRenderTarget(null)
  1798. }
  1799. renderOverlay(params){
  1800. let camera = params.camera ? params.camera : this.scene.getActiveCamera();
  1801. if(!params.magnifier){//为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖
  1802. this.setCameraLayers(camera, ['sceneObjects','marker','reticule','route'], params.extraEnableLayers) //透明贴图层 skybox 、reticule marker 不能遮住测量线
  1803. this.renderer.render(this.scene.scene, camera);
  1804. }
  1805. this.dispatchEvent({type: "render.pass.scene", viewer: viewer});
  1806. //清除深度 !!!!
  1807. this.renderer.clearDepth();
  1808. this.transformationTool.update();
  1809. if(!params.magnifier){
  1810. //测量线
  1811. this.dispatchEvent({type: "render.pass.perspective_overlay", camera});
  1812. if(!params.screenshot && !params.isMap){
  1813. this.setCameraLayers(camera, ['magnifier']) //magnifier 遮住测量线
  1814. this.renderer.render(this.scene.scene, camera);
  1815. }
  1816. }
  1817. this.setCameraLayers(camera, ['volume','transformationTool'])
  1818. this.renderer.render(this.clippingTool.sceneVolume, camera);
  1819. this.renderer.render(this.transformationTool.scene, camera);
  1820. }
  1821. setCameraLayers(camera, enableLayers, extraEnableLayers=[]){//add
  1822. camera.layers.disableAll()
  1823. enableLayers.concat(extraEnableLayers).forEach(e=>{
  1824. let layer = Potree.config.renderLayers[e]
  1825. if(layer == void 0){
  1826. console.error('setCameraLayer没找到layer!');
  1827. return
  1828. }
  1829. camera.layers.enable(layer)
  1830. })
  1831. }
  1832. setObjectLayers(object, layerName){//add
  1833. let layer = Potree.config.renderLayers[layerName]
  1834. if(layer == void 0){
  1835. console.error('setCameraLayer没找到layer!');
  1836. return
  1837. }
  1838. object.traverse(e=>{
  1839. e.layers.set(layer)
  1840. })
  1841. }
  1842. updateVisible(object, reason, ifShow){//当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  1843. if(!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  1844. if(ifShow){
  1845. var index = object.unvisibleReasons.indexOf(reason)
  1846. index > -1 && object.unvisibleReasons.splice(index, 1)
  1847. if(object.unvisibleReasons.length == 0){
  1848. object.visible = true;
  1849. object.dispatchEvent({
  1850. type: 'isVisible',
  1851. visible:true
  1852. })
  1853. }
  1854. }else{
  1855. var visiBefore = object.visible
  1856. if(!object.unvisibleReasons.includes(reason)) object.unvisibleReasons.push(reason)
  1857. object.visible = false
  1858. visiBefore && object.dispatchEvent({
  1859. type: 'isVisible',
  1860. visible:false,
  1861. reason,
  1862. })
  1863. }
  1864. }
  1865. getObjVisiByReason(object,reason){//获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  1866. if(object.visible)return true
  1867. else{
  1868. return !object.unvisibleReasons || !object.unvisibleReasons.includes(reason)
  1869. }
  1870. }
  1871. render(params){//add params
  1872. if(Potree.measureTimings) performance.mark("render-start");
  1873. //try{
  1874. const vrActive = this.renderer.xr.isPresenting;
  1875. if(vrActive){
  1876. this.renderVR();
  1877. }else{
  1878. this.renderDefault(params);
  1879. }
  1880. /* }catch(e){
  1881. this.onCrash(e);
  1882. } */
  1883. if(Potree.measureTimings){
  1884. performance.mark("render-end");
  1885. performance.measure("render", "render-start", "render-end");
  1886. }
  1887. }
  1888. startScreenshot(info={}, width=800, height=400, compressRatio){//add
  1889. //抗锯齿待加 1 post处理 2截图大张再抗锯齿缩小
  1890. let deferred = $.Deferred();
  1891. var screenshot = ()=>{
  1892. var { buffer } = this.makeScreenshot( new THREE.Vector2(width,height) );
  1893. var dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio)
  1894. if(!Potree.settings.isOfficial){
  1895. Common.downloadFile(dataUrl, 'screenshot.jpg')
  1896. }
  1897. deferred.resolve(dataUrl)
  1898. {//恢复:
  1899. if(info.type == 'measure'){
  1900. this.scene.measurements.forEach(e=>this.updateVisible(e, 'screenshot',true))
  1901. }
  1902. this.images360.panos.forEach(pano=>{
  1903. viewer.updateVisible(pano, 'screenshot', true)
  1904. })
  1905. viewer.updateVisible(this.reticule, 'screenshot', true)
  1906. viewer.updateVisible(this.mapViewer.cursor, 'screenshot', true)
  1907. if(oldStates.attachedToViewer != this.mapViewer.attachedToViewer){
  1908. if(info.type == 'measure'){
  1909. this.mapViewer.attachToMainViewer(false)
  1910. }
  1911. }
  1912. mapViewport.camera.zoom = oldStates.mapZoom
  1913. oldStates.viewports.forEach(old=>{//恢复相机
  1914. var viewport = [mapViewport, mainViewport].find(v=>v.name == old.name);
  1915. viewport.left = old.left;
  1916. viewport.width = old.width;
  1917. viewport.view.copy(old.view)
  1918. viewport.view.applyToCamera(viewport.camera);
  1919. })
  1920. viewer.updateScreenSize({forceUpdateSize:true})//更新像素
  1921. oldStates.viewports.forEach(old=>{//恢复相机
  1922. var viewport = [mapViewport, mainViewport].find(v=>v.name == old.name);
  1923. this.dispatchEvent({ //update map
  1924. type: "camera_changed",
  1925. camera: viewport.camera,
  1926. viewport : viewport
  1927. })
  1928. })
  1929. }
  1930. }
  1931. let mapViewport = this.mapViewer.viewports[0]
  1932. let mainViewport = this.mainViewport
  1933. let oldStates = {
  1934. attachedToViewer : this.mapViewer.attachedToViewer,
  1935. viewports : [mapViewport, mainViewport].map(e=>{
  1936. return e.clone()
  1937. }),
  1938. mapZoom: mapViewport.camera.zoom
  1939. }
  1940. //令漫游点不可见
  1941. this.images360.panos.forEach(pano=>{
  1942. viewer.updateVisible(pano, 'screenshot', false)
  1943. })
  1944. //令reticule不可见
  1945. viewer.updateVisible(this.reticule, 'screenshot', false)
  1946. //令mapCursor不可见
  1947. viewer.updateVisible(this.mapViewer.cursor, 'screenshot', false)
  1948. if(info.type == 'measure'){//要截图双屏
  1949. this.scene.measurements.forEach(e=>this.updateVisible(e,'screenshot',e == info.measurement) )
  1950. this.mapViewer.attachToMainViewer(true, 'measure', 0.5)
  1951. viewer.updateScreenSize({forceUpdateSize:true, width, height}) //更新viewports相机透视
  1952. //不同角度截图 得到三维的会不一样,因为focusOnObject是根据方向的
  1953. let promise = this.focusOnObject(info.measurement, 'measure', 0, /* {mapDont:true} */)
  1954. promise.done(()=>{
  1955. this.viewports.forEach(e=>{
  1956. e.view.applyToCamera(e.camera)
  1957. this.dispatchEvent({ //update map
  1958. type: "camera_changed",
  1959. camera: e.camera,
  1960. viewport : e
  1961. })
  1962. })
  1963. this.mapViewer.waitLoadDone(screenshot.bind(this))//等待地图所有加载完
  1964. })
  1965. }else{
  1966. screenshot()
  1967. }
  1968. return deferred.promise()
  1969. }
  1970. focusOnObject(object, type, duration, o={} ) {
  1971. //飞向热点、测量线等 。
  1972. let deferred = $.Deferred();
  1973. let target = new THREE.Vector3,
  1974. position = new THREE.Vector3,
  1975. dis;
  1976. duration = duration == void 0 ? 2000 : duration;
  1977. let camera = viewer.scene.getActiveCamera()
  1978. if (type == 'measure') {
  1979. let bound = new THREE.Box3()
  1980. object.points.forEach(p => bound.expandByPoint(p))
  1981. let boundSize = bound.getSize(new THREE.Vector3)
  1982. let {center,radius} = bound.getBoundingSphere({center:new THREE.Vector3}) //用不box的算不准,就保守用sphere了,缺点是无法占满屏,优点是不会靠太近
  1983. target.copy(object.getCenter())//copy(center)
  1984. let aspect = 1
  1985. if(camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  1986. dis = radius/ THREE.Math.degToRad(camera.fov / 2)
  1987. }else{
  1988. let hfov = cameraLight.getHFOVForCamera(camera, camera.aspect, 1 );
  1989. dis = radius / THREE.Math.degToRad(hfov / 2)
  1990. }
  1991. if(o.mapDont || this.mapViewer.attachedToViewer){
  1992. this.mapViewer.fitToBound(target.clone(), boundSize.clone().multiplyScalar(2), duration)
  1993. }
  1994. if(Potree.settings.displayMode == 'showPointCloud'){
  1995. let dir = new THREE.Vector3().subVectors(camera.position, target).normalize()
  1996. position.copy(target).add(dir.multiplyScalar(dis))
  1997. }else if(Potree.settings.displayMode == 'showPanos'){
  1998. let pano = viewer.images360.fitPanoTowardPoint({
  1999. point : target,
  2000. bestDistance : dis * 0.5 //乘以小数是为了尽量靠近
  2001. })
  2002. pano && viewer.images360.flyToPano({pano, target, duration, deferred })
  2003. return deferred
  2004. }
  2005. } else if (type == 'tag') {
  2006. const bestDistance = 2
  2007. target.copy(object.position)
  2008. if(Potree.settings.displayMode == 'showPointCloud'){
  2009. dis = bestDistance
  2010. let dir = new THREE.Vector3().subVectors(camera.position, target).normalize()
  2011. position.copy(target).add(dir.multiplyScalar(dis))
  2012. }else if(Potree.settings.displayMode == 'showPanos'){
  2013. let pano = viewer.images360.fitPanoTowardPoint({
  2014. point : target,
  2015. bestDistance //越近越好,但不要太近,bestDistance左右差不多
  2016. })
  2017. pano && viewer.images360.flyToPano({pano, target, duration, deferred })
  2018. return deferred
  2019. }
  2020. }
  2021. viewer.scene.view.setView(position, target, duration, ()=>{
  2022. deferred.resolve()
  2023. })
  2024. return deferred.promise()
  2025. }
  2026. resolveTimings(timestamp){
  2027. if(Potree.measureTimings){
  2028. if(!this.toggle){
  2029. this.toggle = timestamp;
  2030. }
  2031. let duration = timestamp - this.toggle;
  2032. if(duration > 1000.0){
  2033. let measures = performance.getEntriesByType("measure");
  2034. let names = new Set();
  2035. for(let measure of measures){
  2036. names.add(measure.name);
  2037. }
  2038. let groups = new Map();
  2039. for(let name of names){
  2040. groups.set(name, {
  2041. measures: [],
  2042. sum: 0,
  2043. n: 0,
  2044. min: Infinity,
  2045. max: -Infinity
  2046. });
  2047. }
  2048. for(let measure of measures){
  2049. let group = groups.get(measure.name);
  2050. group.measures.push(measure);
  2051. group.sum += measure.duration;
  2052. group.n++;
  2053. group.min = Math.min(group.min, measure.duration);
  2054. group.max = Math.max(group.max, measure.duration);
  2055. }
  2056. let glQueries = Potree.resolveQueries(this.renderer.getContext());
  2057. for(let [key, value] of glQueries){
  2058. let group = {
  2059. measures: value.map(v => {return {duration: v}}),
  2060. sum: value.reduce( (a, i) => a + i, 0),
  2061. n: value.length,
  2062. min: Math.min(...value),
  2063. max: Math.max(...value)
  2064. };
  2065. let groupname = `[tq] ${key}`;
  2066. groups.set(groupname, group);
  2067. names.add(groupname);
  2068. }
  2069. for(let [name, group] of groups){
  2070. group.mean = group.sum / group.n;
  2071. group.measures.sort( (a, b) => a.duration - b.duration );
  2072. if(group.n === 1){
  2073. group.median = group.measures[0].duration;
  2074. }else if(group.n > 1){
  2075. group.median = group.measures[parseInt(group.n / 2)].duration;
  2076. }
  2077. }
  2078. let cn = Array.from(names).reduce( (a, i) => Math.max(a, i.length), 0) + 5;
  2079. let cmin = 10;
  2080. let cmed = 10;
  2081. let cmax = 10;
  2082. let csam = 6;
  2083. let message = ` ${"NAME".padEnd(cn)} |`
  2084. + ` ${"MIN".padStart(cmin)} |`
  2085. + ` ${"MEDIAN".padStart(cmed)} |`
  2086. + ` ${"MAX".padStart(cmax)} |`
  2087. + ` ${"SAMPLES".padStart(csam)} \n`;
  2088. message += ` ${"-".repeat(message.length) }\n`;
  2089. names = Array.from(names).sort();
  2090. for(let name of names){
  2091. let group = groups.get(name);
  2092. let min = group.min.toFixed(3);
  2093. let median = group.median.toFixed(3);
  2094. let max = group.max.toFixed(3);
  2095. let n = group.n;
  2096. message += ` ${name.padEnd(cn)} |`
  2097. + ` ${min.padStart(cmin)} |`
  2098. + ` ${median.padStart(cmed)} |`
  2099. + ` ${max.padStart(cmax)} |`
  2100. + ` ${n.toString().padStart(csam)}\n`;
  2101. }
  2102. message += `\n`;
  2103. console.log(message);
  2104. performance.clearMarks();
  2105. performance.clearMeasures();
  2106. this.toggle = timestamp;
  2107. }
  2108. }
  2109. }
  2110. loop(timestamp){
  2111. if(this.stats){
  2112. this.stats.begin();
  2113. }
  2114. if(Potree.measureTimings){
  2115. performance.mark("loop-start");
  2116. }
  2117. this.update(this.clock.getDelta(), timestamp);
  2118. this.magnifier.render();
  2119. this.render();
  2120. // let vrActive = viewer.renderer.xr.isPresenting;
  2121. // if(vrActive){
  2122. // this.update(this.clock.getDelta(), timestamp);
  2123. // this.render();
  2124. // }else{
  2125. // this.update(this.clock.getDelta(), timestamp);
  2126. // this.render();
  2127. // }
  2128. if(Potree.measureTimings){
  2129. performance.mark("loop-end");
  2130. performance.measure("loop", "loop-start", "loop-end");
  2131. }
  2132. this.resolveTimings(timestamp);
  2133. Potree.framenumber++;
  2134. if(this.stats){
  2135. this.stats.end();
  2136. }
  2137. }
  2138. postError(content, params = {}){
  2139. let message = this.postMessage(content, params);
  2140. message.element.addClass("potree_message_error");
  2141. return message;
  2142. }
  2143. postMessage(content, params = {}){
  2144. let message = new Message(content);
  2145. let animationDuration = 100;
  2146. message.element.css("display", "none");
  2147. message.elClose.click( () => {
  2148. message.element.slideToggle(animationDuration);
  2149. let index = this.messages.indexOf(message);
  2150. if(index >= 0){
  2151. this.messages.splice(index, 1);
  2152. }
  2153. });
  2154. this.elMessages.prepend(message.element);
  2155. message.element.slideToggle(animationDuration);
  2156. this.messages.push(message);
  2157. if(params.duration !== undefined){
  2158. let fadeDuration = 500;
  2159. let slideOutDuration = 200;
  2160. setTimeout(() => {
  2161. message.element.animate({
  2162. opacity: 0
  2163. }, fadeDuration);
  2164. message.element.slideToggle(slideOutDuration);
  2165. }, params.duration)
  2166. }
  2167. return message;
  2168. }
  2169. getBoundingBox (pointclouds) {
  2170. //可以直接返回viewer.bound
  2171. if(!this.bound){
  2172. this.updateModelBound()
  2173. }
  2174. return this.bound.boundingBox.clone()//this.scene.getBoundingBox(pointclouds);
  2175. };
  2176. updateModelBound(){
  2177. this.bound = Utils.computePointcloudsBound(this.scene.pointclouds)
  2178. viewer.farWhenShowPano = this.bound.boundSize.length() * 2//全景漫游时要能看到整个skybox
  2179. }
  2180. waitForLoad(object, isLoadedCallback){//等待加载时显示loading。主要是贴图
  2181. this.waitQueue.push({
  2182. object,
  2183. isLoadedCallback,
  2184. })
  2185. 1 === this.waitQueue.length && this.emit("loading", true)
  2186. }
  2187. ifAllLoaded(object){
  2188. if(this.waitQueue.length>0){
  2189. this.waitQueue = this.waitQueue.filter(function(e) {
  2190. return !e.isLoadedCallback()
  2191. })
  2192. }
  2193. 0 === this.waitQueue.length && this.emit("loading", false)
  2194. }
  2195. setView(o={}){
  2196. let callback = ()=>{
  2197. if(o.displayMode){
  2198. Potree.settings.displayMode = o.displayMode
  2199. }
  2200. o.callback && o.callback()
  2201. }
  2202. if(o.pano != void 0){//pano 权重高于 position
  2203. this.images360.flyToPano(o)
  2204. }else{
  2205. this.scene.view.setView(o.position, o.target, o.duration, callback)
  2206. }
  2207. }
  2208. };
  2209. /* t.prototype.getTransformationMatrix = function(t) {//点云截取 所有点在乘上这个矩阵后, 还能落在 1 * 1 * 1的box内的点就是所裁剪的
  2210. var e = this.ViewService.mainView.getVolumeClippingLayer().getBoxFrame()
  2211. , n = (new o.Matrix4).getInverse(e.matrixWorld)
  2212. , i = t.m2w_;
  2213. return (new o.Matrix4).multiplyMatrices(n, i).transpose() */