PotreeRendererNew.js 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  1. import * as THREE from "../libs/three.js/build/three.module.js";
  2. import {PointCloudTree} from "./PointCloudTree.js";
  3. import {PointSizeType, ClipTask, ElevationGradientRepeat} from "./defines.js";
  4. // Copied from three.js: WebGLRenderer.js
  5. function paramThreeToGL(_gl, p) {
  6. let extension;
  7. if (p === THREE.RepeatWrapping) return _gl.REPEAT;
  8. if (p === THREE.ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  9. if (p === THREE.MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  10. if (p === THREE.NearestFilter) return _gl.NEAREST;
  11. if (p === THREE.NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  12. if (p === THREE.NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  13. if (p === THREE.LinearFilter) return _gl.LINEAR;
  14. if (p === THREE.LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  15. if (p === THREE.LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  16. if (p === THREE.UnsignedByteType) return _gl.UNSIGNED_BYTE;
  17. if (p === THREE.UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  18. if (p === THREE.UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  19. if (p === THREE.UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  20. if (p === THREE.ByteType) return _gl.BYTE;
  21. if (p === THREE.ShortType) return _gl.SHORT;
  22. if (p === THREE.UnsignedShortType) return _gl.UNSIGNED_SHORT;
  23. if (p === THREE.IntType) return _gl.INT;
  24. if (p === THREE.UnsignedIntType) return _gl.UNSIGNED_INT;
  25. if (p === THREE.FloatType) return _gl.FLOAT;
  26. if (p === THREE.HalfFloatType) {
  27. extension = extensions.get('OES_texture_half_float');
  28. if (extension !== null) return extension.HALF_FLOAT_OES;
  29. }
  30. if (p === THREE.AlphaFormat) return _gl.ALPHA;
  31. if (p === THREE.RGBFormat) return _gl.RGB;
  32. if (p === THREE.RGBAFormat) return _gl.RGBA;
  33. if (p === THREE.LuminanceFormat) return _gl.LUMINANCE;
  34. if (p === THREE.LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  35. if (p === THREE.DepthFormat) return _gl.DEPTH_COMPONENT;
  36. if (p === THREE.DepthStencilFormat) return _gl.DEPTH_STENCIL;
  37. if (p === THREE.AddEquation) return _gl.FUNC_ADD;
  38. if (p === THREE.SubtractEquation) return _gl.FUNC_SUBTRACT;
  39. if (p === THREE.ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  40. if (p === THREE.ZeroFactor) return _gl.ZERO;
  41. if (p === THREE.OneFactor) return _gl.ONE;
  42. if (p === THREE.SrcColorFactor) return _gl.SRC_COLOR;
  43. if (p === THREE.OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  44. if (p === THREE.SrcAlphaFactor) return _gl.SRC_ALPHA;
  45. if (p === THREE.OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  46. if (p === THREE.DstAlphaFactor) return _gl.DST_ALPHA;
  47. if (p === THREE.OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  48. if (p === THREE.DstColorFactor) return _gl.DST_COLOR;
  49. if (p === THREE.OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  50. if (p === THREE.SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  51. if (p === THREE.RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  52. p === THREE.RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  53. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  54. if (extension !== null) {
  55. if (p === THREE.RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  56. if (p === THREE.RGBA_S3TC_DXT1_Format) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  57. if (p === THREE.RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  58. if (p === THREE.RGBA_S3TC_DXT5_Format) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  59. }
  60. }
  61. if (p === THREE.RGB_PVRTC_4BPPV1_Format || p === THREE.RGB_PVRTC_2BPPV1_Format ||
  62. p === THREE.RGBA_PVRTC_4BPPV1_Format || p === THREE.RGBA_PVRTC_2BPPV1_Format) {
  63. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  64. if (extension !== null) {
  65. if (p === THREE.RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  66. if (p === THREE.RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  67. if (p === THREE.RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  68. if (p === THREE.RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  69. }
  70. }
  71. if (p === THREE.RGB_ETC1_Format) {
  72. extension = extensions.get('WEBGL_compressed_texture_etc1');
  73. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  74. }
  75. if (p === THREE.MinEquation || p === THREE.MaxEquation) {
  76. extension = extensions.get('EXT_blend_minmax');
  77. if (extension !== null) {
  78. if (p === THREE.MinEquation) return extension.MIN_EXT;
  79. if (p === THREE.MaxEquation) return extension.MAX_EXT;
  80. }
  81. }
  82. if (p === UnsignedInt248Type) {
  83. extension = extensions.get('WEBGL_depth_texture');
  84. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  85. }
  86. return 0;
  87. };
  88. let attributeLocations = {
  89. "position": {name: "position", location: 0},
  90. "color": {name: "color", location: 1},
  91. "rgba": {name: "color", location: 1},
  92. "intensity": {name: "intensity", location: 2},
  93. "classification": {name: "classification", location: 3},
  94. "returnNumber": {name: "returnNumber", location: 4},
  95. "return number": {name: "returnNumber", location: 4},
  96. "returns": {name: "returnNumber", location: 4},
  97. "numberOfReturns": {name: "numberOfReturns", location: 5},
  98. "number of returns": {name: "numberOfReturns", location: 5},
  99. "pointSourceID": {name: "pointSourceID", location: 6},
  100. "source id": {name: "pointSourceID", location: 6},
  101. "point source id": {name: "pointSourceID", location: 6},
  102. "indices": {name: "indices", location: 7},
  103. "normal": {name: "normal", location: 8},
  104. "spacing": {name: "spacing", location: 9},
  105. "gps-time": {name: "gpsTime", location: 10},
  106. "aExtra": {name: "aExtra", location: 11},
  107. };
  108. class Shader {
  109. constructor(gl, name, vsSource, fsSource) {
  110. this.gl = gl;
  111. this.name = name;
  112. this.vsSource = vsSource;
  113. this.fsSource = fsSource;
  114. this.cache = new Map();
  115. this.vs = null;
  116. this.fs = null;
  117. this.program = null;
  118. this.uniformLocations = {};
  119. this.attributeLocations = {};
  120. this.uniformBlockIndices = {};
  121. this.uniformBlocks = {};
  122. this.uniforms = {};
  123. this.update(vsSource, fsSource);
  124. }
  125. update(vsSource, fsSource) {
  126. this.vsSource = vsSource;
  127. this.fsSource = fsSource;
  128. this.linkProgram();
  129. }
  130. compileShader(shader, source){
  131. let gl = this.gl;
  132. gl.shaderSource(shader, source);
  133. gl.compileShader(shader);
  134. let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  135. if (!success) {
  136. let info = gl.getShaderInfoLog(shader);
  137. let numberedSource = source.split("\n").map((a, i) => `${i + 1}`.padEnd(5) + a).join("\n");
  138. throw `could not compile shader ${this.name}: ${info}, \n${numberedSource}`;
  139. }
  140. }
  141. linkProgram() {
  142. const tStart = performance.now();
  143. let gl = this.gl;
  144. this.uniformLocations = {};
  145. this.attributeLocations = {};
  146. this.uniforms = {};
  147. gl.useProgram(null);
  148. let cached = this.cache.get(`${this.vsSource}, ${this.fsSource}`);
  149. if (cached) {
  150. this.program = cached.program;
  151. this.vs = cached.vs;
  152. this.fs = cached.fs;
  153. this.attributeLocations = cached.attributeLocations;
  154. this.uniformLocations = cached.uniformLocations;
  155. this.uniformBlocks = cached.uniformBlocks;
  156. this.uniforms = cached.uniforms;
  157. return;
  158. } else {
  159. this.vs = gl.createShader(gl.VERTEX_SHADER);
  160. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  161. this.program = gl.createProgram();
  162. if( !gl.isProgram(this.program )){//创建失败 开启多个页面可能会,原因是webglcontextlost
  163. //console.error('创建program失败');
  164. viewer.dispatchEvent('webglError', {msg: 'potreeRenderer创建program失败'})
  165. console.log(this.vs)
  166. console.log(this.fs)
  167. return;
  168. }
  169. for(let name of Object.keys(attributeLocations)){
  170. let location = attributeLocations[name].location;
  171. let glslName = attributeLocations[name].name;
  172. gl.bindAttribLocation(this.program, location, glslName);
  173. }
  174. this.compileShader(this.vs, this.vsSource);
  175. this.compileShader(this.fs, this.fsSource);
  176. let program = this.program;
  177. gl.attachShader(program, this.vs);
  178. gl.attachShader(program, this.fs);
  179. gl.linkProgram(program);
  180. gl.detachShader(program, this.vs);
  181. gl.detachShader(program, this.fs);
  182. // 检测当前程序链接状态
  183. let success = gl.getProgramParameter(program, gl.LINK_STATUS);
  184. if (!success) {
  185. let info = gl.getProgramInfoLog(program);
  186. throw `could not link program ${this.name}: ${info}`;
  187. }
  188. { // attribute locations
  189. let numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  190. for (let i = 0; i < numAttributes; i++) {
  191. let attribute = gl.getActiveAttrib(program, i);
  192. let location = gl.getAttribLocation(program, attribute.name);
  193. this.attributeLocations[attribute.name] = location;
  194. }
  195. }
  196. { // uniform locations
  197. let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  198. for (let i = 0; i < numUniforms; i++) {
  199. let uniform = gl.getActiveUniform(program, i);
  200. let location = gl.getUniformLocation(program, uniform.name);
  201. this.uniformLocations[uniform.name] = location;
  202. this.uniforms[uniform.name] = {
  203. location: location,
  204. value: null,
  205. };
  206. }
  207. }
  208. // uniform blocks
  209. if( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext){ //WebGL2RenderingContext在mac的safari14以下是没有定义的
  210. let numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  211. for (let i = 0; i < numBlocks; i++) {
  212. let blockName = gl.getActiveUniformBlockName(program, i);
  213. let blockIndex = gl.getUniformBlockIndex(program, blockName);
  214. this.uniformBlockIndices[blockName] = blockIndex;
  215. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  216. let dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  217. let uBuffer = gl.createBuffer();
  218. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  219. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  220. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  221. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  222. this.uniformBlocks[blockName] = {
  223. name: blockName,
  224. index: blockIndex,
  225. dataSize: dataSize,
  226. buffer: uBuffer
  227. };
  228. }
  229. }
  230. let cached = {
  231. program: this.program,
  232. vs: this.vs,
  233. fs: this.fs,
  234. attributeLocations: this.attributeLocations,
  235. uniformLocations: this.uniformLocations,
  236. uniforms: this.uniforms,
  237. uniformBlocks: this.uniformBlocks,
  238. };
  239. this.cache.set(`${this.vsSource}, ${this.fsSource}`, cached);
  240. }
  241. const tEnd = performance.now();
  242. const duration = tEnd - tStart;
  243. //console.log(`shader compile duration: ${duration.toFixed(3)}`);
  244. }
  245. setUniformMatrix4(name, value) {
  246. const gl = this.gl;
  247. const location = this.uniformLocations[name];
  248. if (location == null) {
  249. return;
  250. }
  251. let tmp = new Float32Array(value.elements);
  252. gl.uniformMatrix4fv(location, false, tmp);
  253. }
  254. setUniform1f(name, value) {
  255. const gl = this.gl;
  256. const uniform = this.uniforms[name];
  257. if (uniform === undefined) {
  258. return;
  259. }
  260. if(uniform.value === value){
  261. return;
  262. }
  263. uniform.value = value;
  264. gl.uniform1f(uniform.location, value);
  265. }
  266. setUniformBoolean(name, value) {
  267. const gl = this.gl;
  268. const uniform = this.uniforms[name];
  269. if (uniform === undefined) {
  270. return;
  271. }
  272. if(uniform.value === value){
  273. return;
  274. }
  275. uniform.value = value;
  276. gl.uniform1i(uniform.location, value);
  277. }
  278. setUniformTexture(name, value) {
  279. const gl = this.gl;
  280. const location = this.uniformLocations[name];
  281. if (location == null) {
  282. return;
  283. }
  284. gl.uniform1i(location, value);
  285. }
  286. setUniform2f(name, value) {
  287. const gl = this.gl;
  288. const location = this.uniformLocations[name];
  289. if (location == null) {
  290. return;
  291. }
  292. gl.uniform2f(location, value[0], value[1]);
  293. }
  294. setUniform3f(name, value) {
  295. const gl = this.gl;
  296. const location = this.uniformLocations[name];
  297. if (location == null) {
  298. return;
  299. }
  300. gl.uniform3f(location, value[0], value[1], value[2]);
  301. }
  302. setUniform(name, value) {
  303. if (value.constructor === THREE.Matrix4) {
  304. this.setUniformMatrix4(name, value);
  305. } else if (typeof value === "number") {
  306. this.setUniform1f(name, value);
  307. } else if (typeof value === "boolean") {
  308. this.setUniformBoolean(name, value);
  309. } else if (value instanceof WebGLTexture) {
  310. this.setUniformTexture(name, value);
  311. } else if (value instanceof Array) {
  312. if (value.length === 2) {
  313. this.setUniform2f(name, value);
  314. } else if (value.length === 3) {
  315. this.setUniform3f(name, value);
  316. }
  317. } else {
  318. console.error("unhandled uniform type: ", name, value);
  319. }
  320. }
  321. setUniform1i(name, value) {
  322. let gl = this.gl;
  323. let location = this.uniformLocations[name];
  324. if (location == null) {
  325. return;
  326. }
  327. gl.uniform1i(location, value);
  328. }
  329. };
  330. class WebGLTexture {
  331. constructor(gl, texture) {
  332. this.gl = gl;
  333. this.texture = texture;
  334. this.id = gl.createTexture();
  335. this.target = gl.TEXTURE_2D;
  336. this.version = -1;
  337. this.update(texture);
  338. }
  339. update() {
  340. if (!this.texture.image) {
  341. this.version = this.texture.version;
  342. return;
  343. }
  344. let gl = this.gl;
  345. let texture = this.texture;
  346. if (this.version === texture.version) {
  347. return;
  348. }
  349. this.target = gl.TEXTURE_2D;
  350. gl.bindTexture(this.target, this.id);
  351. let level = 0;
  352. let internalFormat = paramThreeToGL(gl, texture.format);
  353. let width = texture.image.width;
  354. let height = texture.image.height;
  355. let border = 0;
  356. let srcFormat = internalFormat;
  357. let srcType = paramThreeToGL(gl, texture.type);
  358. let data;
  359. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  360. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  361. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  362. if (texture instanceof THREE.DataTexture) {
  363. data = texture.image.data;
  364. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  365. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  366. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  367. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  368. gl.texImage2D(this.target, level, internalFormat,
  369. width, height, border, srcFormat, srcType,
  370. data);
  371. } else if ((texture instanceof THREE.CanvasTexture) || (texture instanceof THREE.Texture)) {
  372. data = texture.image;
  373. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL(gl, texture.wrapS));
  374. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL(gl, texture.wrapT));
  375. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  376. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  377. gl.texImage2D(this.target, level, internalFormat,
  378. internalFormat, srcType, data);
  379. if (texture instanceof THREE.Texture) {gl.generateMipmap(gl.TEXTURE_2D);}
  380. }
  381. gl.bindTexture(this.target, null);
  382. this.version = texture.version;
  383. }
  384. };
  385. class WebGLBuffer {
  386. constructor() {
  387. this.numElements = 0;
  388. this.vao = null;
  389. this.vbos = new Map();
  390. }
  391. };
  392. export class Renderer {
  393. constructor(threeRenderer) {
  394. this.threeRenderer = threeRenderer;
  395. this.gl = this.threeRenderer.getContext();
  396. this.buffers = new Map();
  397. this.shaders = new Map();
  398. this.textures = new Map();
  399. this.glTypeMapping = new Map();
  400. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  401. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  402. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  403. this.toggle = 0;
  404. }
  405. deleteBuffer(geometry) {
  406. let gl = this.gl;
  407. let webglBuffer = this.buffers.get(geometry);
  408. if (webglBuffer != null) {
  409. for (let attributeName in geometry.attributes) {
  410. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  411. }
  412. this.buffers.delete(geometry);
  413. }
  414. }
  415. createBuffer(geometry){
  416. let gl = this.gl;
  417. let webglBuffer = new WebGLBuffer();
  418. webglBuffer.vao = gl.createVertexArray();
  419. webglBuffer.numElements = geometry.attributes.position.count;
  420. gl.bindVertexArray(webglBuffer.vao);
  421. for(let attributeName in geometry.attributes){
  422. let bufferAttribute = geometry.attributes[attributeName];
  423. let vbo = gl.createBuffer();
  424. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  425. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  426. let normalized = bufferAttribute.normalized;
  427. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  428. if(attributeLocations[attributeName] === undefined){
  429. //attributeLocation = attributeLocations["aExtra"];
  430. }else{
  431. let attributeLocation = attributeLocations[attributeName].location;
  432. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  433. gl.enableVertexAttribArray(attributeLocation);
  434. }
  435. webglBuffer.vbos.set(attributeName, {
  436. handle: vbo,
  437. name: attributeName,
  438. count: bufferAttribute.count,
  439. itemSize: bufferAttribute.itemSize,
  440. type: geometry.attributes.position.array.constructor,
  441. version: 0
  442. });
  443. }
  444. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  445. gl.bindVertexArray(null);
  446. let disposeHandler = (event) => {
  447. this.deleteBuffer(geometry);
  448. geometry.removeEventListener("dispose", disposeHandler);
  449. };
  450. geometry.addEventListener("dispose", disposeHandler);
  451. return webglBuffer;
  452. }
  453. updateBuffer(geometry){
  454. let gl = this.gl;
  455. let webglBuffer = this.buffers.get(geometry);
  456. gl.bindVertexArray(webglBuffer.vao);
  457. for(let attributeName in geometry.attributes){
  458. let bufferAttribute = geometry.attributes[attributeName];
  459. let normalized = bufferAttribute.normalized;
  460. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  461. let vbo = null;
  462. if(!webglBuffer.vbos.has(attributeName)){
  463. vbo = gl.createBuffer();
  464. webglBuffer.vbos.set(attributeName, {
  465. handle: vbo,
  466. name: attributeName,
  467. count: bufferAttribute.count,
  468. itemSize: bufferAttribute.itemSize,
  469. type: geometry.attributes.position.array.constructor,
  470. version: bufferAttribute.version
  471. });
  472. }else{
  473. vbo = webglBuffer.vbos.get(attributeName).handle;
  474. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  475. }
  476. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  477. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  478. if(attributeLocations[attributeName] === undefined){
  479. //attributeLocation = attributeLocations["aExtra"];
  480. }else{
  481. let attributeLocation = attributeLocations[attributeName].location;
  482. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  483. gl.enableVertexAttribArray(attributeLocation);
  484. }
  485. }
  486. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  487. gl.bindVertexArray(null);
  488. }
  489. traverse(scene) {
  490. let octrees = [];
  491. let stack = [scene];
  492. while (stack.length > 0) {
  493. let node = stack.pop();
  494. if (node instanceof PointCloudTree) {
  495. octrees.push(node);
  496. continue;
  497. }
  498. let visibleChildren = node.children.filter(c => c.visible);
  499. stack.push(...visibleChildren);
  500. }
  501. let result = {
  502. octrees: octrees
  503. };
  504. return result;
  505. }
  506. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  507. viewer.addTimeMark('renderNodes','start')
  508. let gl = this.gl;
  509. let material = params.material ? params.material : octree.material;
  510. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  511. let view = camera.matrixWorldInverse;
  512. if(params.viewOverride){
  513. view = params.viewOverride;
  514. }
  515. let worldView = new THREE.Matrix4();
  516. let mat4holder = new Float32Array(16);
  517. let i = 0;
  518. //---------从renderOctree搬到这----
  519. shader.setUniform1f("size", material.usePanoMap ? Potree.config.material.absolutePanoramaSize * Math.min(window.devicePixelRatio,2) : material.size);//usePanoMap时控制在不大不小的范围内感觉较好,考虑到有的点云稀疏,用大一点的点
  520. shader.setUniform1f("uOpacity", material.usePanoMap ? 1: material.opacity);
  521. shader.setUniform3f("uColor", material.color.toArray());
  522. /* let currentTextureBindingPoint = params.currentTextureBindingPoint
  523. if (material.pointSizeType >= 0 && window.needvisibilityTexture) {
  524. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  525. material.activeAttributeName === "level of detail") {
  526. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  527. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  528. const vnt = material.visibleNodesTexture;
  529. const data = vnt.image.data;
  530. data.set(visibilityTextureData.data);
  531. vnt.needsUpdate = true;
  532. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture); //不知道为什么这段从renderOctree中移过来,会崩溃。暂时不移动了
  533. if(vnWebGLTexture){
  534. shader.setUniform1i("visibleNodes", currentTextureBindingPoint);
  535. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  536. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  537. currentTextureBindingPoint++;
  538. }
  539. }
  540. } */
  541. let transparent = false;
  542. if(params.transparent !== undefined){
  543. transparent = params.transparent && material.opacity < 1;
  544. }else{
  545. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  546. }
  547. if (transparent){
  548. gl.enable(gl.BLEND);
  549. if(params.notAdditiveBlending){
  550. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending
  551. gl.enable(gl.DEPTH_TEST);
  552. gl.depthMask(true); //如果不开启depthWrite,深度会错乱。
  553. }else{
  554. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  555. gl.disable(gl.DEPTH_TEST);
  556. gl.depthMask(false);
  557. }
  558. } else {
  559. gl.disable(gl.BLEND);
  560. gl.depthMask(true);
  561. gl.enable(gl.DEPTH_TEST);
  562. }
  563. if(params.blendFunc !== undefined){
  564. gl.enable(gl.BLEND);
  565. gl.blendFunc(...params.blendFunc);
  566. }
  567. if(params.depthTest !== undefined){
  568. if(params.depthTest === true){
  569. gl.enable(gl.DEPTH_TEST);
  570. }else{
  571. gl.disable(gl.DEPTH_TEST);
  572. }
  573. }
  574. if(params.depthWrite !== undefined){
  575. if(params.depthWrite === true){
  576. gl.depthMask(true);
  577. }else{
  578. gl.depthMask(false);
  579. }
  580. }
  581. //---------------------------------
  582. for (let node of nodes) {
  583. if(exports.debug.allowedNodes !== undefined){
  584. if(!exports.debug.allowedNodes.includes(node.name)){
  585. continue;
  586. }
  587. }
  588. let world = node.sceneNode.matrixWorld;
  589. worldView.multiplyMatrices(view, world);
  590. if (visibilityTextureData) {
  591. let vnStart = visibilityTextureData.offsets.get(node);
  592. console.log('vnStart',vnStart)
  593. shader.setUniform1f("uVNStart", vnStart);
  594. }
  595. let level = node.getLevel();
  596. if(node.debug){
  597. shader.setUniform("uDebug", true);
  598. }else{
  599. shader.setUniform("uDebug", false);
  600. }
  601. // let isLeaf = false;
  602. // if(node instanceof PointCloudOctreeNode){
  603. // isLeaf = Object.keys(node.children).length === 0;
  604. // }else if(node instanceof PointCloudArena4DNode){
  605. // isLeaf = node.geometryNode.isLeaf;
  606. // }
  607. // shader.setUniform("uIsLeafNode", isLeaf);
  608. // let isLeaf = node.children.filter(n => n != null).length === 0;
  609. // if(!isLeaf){
  610. // continue;
  611. // }
  612. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  613. const lModel = shader.uniformLocations["modelMatrix"];
  614. if (lModel) {
  615. mat4holder.set(world.elements);
  616. gl.uniformMatrix4fv(lModel, false, mat4holder);
  617. }
  618. const lModelView = shader.uniformLocations["modelViewMatrix"];
  619. //mat4holder.set(worldView.elements);
  620. // faster then set in chrome 63
  621. for(let j = 0; j < 16; j++){
  622. mat4holder[j] = worldView.elements[j];
  623. }
  624. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  625. { // Clip Polygons
  626. if(material.clipPolygons && material.clipPolygons.length > 0){
  627. let clipPolygonVCount = [];
  628. let worldViewProjMatrices = [];
  629. for(let clipPolygon of material.clipPolygons){
  630. let view = clipPolygon.viewMatrix;
  631. let proj = clipPolygon.projMatrix;
  632. let worldViewProj = proj.clone().multiply(view).multiply(world);
  633. clipPolygonVCount.push(clipPolygon.markers.length);
  634. worldViewProjMatrices.push(worldViewProj);
  635. }
  636. let flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  637. let flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  638. for(let i = 0; i < material.clipPolygons.length; i++){
  639. let clipPolygon = material.clipPolygons[i];
  640. for(let j = 0; j < clipPolygon.markers.length; j++){
  641. flattenedVertices[i * 24 + (j * 3 + 0)] = clipPolygon.markers[j].position.x;
  642. flattenedVertices[i * 24 + (j * 3 + 1)] = clipPolygon.markers[j].position.y;
  643. flattenedVertices[i * 24 + (j * 3 + 2)] = clipPolygon.markers[j].position.z;
  644. }
  645. }
  646. const lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  647. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  648. const lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  649. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  650. const lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  651. gl.uniform3fv(lClipPolygons, flattenedVertices);
  652. }
  653. }
  654. //shader.setUniformMatrix4("modelMatrix", world);
  655. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  656. shader.setUniform1f("uLevel", level);
  657. //shader.setUniform1f("levelPercent", octree.nodeMaxLevel ? level / octree.nodeMaxLevel : 0.5);//xzw add
  658. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  659. shader.setUniform1f("uPCIndex", i);
  660. // uBBSize
  661. if (shadowMaps.length > 0) {
  662. const lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  663. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  664. let bindingStart = 5;
  665. let bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => (a + i));
  666. gl.uniform1iv(lShadowMap, bindingPoints);
  667. for (let i = 0; i < shadowMaps.length; i++) {
  668. let shadowMap = shadowMaps[i];
  669. let bindingPoint = bindingPoints[i];
  670. let glTexture = this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  671. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  672. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  673. }
  674. {
  675. let worldViewMatrices = shadowMaps
  676. .map(sm => sm.camera.matrixWorldInverse)
  677. .map(view => new THREE.Matrix4().multiplyMatrices(view, world))
  678. let flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  679. const lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  680. gl.uniformMatrix4fv(lWorldView, false, flattenedMatrices);
  681. }
  682. {
  683. let flattenedMatrices = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  684. const lProj = shader.uniformLocations["uShadowProj[0]"];
  685. gl.uniformMatrix4fv(lProj, false, flattenedMatrices);
  686. }
  687. }
  688. const geometry = node.geometryNode.geometry;
  689. if(geometry.attributes["gps-time"]){
  690. const bufferAttribute = geometry.attributes["gps-time"];
  691. const attGPS = octree.getAttribute("gps-time");
  692. let initialRange = attGPS.initialRange;
  693. let initialRangeSize = initialRange[1] - initialRange[0];
  694. let globalRange = attGPS.range;
  695. let globalRangeSize = globalRange[1] - globalRange[0];
  696. let scale = initialRangeSize / globalRangeSize;
  697. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  698. scale = Number.isNaN(scale) ? 1 : scale;
  699. offset = Number.isNaN(offset) ? 0 : offset;
  700. shader.setUniform1f("uGpsScale", scale);
  701. shader.setUniform1f("uGpsOffset", offset);
  702. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  703. let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  704. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  705. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  706. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  707. let normalizedClipRange = [
  708. (uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize,
  709. (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize,
  710. ];
  711. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  712. // // ranges in full gps coordinate system
  713. // const globalRange = attGPS.range;
  714. // const bufferRange = bufferAttribute.potree.range;
  715. // // ranges in [0, 1]
  716. // // normalizedGlobalRange = [0, 1]
  717. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  718. // const globalWidth = globalRange[1] - globalRange[0];
  719. // const normalizedBufferRange = [
  720. // (bufferRange[0] - globalRange[0]) / globalWidth,
  721. // (bufferRange[1] - globalRange[0]) / globalWidth,
  722. // ];
  723. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  724. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  725. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  726. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  727. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  728. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  729. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  730. }
  731. {
  732. let uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  733. let uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  734. let uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  735. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  736. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  737. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  738. }
  739. let webglBuffer = null;
  740. if(!this.buffers.has(geometry)){
  741. webglBuffer = this.createBuffer(geometry);
  742. this.buffers.set(geometry, webglBuffer);
  743. }else{
  744. webglBuffer = this.buffers.get(geometry);
  745. for(let attributeName in geometry.attributes){
  746. let attribute = geometry.attributes[attributeName];
  747. if(attribute.version > webglBuffer.vbos.get(attributeName).version){
  748. this.updateBuffer(geometry);
  749. }
  750. }
  751. }
  752. gl.bindVertexArray(webglBuffer.vao);
  753. let isExtraAttribute =
  754. attributeLocations[material.activeAttributeName] === undefined
  755. && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  756. if(isExtraAttribute){
  757. const attributeLocation = attributeLocations["aExtra"].location;
  758. for(const attributeName in geometry.attributes){
  759. const bufferAttribute = geometry.attributes[attributeName];
  760. const vbo = webglBuffer.vbos.get(attributeName);
  761. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  762. gl.disableVertexAttribArray(attributeLocation);
  763. }
  764. const attName = material.activeAttributeName;
  765. const bufferAttribute = geometry.attributes[attName];
  766. const vbo = webglBuffer.vbos.get(attName);
  767. if(bufferAttribute !== undefined && vbo !== undefined){
  768. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  769. let normalized = bufferAttribute.normalized;
  770. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  771. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  772. gl.enableVertexAttribArray(attributeLocation);
  773. }
  774. {
  775. const attExtra = octree.pcoGeometry.pointAttributes.attributes
  776. .find(a => a.name === attName);
  777. let range = material.getRange(attName);
  778. if(!range){
  779. range = attExtra.range;
  780. }
  781. if(!range){
  782. range = [0, 1];
  783. }
  784. let initialRange = attExtra.initialRange;
  785. let initialRangeSize = initialRange[1] - initialRange[0];
  786. let globalRange = range;
  787. let globalRangeSize = globalRange[1] - globalRange[0];
  788. let scale = initialRangeSize / globalRangeSize;
  789. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  790. scale = Number.isNaN(scale) ? 1 : scale;
  791. offset = Number.isNaN(offset) ? 0 : offset;
  792. shader.setUniform1f("uExtraScale", scale);
  793. shader.setUniform1f("uExtraOffset", offset);
  794. }
  795. }else{
  796. for(const attributeName in geometry.attributes){
  797. const bufferAttribute = geometry.attributes[attributeName];
  798. const vbo = webglBuffer.vbos.get(attributeName);
  799. if(attributeLocations[attributeName] !== undefined){
  800. const attributeLocation = attributeLocations[attributeName].location;
  801. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  802. let normalized = bufferAttribute.normalized;
  803. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  804. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  805. gl.enableVertexAttribArray(attributeLocation);
  806. }
  807. }
  808. }
  809. let numPoints = webglBuffer.numElements;
  810. gl.drawArrays(gl.POINTS, 0, numPoints);
  811. //gl.drawArrays(gl.TRIANGLES, 0, numPoints);
  812. i++;
  813. }
  814. gl.bindVertexArray(null);
  815. viewer.addTimeMark('renderNodes','end')
  816. }
  817. renderOctree(octrees, nodes, camera, target, params = {}){
  818. viewer.addTimeMark('renderOctree','start')
  819. let octree
  820. if(octrees instanceof Array){
  821. octree = octrees[0];
  822. }else{
  823. octree = octrees; octrees = [octree]
  824. }
  825. let gl = this.gl;
  826. let material = params.material ? params.material : octree.material;
  827. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  828. let view = camera.matrixWorldInverse;
  829. let viewInv = camera.matrixWorld;
  830. if(params.viewOverride){
  831. view = params.viewOverride;
  832. viewInv = view.clone().invert();
  833. }
  834. let proj = camera.projectionMatrix;
  835. let projInv = proj.clone().invert();
  836. //let worldView = new THREE.Matrix4();
  837. let shader = null;
  838. let visibilityTextureData = null;
  839. let currentTextureBindingPoint = 0;
  840. if (material.pointSizeType >= 0) {//最好搬到renderNodes
  841. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  842. material.activeAttributeName === "level of detail") {
  843. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  844. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  845. const vnt = material.visibleNodesTexture;
  846. const data = vnt.image.data;
  847. data.set(visibilityTextureData.data);
  848. vnt.needsUpdate = true;
  849. }
  850. }
  851. { // UPDATE SHADER AND TEXTURES
  852. if (!this.shaders.has(material)) {
  853. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  854. let shader = new Shader(gl, "pointcloud", vs, fs);
  855. this.shaders.set(material, shader);
  856. }
  857. shader = this.shaders.get(material);
  858. if(material.shaderNeedsUpdate)
  859. {
  860. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  861. let numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  862. let num_in_clipboxes = (material.clipBoxes_in && material.clipBoxes_in.length) ? material.clipBoxes_in.length : 0;
  863. let num_out_clipboxes = (material.clipBoxes_out && material.clipBoxes_out.length) ? material.clipBoxes_out.length : 0;
  864. let num_highlightBox = (material.highlightBoxes && material.highlightBoxes.length) ? material.highlightBoxes.length : 0;
  865. let numClipSpheres = (params.clipSpheres && params.clipSpheres.length) ? params.clipSpheres.length : 0;
  866. let numClipPolygons = (material.clipPolygons && material.clipPolygons.length) ? material.clipPolygons.length : 0;
  867. let defines = [
  868. `#define num_shadowmaps ${shadowMaps.length}`,
  869. `#define num_snapshots ${numSnapshots}`,
  870. `#define num_in_clipboxes ${num_in_clipboxes}`, //改
  871. `#define num_out_clipboxes ${num_out_clipboxes}`, //改
  872. `#define num_highlightBox ${num_highlightBox}`, //改
  873. `#define num_clipspheres ${numClipSpheres}`,
  874. ];
  875. //add:-----------
  876. if(material.bigClipInBox ){//裁剪下载
  877. defines.push('#define bigClipInBox')
  878. }
  879. if(material.usePanoMap){
  880. defines.push("#define usePanoMap");
  881. }
  882. if(material.useFilterByNormal){
  883. defines.push("#define use_filter_by_normal");
  884. //Potree.settings.editType == 'pano' ? defines.push("#define attenuated_opacity2") : defines.push("#define attenuated_opacity");
  885. }
  886. //---------------
  887. if(octree.pcoGeometry.root.isLoaded()){
  888. let attributes = octree.pcoGeometry.root.geometry.attributes;
  889. if(attributes["gps-time"]){
  890. defines.push("#define clip_gps_enabled");
  891. }
  892. if(attributes["return number"]){
  893. defines.push("#define clip_return_number_enabled");
  894. }
  895. if(attributes["number of returns"]){
  896. defines.push("#define clip_number_of_returns_enabled");
  897. }
  898. if(attributes["source id"] || attributes["point source id"]){
  899. defines.push("#define clip_point_source_id_enabled");
  900. }
  901. }
  902. let definesString = defines.join("\n");
  903. let vsVersionIndex = vs.indexOf("#version ");
  904. let fsVersionIndex = fs.indexOf("#version ");
  905. if(vsVersionIndex >= 0){
  906. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`)
  907. }else{
  908. vs = `${definesString}\n${vs}`;
  909. }
  910. if(fsVersionIndex >= 0){
  911. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`)
  912. }else{
  913. fs = `${definesString}\n${fs}`;
  914. }
  915. shader.update(vs, fs);
  916. material.shaderNeedsUpdate = false;
  917. }
  918. for (let uniformName of Object.keys(material.uniforms)) {
  919. let uniform = material.uniforms[uniformName];
  920. if (uniform.type == "t") {
  921. let texture = uniform.value;
  922. if (!texture) {
  923. continue;
  924. }
  925. //add
  926. if(uniformName == 'pano0Map' || uniformName == 'pano1Map' ){ //属于cubeTex,另外设置
  927. continue
  928. }
  929. if (!this.textures.has(texture)) {
  930. let webglTexture = new WebGLTexture(gl, texture);
  931. this.textures.set(texture, webglTexture);
  932. }
  933. let webGLTexture = this.textures.get(texture);
  934. webGLTexture.update();
  935. }
  936. }
  937. }
  938. gl.useProgram(shader.program);
  939. /* let transparent = false;
  940. if(params.transparent !== undefined){
  941. transparent = params.transparent && material.opacity < 1;
  942. }else{
  943. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  944. }
  945. if (transparent){
  946. gl.enable(gl.BLEND);
  947. if(params.notAdditiveBlending){
  948. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending
  949. gl.enable(gl.DEPTH_TEST);
  950. gl.depthMask(true); //如果不开启depthWrite,深度会错乱。
  951. }else{
  952. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  953. gl.disable(gl.DEPTH_TEST);
  954. gl.depthMask(false);
  955. }
  956. } else {
  957. gl.disable(gl.BLEND);
  958. gl.depthMask(true);
  959. gl.enable(gl.DEPTH_TEST);
  960. }
  961. if(params.blendFunc !== undefined){
  962. gl.enable(gl.BLEND);
  963. gl.blendFunc(...params.blendFunc);
  964. }
  965. if(params.depthTest !== undefined){
  966. if(params.depthTest === true){
  967. gl.enable(gl.DEPTH_TEST);
  968. }else{
  969. gl.disable(gl.DEPTH_TEST);
  970. }
  971. }
  972. if(params.depthWrite !== undefined){
  973. if(params.depthWrite === true){
  974. gl.depthMask(true);
  975. }else{
  976. gl.depthMask(false);
  977. }
  978. } */
  979. { // UPDATE UNIFORMS
  980. shader.setUniformMatrix4("projectionMatrix", proj);
  981. shader.setUniformMatrix4("viewMatrix", view);
  982. shader.setUniformMatrix4("uViewInv", viewInv);
  983. shader.setUniformMatrix4("uProjInv", projInv);
  984. /* let screenWidth = target ? target.width : material.screenWidth;
  985. let screenHeight = target ? target.height : material.screenHeight;
  986. shader.setUniform1f("uScreenWidth", screenWidth);
  987. shader.setUniform1f("uScreenHeight", screenHeight); */
  988. shader.setUniform2f('resolution', material.resolution.toArray())
  989. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  990. shader.setUniform1f("near", camera.near);
  991. shader.setUniform1f("far", camera.far);
  992. if(camera instanceof THREE.OrthographicCamera){
  993. shader.setUniform("uUseOrthographicCamera", true);
  994. shader.setUniform("uOrthoWidth", (camera.right - camera.left) / camera.zoom); //改
  995. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  996. }else{
  997. shader.setUniform("uUseOrthographicCamera", false);
  998. }
  999. /* if(material.clipBoxes.length + material.clipPolygons.length === 0){//改
  1000. shader.setUniform1i("clipTask", ClipTask.NONE);
  1001. }else{
  1002. shader.setUniform1i("clipTask", material.clipTask);
  1003. }
  1004. shader.setUniform1i("clipMethod", material.clipMethod);*/
  1005. //改
  1006. if (material.clipBoxes_in && material.clipBoxes_in.length > 0) {
  1007. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  1008. const lClipBoxes = shader.uniformLocations["clipBoxes_in[0]"];
  1009. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes_in.value);
  1010. }
  1011. if (material.clipBoxes_out && material.clipBoxes_out.length > 0) {//add
  1012. const lClipBoxes2 = shader.uniformLocations["clipBoxes_out[0]"];
  1013. gl.uniformMatrix4fv(lClipBoxes2, false, material.uniforms.clipBoxes_out.value);
  1014. }
  1015. if (material.highlightBoxes && material.highlightBoxes.length > 0) {//add
  1016. const boxes_highlight = shader.uniformLocations["boxes_highlight[0]"];
  1017. gl.uniformMatrix4fv(boxes_highlight, false, material.uniforms.boxes_highlight.value);
  1018. }
  1019. if (material.bigClipInBox ) {//add
  1020. shader.setUniformMatrix4("clipBoxBig_in", material.uniforms.clipBoxBig_in.value);
  1021. }
  1022. // TODO CLIPSPHERES
  1023. if(params.clipSpheres && params.clipSpheres.length > 0){
  1024. let clipSpheres = params.clipSpheres;
  1025. let matrices = [];
  1026. for(let clipSphere of clipSpheres){
  1027. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  1028. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  1029. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  1030. let clipToWorld = clipSphere.matrixWorld;
  1031. let viewToWorld = camera.matrixWorld
  1032. let worldToClip = clipToWorld.clone().invert();
  1033. let viewToClip = new THREE.Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  1034. matrices.push(viewToClip);
  1035. }
  1036. let flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  1037. const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  1038. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  1039. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  1040. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  1041. }
  1042. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  1043. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  1044. // uniform float uPCIndex
  1045. shader.setUniform1f("uOctreeSpacing", material.spacing);
  1046. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  1047. shader.setUniform2f("elevationRange", material.elevationRange);
  1048. shader.setUniform2f("intensityRange", material.intensityRange);
  1049. shader.setUniform3f("uIntensity_gbc", [
  1050. material.intensityGamma,
  1051. material.intensityBrightness,
  1052. material.intensityContrast
  1053. ]);
  1054. shader.setUniform3f("uRGB_gbc", [
  1055. material.rgbGamma,
  1056. material.rgbBrightness,
  1057. material.rgbContrast
  1058. ]);
  1059. shader.setUniform1f("uTransition", material.transition);
  1060. shader.setUniform1f("wRGB", material.weightRGB);
  1061. shader.setUniform1f("wIntensity", material.weightIntensity);
  1062. shader.setUniform1f("wElevation", material.weightElevation);
  1063. shader.setUniform1f("wClassification", material.weightClassification);
  1064. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  1065. shader.setUniform1f("wSourceID", material.weightSourceID);
  1066. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  1067. //==========================
  1068. //gl.TEXTURE_CUBE_MAP: 34067
  1069. //gl.TEXTURE0=33984 , vnWebGLTexture.target=gl.TEXTURE_2D = 3353
  1070. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);//最好搬到renderNodes
  1071. if(vnWebGLTexture){
  1072. shader.setUniform1i("visibleNodes", currentTextureBindingPoint); //为何之前写的是"visibleNodesTexture",但和"visibleNodes"效果相同?可shader里只有"visibleNodes"
  1073. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  1074. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  1075. currentTextureBindingPoint++;
  1076. }
  1077. let gradientTexture = this.textures.get(material.gradientTexture);
  1078. shader.setUniform1i("gradient", currentTextureBindingPoint);
  1079. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  1080. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  1081. currentTextureBindingPoint++;
  1082. const repeat = material.elevationGradientRepeat;
  1083. if(repeat === ElevationGradientRepeat.REPEAT){
  1084. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  1085. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  1086. }else if(repeat === ElevationGradientRepeat.MIRRORED_REPEAT){
  1087. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  1088. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  1089. }else{
  1090. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1091. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1092. }
  1093. currentTextureBindingPoint++;
  1094. let classificationTexture = this.textures.get(material.classificationTexture);
  1095. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  1096. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  1097. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  1098. currentTextureBindingPoint++;
  1099. /* let matcapTexture = this.textures.get(material.matcapTexture);
  1100. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  1101. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  1102. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  1103. currentTextureBindingPoint++; */
  1104. if (material.snapEnabled === true) {
  1105. {
  1106. const lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  1107. const lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  1108. let bindingStart = currentTextureBindingPoint;
  1109. let lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => (a + i));
  1110. let lSnapshotDepthBindingPoints = new Array(5)
  1111. .fill(1 + Math.max(...lSnapshotBindingPoints))
  1112. .map((a, i) => (a + i));
  1113. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  1114. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  1115. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  1116. for (let i = 0; i < 5; i++) {
  1117. let texture = material.uniforms[`uSnapshot`].value[i];
  1118. let textureDepth = material.uniforms[`uSnapshotDepth`].value[i];
  1119. if (!texture) {
  1120. break;
  1121. }
  1122. let snapTexture = this.threeRenderer.properties.get(texture).__webglTexture;
  1123. let snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  1124. let bindingPoint = lSnapshotBindingPoints[i];
  1125. let depthBindingPoint = lSnapshotDepthBindingPoints[i];
  1126. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  1127. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  1128. gl.activeTexture(gl[`TEXTURE${depthBindingPoint}`]);
  1129. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  1130. }
  1131. }
  1132. {
  1133. let flattenedMatrices = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  1134. const lSnapView = shader.uniformLocations["uSnapView[0]"];
  1135. gl.uniformMatrix4fv(lSnapView, false, flattenedMatrices);
  1136. }
  1137. {
  1138. let flattenedMatrices = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  1139. const lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  1140. gl.uniformMatrix4fv(lSnapProj, false, flattenedMatrices);
  1141. }
  1142. {
  1143. let flattenedMatrices = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  1144. const lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  1145. gl.uniformMatrix4fv(lSnapProjInv, false, flattenedMatrices);
  1146. }
  1147. {
  1148. let flattenedMatrices = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  1149. const lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  1150. gl.uniformMatrix4fv(lSnapViewInv, false, flattenedMatrices);
  1151. }
  1152. }
  1153. //=============add===========
  1154. if(material.usePanoMap){//为什么pointsize失效
  1155. shader.setUniform1f("progress", material.uniforms.progress.value);
  1156. shader.setUniform1f("easeInOutRatio", material.uniforms.easeInOutRatio.value);
  1157. shader.setUniform3f("pano0Position", material.uniforms.pano0Position.value.toArray());
  1158. shader.setUniform3f("pano1Position", material.uniforms.pano1Position.value.toArray());
  1159. shader.setUniform('pano0Matrix', material.uniforms.pano0Matrix.value);
  1160. shader.setUniform('pano1Matrix', material.uniforms.pano1Matrix.value);
  1161. let pano0Map = material.uniforms.pano0Map.value
  1162. if(pano0Map){
  1163. this.threeRenderer._textures.safeSetTextureCube( pano0Map, ++currentTextureBindingPoint );
  1164. shader.setUniform1i('pano0Map', currentTextureBindingPoint);
  1165. }
  1166. let pano1Map = material.uniforms.pano1Map.value
  1167. if(pano1Map){
  1168. this.threeRenderer._textures.safeSetTextureCube( pano1Map, ++currentTextureBindingPoint );
  1169. shader.setUniform1i('pano1Map', currentTextureBindingPoint);
  1170. }
  1171. //注: three.js我添加了个 _textures, safeSetTextureCube里主要就是activeTexture和bindTexture
  1172. }
  1173. }
  1174. viewer.addTimeMark('renderOctree','end')
  1175. params.currentTextureBindingPoint = currentTextureBindingPoint
  1176. octrees.forEach(octree=>{
  1177. this.renderNodes(octree, nodes || octree.visibleNodes, visibilityTextureData, camera, target, shader, params);
  1178. })
  1179. gl.activeTexture(gl.TEXTURE2);
  1180. gl.bindTexture(gl.TEXTURE_2D, null);
  1181. gl.activeTexture(gl.TEXTURE0);
  1182. //gl.bindTexture(gl.TEXTURE_2D, null); //add
  1183. //add 恢复为不透明(否则renderToCubeMap时的贴图会被渲染成高亮的颜色)
  1184. gl.disable(gl.BLEND);
  1185. gl.depthMask(true);
  1186. gl.enable(gl.DEPTH_TEST);
  1187. //DEPTH_TEST等需要恢复吗
  1188. }
  1189. render(scene, camera, target = null, params = {}) {
  1190. const gl = this.gl;
  1191. // PREPARE
  1192. if (target != null) {
  1193. this.threeRenderer.setRenderTarget(target);
  1194. }
  1195. //camera.updateProjectionMatrix();
  1196. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  1197. const traversalResult = this.traverse(scene);
  1198. //排序
  1199. if(Potree.settings.notAdditiveBlending){//add
  1200. traversalResult.octrees.forEach(tree=>{
  1201. if(tree.material.opacity==1){
  1202. tree._z = Infinity //不透明的先渲染
  1203. }else{
  1204. let center = tree.boundCenter ? tree.boundCenter.clone() : tree.boundingBox.getCenter(tree.boundCenter).applyMatrix4(tree.matrixWorld)
  1205. center.project(camera)
  1206. tree._z = center.z
  1207. }
  1208. })
  1209. traversalResult.octrees.sort((tree1,tree2)=>{
  1210. return tree2._z - tree1._z //降序 (-1 朝外)。 离屏幕近的后渲染
  1211. })
  1212. }
  1213. // RENDER
  1214. let mat = traversalResult.octrees[0].material
  1215. if(Potree.settings.cloudSameMat && viewer.scene.volumes.length == 0 && mat.pointSizeType != PointSizeType.ADAPTIVE && mat.activeAttributeName != "level of detail"){
  1216. this.renderOctree(traversalResult.octrees, null, camera, target, params); //所有点云除了个别属性需要在shader中更新,其他都使用第一个点云的材质
  1217. }else for (const octree of traversalResult.octrees) {
  1218. for (const octree of traversalResult.octrees) {
  1219. this.renderOctree(octree, octree.visibleNodes, camera, target, params);
  1220. }
  1221. }
  1222. //if (octree material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") {
  1223. // CLEANUP
  1224. gl.activeTexture(gl.TEXTURE1);
  1225. gl.bindTexture(gl.TEXTURE_2D, null);
  1226. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  1227. gl.bindVertexArray(null);
  1228. this.threeRenderer.resetState();
  1229. }
  1230. };
  1231. /*
  1232. 中东的链接http://indoor.popsmart.cn:8094/zdoblh-yz/?vlon=5.14&vlat=-0.13&fov=100.0&pc=true&lon=121.61136592&lat=29.87855579&z=16.577
  1233. geometry: 有的attributes: 属性是:
  1234. classification:
  1235. color:
  1236. indices:
  1237. normal:
  1238. position:
  1239. 最好有个spacing
  1240. */