PotreeRendererNew.js 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746
  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("uNodeSpacing", node.geometryNode.estimatedSpacing);
  658. shader.setUniform1f("uPCIndex", i);
  659. // uBBSize
  660. if (shadowMaps.length > 0) {
  661. const lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  662. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  663. let bindingStart = 5;
  664. let bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => (a + i));
  665. gl.uniform1iv(lShadowMap, bindingPoints);
  666. for (let i = 0; i < shadowMaps.length; i++) {
  667. let shadowMap = shadowMaps[i];
  668. let bindingPoint = bindingPoints[i];
  669. let glTexture = this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  670. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  671. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  672. }
  673. {
  674. let worldViewMatrices = shadowMaps
  675. .map(sm => sm.camera.matrixWorldInverse)
  676. .map(view => new THREE.Matrix4().multiplyMatrices(view, world))
  677. let flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  678. const lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  679. gl.uniformMatrix4fv(lWorldView, false, flattenedMatrices);
  680. }
  681. {
  682. let flattenedMatrices = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  683. const lProj = shader.uniformLocations["uShadowProj[0]"];
  684. gl.uniformMatrix4fv(lProj, false, flattenedMatrices);
  685. }
  686. }
  687. const geometry = node.geometryNode.geometry;
  688. if(geometry.attributes["gps-time"]){
  689. const bufferAttribute = geometry.attributes["gps-time"];
  690. const attGPS = octree.getAttribute("gps-time");
  691. let initialRange = attGPS.initialRange;
  692. let initialRangeSize = initialRange[1] - initialRange[0];
  693. let globalRange = attGPS.range;
  694. let globalRangeSize = globalRange[1] - globalRange[0];
  695. let scale = initialRangeSize / globalRangeSize;
  696. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  697. scale = Number.isNaN(scale) ? 1 : scale;
  698. offset = Number.isNaN(offset) ? 0 : offset;
  699. shader.setUniform1f("uGpsScale", scale);
  700. shader.setUniform1f("uGpsOffset", offset);
  701. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  702. let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  703. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  704. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  705. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  706. let normalizedClipRange = [
  707. (uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize,
  708. (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize,
  709. ];
  710. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  711. // // ranges in full gps coordinate system
  712. // const globalRange = attGPS.range;
  713. // const bufferRange = bufferAttribute.potree.range;
  714. // // ranges in [0, 1]
  715. // // normalizedGlobalRange = [0, 1]
  716. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  717. // const globalWidth = globalRange[1] - globalRange[0];
  718. // const normalizedBufferRange = [
  719. // (bufferRange[0] - globalRange[0]) / globalWidth,
  720. // (bufferRange[1] - globalRange[0]) / globalWidth,
  721. // ];
  722. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  723. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  724. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  725. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  726. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  727. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  728. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  729. }
  730. {
  731. let uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  732. let uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  733. let uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  734. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  735. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  736. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  737. }
  738. let webglBuffer = null;
  739. if(!this.buffers.has(geometry)){
  740. webglBuffer = this.createBuffer(geometry);
  741. this.buffers.set(geometry, webglBuffer);
  742. }else{
  743. webglBuffer = this.buffers.get(geometry);
  744. for(let attributeName in geometry.attributes){
  745. let attribute = geometry.attributes[attributeName];
  746. if(attribute.version > webglBuffer.vbos.get(attributeName).version){
  747. this.updateBuffer(geometry);
  748. }
  749. }
  750. }
  751. gl.bindVertexArray(webglBuffer.vao);
  752. let isExtraAttribute =
  753. attributeLocations[material.activeAttributeName] === undefined
  754. && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  755. if(isExtraAttribute){
  756. const attributeLocation = attributeLocations["aExtra"].location;
  757. for(const attributeName in geometry.attributes){
  758. const bufferAttribute = geometry.attributes[attributeName];
  759. const vbo = webglBuffer.vbos.get(attributeName);
  760. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  761. gl.disableVertexAttribArray(attributeLocation);
  762. }
  763. const attName = material.activeAttributeName;
  764. const bufferAttribute = geometry.attributes[attName];
  765. const vbo = webglBuffer.vbos.get(attName);
  766. if(bufferAttribute !== undefined && vbo !== undefined){
  767. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  768. let normalized = bufferAttribute.normalized;
  769. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  770. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  771. gl.enableVertexAttribArray(attributeLocation);
  772. }
  773. {
  774. const attExtra = octree.pcoGeometry.pointAttributes.attributes
  775. .find(a => a.name === attName);
  776. let range = material.getRange(attName);
  777. if(!range){
  778. range = attExtra.range;
  779. }
  780. if(!range){
  781. range = [0, 1];
  782. }
  783. let initialRange = attExtra.initialRange;
  784. let initialRangeSize = initialRange[1] - initialRange[0];
  785. let globalRange = range;
  786. let globalRangeSize = globalRange[1] - globalRange[0];
  787. let scale = initialRangeSize / globalRangeSize;
  788. let offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  789. scale = Number.isNaN(scale) ? 1 : scale;
  790. offset = Number.isNaN(offset) ? 0 : offset;
  791. shader.setUniform1f("uExtraScale", scale);
  792. shader.setUniform1f("uExtraOffset", offset);
  793. }
  794. }else{
  795. for(const attributeName in geometry.attributes){
  796. const bufferAttribute = geometry.attributes[attributeName];
  797. const vbo = webglBuffer.vbos.get(attributeName);
  798. if(attributeLocations[attributeName] !== undefined){
  799. const attributeLocation = attributeLocations[attributeName].location;
  800. let type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  801. let normalized = bufferAttribute.normalized;
  802. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  803. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  804. gl.enableVertexAttribArray(attributeLocation);
  805. }
  806. }
  807. }
  808. let numPoints = webglBuffer.numElements;
  809. gl.drawArrays(gl.POINTS, 0, numPoints);
  810. //gl.drawArrays(gl.TRIANGLES, 0, numPoints);
  811. i++;
  812. }
  813. gl.bindVertexArray(null);
  814. viewer.addTimeMark('renderNodes','end')
  815. }
  816. renderOctree(octrees, nodes, camera, target, params = {}){
  817. viewer.addTimeMark('renderOctree','start')
  818. let octree
  819. if(octrees instanceof Array){
  820. octree = octrees[0];
  821. }else{
  822. octree = octrees; octrees = [octree]
  823. }
  824. let gl = this.gl;
  825. let material = params.material ? params.material : octree.material;
  826. let shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  827. let view = camera.matrixWorldInverse;
  828. let viewInv = camera.matrixWorld;
  829. if(params.viewOverride){
  830. view = params.viewOverride;
  831. viewInv = view.clone().invert();
  832. }
  833. let proj = camera.projectionMatrix;
  834. let projInv = proj.clone().invert();
  835. //let worldView = new THREE.Matrix4();
  836. let shader = null;
  837. let visibilityTextureData = null;
  838. let currentTextureBindingPoint = 0;
  839. if (material.pointSizeType >= 0) {//最好搬到renderNodes
  840. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  841. material.activeAttributeName === "level of detail") {
  842. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  843. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  844. const vnt = material.visibleNodesTexture;
  845. const data = vnt.image.data;
  846. data.set(visibilityTextureData.data);
  847. vnt.needsUpdate = true;
  848. }
  849. }
  850. { // UPDATE SHADER AND TEXTURES
  851. if (!this.shaders.has(material)) {
  852. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  853. let shader = new Shader(gl, "pointcloud", vs, fs);
  854. this.shaders.set(material, shader);
  855. }
  856. shader = this.shaders.get(material);
  857. if(material.shaderNeedsUpdate)
  858. {
  859. let [vs, fs] = [material.vertexShader, material.fragmentShader];
  860. let numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  861. let num_in_clipboxes = (material.clipBoxes_in && material.clipBoxes_in.length) ? material.clipBoxes_in.length : 0;
  862. let num_out_clipboxes = (material.clipBoxes_out && material.clipBoxes_out.length) ? material.clipBoxes_out.length : 0;
  863. let num_highlightBox = (material.highlightBoxes && material.highlightBoxes.length) ? material.highlightBoxes.length : 0;
  864. let numClipSpheres = (params.clipSpheres && params.clipSpheres.length) ? params.clipSpheres.length : 0;
  865. let numClipPolygons = (material.clipPolygons && material.clipPolygons.length) ? material.clipPolygons.length : 0;
  866. let defines = [
  867. `#define num_shadowmaps ${shadowMaps.length}`,
  868. `#define num_snapshots ${numSnapshots}`,
  869. `#define num_in_clipboxes ${num_in_clipboxes}`, //改
  870. `#define num_out_clipboxes ${num_out_clipboxes}`, //改
  871. `#define num_highlightBox ${num_highlightBox}`, //改
  872. `#define num_clipspheres ${numClipSpheres}`,
  873. ];
  874. //add:-----------
  875. if(material.bigClipInBox ){//裁剪下载
  876. defines.push('#define bigClipInBox')
  877. }
  878. if(material.usePanoMap){
  879. defines.push("#define usePanoMap");
  880. }
  881. if(material.useFilterByNormal){
  882. defines.push("#define use_filter_by_normal");
  883. //Potree.settings.editType == 'pano' ? defines.push("#define attenuated_opacity2") : defines.push("#define attenuated_opacity");
  884. }
  885. //---------------
  886. if(octree.pcoGeometry.root.isLoaded()){
  887. let attributes = octree.pcoGeometry.root.geometry.attributes;
  888. if(attributes["gps-time"]){
  889. defines.push("#define clip_gps_enabled");
  890. }
  891. if(attributes["return number"]){
  892. defines.push("#define clip_return_number_enabled");
  893. }
  894. if(attributes["number of returns"]){
  895. defines.push("#define clip_number_of_returns_enabled");
  896. }
  897. if(attributes["source id"] || attributes["point source id"]){
  898. defines.push("#define clip_point_source_id_enabled");
  899. }
  900. }
  901. let definesString = defines.join("\n");
  902. let vsVersionIndex = vs.indexOf("#version ");
  903. let fsVersionIndex = fs.indexOf("#version ");
  904. if(vsVersionIndex >= 0){
  905. vs = vs.replace(/(#version .*)/, `$1\n${definesString}`)
  906. }else{
  907. vs = `${definesString}\n${vs}`;
  908. }
  909. if(fsVersionIndex >= 0){
  910. fs = fs.replace(/(#version .*)/, `$1\n${definesString}`)
  911. }else{
  912. fs = `${definesString}\n${fs}`;
  913. }
  914. shader.update(vs, fs);
  915. material.shaderNeedsUpdate = false;
  916. }
  917. for (let uniformName of Object.keys(material.uniforms)) {
  918. let uniform = material.uniforms[uniformName];
  919. if (uniform.type == "t") {
  920. let texture = uniform.value;
  921. if (!texture) {
  922. continue;
  923. }
  924. //add
  925. if(uniformName == 'pano0Map' || uniformName == 'pano1Map' ){ //属于cubeTex,另外设置
  926. continue
  927. }
  928. if (!this.textures.has(texture)) {
  929. let webglTexture = new WebGLTexture(gl, texture);
  930. this.textures.set(texture, webglTexture);
  931. }
  932. let webGLTexture = this.textures.get(texture);
  933. webGLTexture.update();
  934. }
  935. }
  936. }
  937. gl.useProgram(shader.program);
  938. /* let transparent = false;
  939. if(params.transparent !== undefined){
  940. transparent = params.transparent && material.opacity < 1;
  941. }else{
  942. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  943. }
  944. if (transparent){
  945. gl.enable(gl.BLEND);
  946. if(params.notAdditiveBlending){
  947. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending
  948. gl.enable(gl.DEPTH_TEST);
  949. gl.depthMask(true); //如果不开启depthWrite,深度会错乱。
  950. }else{
  951. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  952. gl.disable(gl.DEPTH_TEST);
  953. gl.depthMask(false);
  954. }
  955. } else {
  956. gl.disable(gl.BLEND);
  957. gl.depthMask(true);
  958. gl.enable(gl.DEPTH_TEST);
  959. }
  960. if(params.blendFunc !== undefined){
  961. gl.enable(gl.BLEND);
  962. gl.blendFunc(...params.blendFunc);
  963. }
  964. if(params.depthTest !== undefined){
  965. if(params.depthTest === true){
  966. gl.enable(gl.DEPTH_TEST);
  967. }else{
  968. gl.disable(gl.DEPTH_TEST);
  969. }
  970. }
  971. if(params.depthWrite !== undefined){
  972. if(params.depthWrite === true){
  973. gl.depthMask(true);
  974. }else{
  975. gl.depthMask(false);
  976. }
  977. } */
  978. { // UPDATE UNIFORMS
  979. shader.setUniformMatrix4("projectionMatrix", proj);
  980. shader.setUniformMatrix4("viewMatrix", view);
  981. shader.setUniformMatrix4("uViewInv", viewInv);
  982. shader.setUniformMatrix4("uProjInv", projInv);
  983. /* let screenWidth = target ? target.width : material.screenWidth;
  984. let screenHeight = target ? target.height : material.screenHeight;
  985. shader.setUniform1f("uScreenWidth", screenWidth);
  986. shader.setUniform1f("uScreenHeight", screenHeight); */
  987. shader.setUniform2f('resolution', material.resolution.toArray())
  988. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  989. shader.setUniform1f("near", camera.near);
  990. shader.setUniform1f("far", camera.far);
  991. if(camera instanceof THREE.OrthographicCamera){
  992. shader.setUniform("uUseOrthographicCamera", true);
  993. shader.setUniform("uOrthoWidth", (camera.right - camera.left) / camera.zoom); //改
  994. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  995. }else{
  996. shader.setUniform("uUseOrthographicCamera", false);
  997. }
  998. /* if(material.clipBoxes.length + material.clipPolygons.length === 0){//改
  999. shader.setUniform1i("clipTask", ClipTask.NONE);
  1000. }else{
  1001. shader.setUniform1i("clipTask", material.clipTask);
  1002. }
  1003. shader.setUniform1i("clipMethod", material.clipMethod);*/
  1004. //改
  1005. if (material.clipBoxes_in && material.clipBoxes_in.length > 0) {
  1006. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  1007. const lClipBoxes = shader.uniformLocations["clipBoxes_in[0]"];
  1008. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes_in.value);
  1009. }
  1010. if (material.clipBoxes_out && material.clipBoxes_out.length > 0) {//add
  1011. const lClipBoxes2 = shader.uniformLocations["clipBoxes_out[0]"];
  1012. gl.uniformMatrix4fv(lClipBoxes2, false, material.uniforms.clipBoxes_out.value);
  1013. }
  1014. if (material.highlightBoxes && material.highlightBoxes.length > 0) {//add
  1015. const boxes_highlight = shader.uniformLocations["boxes_highlight[0]"];
  1016. gl.uniformMatrix4fv(boxes_highlight, false, material.uniforms.boxes_highlight.value);
  1017. }
  1018. if (material.bigClipInBox ) {//add
  1019. shader.setUniformMatrix4("clipBoxBig_in", material.uniforms.clipBoxBig_in.value);
  1020. }
  1021. // TODO CLIPSPHERES
  1022. if(params.clipSpheres && params.clipSpheres.length > 0){
  1023. let clipSpheres = params.clipSpheres;
  1024. let matrices = [];
  1025. for(let clipSphere of clipSpheres){
  1026. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  1027. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  1028. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  1029. let clipToWorld = clipSphere.matrixWorld;
  1030. let viewToWorld = camera.matrixWorld
  1031. let worldToClip = clipToWorld.clone().invert();
  1032. let viewToClip = new THREE.Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  1033. matrices.push(viewToClip);
  1034. }
  1035. let flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  1036. const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  1037. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  1038. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  1039. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  1040. }
  1041. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  1042. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  1043. // uniform float uPCIndex
  1044. shader.setUniform1f("uOctreeSpacing", material.spacing);
  1045. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  1046. shader.setUniform2f("elevationRange", material.elevationRange);
  1047. shader.setUniform2f("intensityRange", material.intensityRange);
  1048. shader.setUniform3f("uIntensity_gbc", [
  1049. material.intensityGamma,
  1050. material.intensityBrightness,
  1051. material.intensityContrast
  1052. ]);
  1053. shader.setUniform3f("uRGB_gbc", [
  1054. material.rgbGamma,
  1055. material.rgbBrightness,
  1056. material.rgbContrast
  1057. ]);
  1058. shader.setUniform1f("uTransition", material.transition);
  1059. shader.setUniform1f("wRGB", material.weightRGB);
  1060. shader.setUniform1f("wIntensity", material.weightIntensity);
  1061. shader.setUniform1f("wElevation", material.weightElevation);
  1062. shader.setUniform1f("wClassification", material.weightClassification);
  1063. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  1064. shader.setUniform1f("wSourceID", material.weightSourceID);
  1065. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  1066. //==========================
  1067. //gl.TEXTURE_CUBE_MAP: 34067
  1068. //gl.TEXTURE0=33984 , vnWebGLTexture.target=gl.TEXTURE_2D = 3353
  1069. let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);//最好搬到renderNodes
  1070. if(vnWebGLTexture){
  1071. shader.setUniform1i("visibleNodes", currentTextureBindingPoint); //为何之前写的是"visibleNodesTexture",但和"visibleNodes"效果相同?可shader里只有"visibleNodes"
  1072. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  1073. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  1074. currentTextureBindingPoint++;
  1075. }
  1076. let gradientTexture = this.textures.get(material.gradientTexture);
  1077. shader.setUniform1i("gradient", currentTextureBindingPoint);
  1078. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  1079. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  1080. currentTextureBindingPoint++;
  1081. const repeat = material.elevationGradientRepeat;
  1082. if(repeat === ElevationGradientRepeat.REPEAT){
  1083. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  1084. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  1085. }else if(repeat === ElevationGradientRepeat.MIRRORED_REPEAT){
  1086. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  1087. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  1088. }else{
  1089. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  1090. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  1091. }
  1092. currentTextureBindingPoint++;
  1093. let classificationTexture = this.textures.get(material.classificationTexture);
  1094. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  1095. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  1096. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  1097. currentTextureBindingPoint++;
  1098. let matcapTexture = this.textures.get(material.matcapTexture);
  1099. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  1100. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  1101. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  1102. currentTextureBindingPoint++;
  1103. if (material.snapEnabled === true) {
  1104. {
  1105. const lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  1106. const lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  1107. let bindingStart = currentTextureBindingPoint;
  1108. let lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => (a + i));
  1109. let lSnapshotDepthBindingPoints = new Array(5)
  1110. .fill(1 + Math.max(...lSnapshotBindingPoints))
  1111. .map((a, i) => (a + i));
  1112. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  1113. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  1114. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  1115. for (let i = 0; i < 5; i++) {
  1116. let texture = material.uniforms[`uSnapshot`].value[i];
  1117. let textureDepth = material.uniforms[`uSnapshotDepth`].value[i];
  1118. if (!texture) {
  1119. break;
  1120. }
  1121. let snapTexture = this.threeRenderer.properties.get(texture).__webglTexture;
  1122. let snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  1123. let bindingPoint = lSnapshotBindingPoints[i];
  1124. let depthBindingPoint = lSnapshotDepthBindingPoints[i];
  1125. gl.activeTexture(gl[`TEXTURE${bindingPoint}`]);
  1126. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  1127. gl.activeTexture(gl[`TEXTURE${depthBindingPoint}`]);
  1128. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  1129. }
  1130. }
  1131. {
  1132. let flattenedMatrices = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  1133. const lSnapView = shader.uniformLocations["uSnapView[0]"];
  1134. gl.uniformMatrix4fv(lSnapView, false, flattenedMatrices);
  1135. }
  1136. {
  1137. let flattenedMatrices = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  1138. const lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  1139. gl.uniformMatrix4fv(lSnapProj, false, flattenedMatrices);
  1140. }
  1141. {
  1142. let flattenedMatrices = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  1143. const lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  1144. gl.uniformMatrix4fv(lSnapProjInv, false, flattenedMatrices);
  1145. }
  1146. {
  1147. let flattenedMatrices = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  1148. const lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  1149. gl.uniformMatrix4fv(lSnapViewInv, false, flattenedMatrices);
  1150. }
  1151. }
  1152. //=============add===========
  1153. if(material.usePanoMap){//为什么pointsize失效
  1154. shader.setUniform1f("progress", material.uniforms.progress.value);
  1155. shader.setUniform1f("easeInOutRatio", material.uniforms.easeInOutRatio.value);
  1156. shader.setUniform3f("pano0Position", material.uniforms.pano0Position.value.toArray());
  1157. shader.setUniform3f("pano1Position", material.uniforms.pano1Position.value.toArray());
  1158. shader.setUniform('pano0Matrix', material.uniforms.pano0Matrix.value);
  1159. shader.setUniform('pano1Matrix', material.uniforms.pano1Matrix.value);
  1160. let pano0Map = material.uniforms.pano0Map.value
  1161. if(pano0Map){
  1162. this.threeRenderer._textures.safeSetTextureCube( pano0Map, ++currentTextureBindingPoint );
  1163. shader.setUniform1i('pano0Map', currentTextureBindingPoint);
  1164. }
  1165. let pano1Map = material.uniforms.pano1Map.value
  1166. if(pano1Map){
  1167. this.threeRenderer._textures.safeSetTextureCube( pano1Map, ++currentTextureBindingPoint );
  1168. shader.setUniform1i('pano1Map', currentTextureBindingPoint);
  1169. }
  1170. //注: three.js我添加了个 _textures, safeSetTextureCube里主要就是activeTexture和bindTexture
  1171. }
  1172. }
  1173. viewer.addTimeMark('renderOctree','end')
  1174. params.currentTextureBindingPoint = currentTextureBindingPoint
  1175. octrees.forEach(octree=>{
  1176. this.renderNodes(octree, nodes || octree.visibleNodes, visibilityTextureData, camera, target, shader, params);
  1177. })
  1178. gl.activeTexture(gl.TEXTURE2);
  1179. gl.bindTexture(gl.TEXTURE_2D, null);
  1180. gl.activeTexture(gl.TEXTURE0);
  1181. //gl.bindTexture(gl.TEXTURE_2D, null); //add
  1182. //add 恢复为不透明(否则renderToCubeMap时的贴图会被渲染成高亮的颜色)
  1183. gl.disable(gl.BLEND);
  1184. gl.depthMask(true);
  1185. gl.enable(gl.DEPTH_TEST);
  1186. //DEPTH_TEST等需要恢复吗
  1187. }
  1188. render(scene, camera, target = null, params = {}) {
  1189. const gl = this.gl;
  1190. // PREPARE
  1191. if (target != null) {
  1192. this.threeRenderer.setRenderTarget(target);
  1193. }
  1194. //camera.updateProjectionMatrix();
  1195. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  1196. const traversalResult = this.traverse(scene);
  1197. //排序
  1198. if(Potree.settings.notAdditiveBlending){//add
  1199. traversalResult.octrees.forEach(tree=>{
  1200. if(tree.material.opacity==1){
  1201. tree._z = Infinity //不透明的先渲染
  1202. }else{
  1203. let center = tree.boundCenter ? tree.boundCenter.clone() : tree.boundingBox.getCenter(tree.boundCenter).applyMatrix4(tree.matrixWorld)
  1204. center.project(camera)
  1205. tree._z = center.z
  1206. }
  1207. })
  1208. traversalResult.octrees.sort((tree1,tree2)=>{
  1209. return tree2._z - tree1._z //降序 (-1 朝外)。 离屏幕近的后渲染
  1210. })
  1211. }
  1212. // RENDER
  1213. let mat = traversalResult.octrees[0].material
  1214. if(Potree.settings.cloudSameMat && viewer.scene.volumes.length == 0 && mat.pointSizeType != PointSizeType.ADAPTIVE && mat.activeAttributeName != "level of detail"){
  1215. this.renderOctree(traversalResult.octrees, null, camera, target, params); //所有点云除了个别属性需要在shader中更新,其他都使用第一个点云的材质
  1216. }else for (const octree of traversalResult.octrees) {
  1217. for (const octree of traversalResult.octrees) {
  1218. this.renderOctree(octree, octree.visibleNodes, camera, target, params);
  1219. }
  1220. }
  1221. //if (octree material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") {
  1222. // CLEANUP
  1223. gl.activeTexture(gl.TEXTURE1);
  1224. gl.bindTexture(gl.TEXTURE_2D, null);
  1225. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  1226. gl.bindVertexArray(null);
  1227. this.threeRenderer.resetState();
  1228. }
  1229. };
  1230. /*
  1231. 中东的链接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
  1232. geometry: 有的attributes: 属性是:
  1233. classification:
  1234. color:
  1235. indices:
  1236. normal:
  1237. position:
  1238. 最好有个spacing
  1239. */