园林绿化
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9188 lines
381 KiB

  1. // import * as mars3d from "mars3d"
  2. // const Cesium = mars3d.Cesium
  3. (function () {
  4. var requirejs, require, define;
  5. (function (undef) {
  6. var main, req, makeMap, handlers,
  7. defined = {},
  8. waiting = {},
  9. config = {},
  10. defining = {},
  11. hasOwn = Object.prototype.hasOwnProperty,
  12. aps = [].slice,
  13. jsSuffixRegExp = /\.js$/;
  14. function hasProp(obj, prop) {
  15. return hasOwn.call(obj, prop);
  16. }
  17. /**
  18. * Given a relative module name, like ./something, normalize it to
  19. * a real name that can be mapped to a path.
  20. * @param {String} name the relative name
  21. * @param {String} baseName a real name that the name arg is relative
  22. * to.
  23. * @returns {String} normalized name
  24. */
  25. function normalize(name, baseName) {
  26. var nameParts, nameSegment, mapValue, foundMap, lastIndex,
  27. foundI, foundStarMap, starI, i, j, part, normalizedBaseParts,
  28. baseParts = baseName && baseName.split("/"),
  29. map = config.map,
  30. starMap = (map && map['*']) || {};
  31. //Adjust any relative paths.
  32. if (name) {
  33. name = name.split('/');
  34. lastIndex = name.length - 1;
  35. // If wanting node ID compatibility, strip .js from end
  36. // of IDs. Have to do this here, and not in nameToUrl
  37. // because node allows either .js or non .js to map
  38. // to same file.
  39. if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
  40. name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
  41. }
  42. // Starts with a '.' so need the baseName
  43. if (name[0].charAt(0) === '.' && baseParts) {
  44. //Convert baseName to array, and lop off the last part,
  45. //so that . matches that 'directory' and not name of the baseName's
  46. //module. For instance, baseName of 'one/two/three', maps to
  47. //'one/two/three.js', but we want the directory, 'one/two' for
  48. //this normalization.
  49. normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
  50. name = normalizedBaseParts.concat(name);
  51. }
  52. //start trimDots
  53. for (i = 0; i < name.length; i++) {
  54. part = name[i];
  55. if (part === '.') {
  56. name.splice(i, 1);
  57. i -= 1;
  58. } else if (part === '..') {
  59. // If at the start, or previous value is still ..,
  60. // keep them so that when converted to a path it may
  61. // still work when converted to a path, even though
  62. // as an ID it is less than ideal. In larger point
  63. // releases, may be better to just kick out an error.
  64. if (i === 0 || (i === 1 && name[2] === '..') || name[i - 1] === '..') {
  65. continue;
  66. } else if (i > 0) {
  67. name.splice(i - 1, 2);
  68. i -= 2;
  69. }
  70. }
  71. }
  72. //end trimDots
  73. name = name.join('/');
  74. }
  75. //Apply map config if available.
  76. if ((baseParts || starMap) && map) {
  77. nameParts = name.split('/');
  78. for (i = nameParts.length; i > 0; i -= 1) {
  79. nameSegment = nameParts.slice(0, i).join("/");
  80. if (baseParts) {
  81. //Find the longest baseName segment match in the config.
  82. //So, do joins on the biggest to smallest lengths of baseParts.
  83. for (j = baseParts.length; j > 0; j -= 1) {
  84. mapValue = map[baseParts.slice(0, j).join('/')];
  85. //baseName segment has config, find if it has one for
  86. //this name.
  87. if (mapValue) {
  88. mapValue = mapValue[nameSegment];
  89. if (mapValue) {
  90. //Match, update name to the new value.
  91. foundMap = mapValue;
  92. foundI = i;
  93. break;
  94. }
  95. }
  96. }
  97. }
  98. if (foundMap) {
  99. break;
  100. }
  101. //Check for a star map match, but just hold on to it,
  102. //if there is a shorter segment match later in a matching
  103. //config, then favor over this star map.
  104. if (!foundStarMap && starMap && starMap[nameSegment]) {
  105. foundStarMap = starMap[nameSegment];
  106. starI = i;
  107. }
  108. }
  109. if (!foundMap && foundStarMap) {
  110. foundMap = foundStarMap;
  111. foundI = starI;
  112. }
  113. if (foundMap) {
  114. nameParts.splice(0, foundI, foundMap);
  115. name = nameParts.join('/');
  116. }
  117. }
  118. return name;
  119. }
  120. function makeRequire(relName, forceSync) {
  121. return function () {
  122. //A version of a require function that passes a moduleName
  123. //value for items that may need to
  124. //look up paths relative to the moduleName
  125. var args = aps.call(arguments, 0);
  126. //If first arg is not require('string'), and there is only
  127. //one arg, it is the array form without a callback. Insert
  128. //a null so that the following concat is correct.
  129. if (typeof args[0] !== 'string' && args.length === 1) {
  130. args.push(null);
  131. }
  132. return req.apply(undef, args.concat([relName, forceSync]));
  133. };
  134. }
  135. function makeNormalize(relName) {
  136. return function (name) {
  137. return normalize(name, relName);
  138. };
  139. }
  140. function makeLoad(depName) {
  141. return function (value) {
  142. defined[depName] = value;
  143. };
  144. }
  145. function callDep(name) {
  146. if (hasProp(waiting, name)) {
  147. var args = waiting[name];
  148. delete waiting[name];
  149. defining[name] = true;
  150. main.apply(undef, args);
  151. }
  152. if (!hasProp(defined, name) && !hasProp(defining, name)) {
  153. throw new Error('No ' + name);
  154. }
  155. return defined[name];
  156. }
  157. //Turns a plugin!resource to [plugin, resource]
  158. //with the plugin being undefined if the name
  159. //did not have a plugin prefix.
  160. function splitPrefix(name) {
  161. var prefix,
  162. index = name ? name.indexOf('!') : -1;
  163. if (index > -1) {
  164. prefix = name.substring(0, index);
  165. name = name.substring(index + 1, name.length);
  166. }
  167. return [prefix, name];
  168. }
  169. //Creates a parts array for a relName where first part is plugin ID,
  170. //second part is resource ID. Assumes relName has already been normalized.
  171. function makeRelParts(relName) {
  172. return relName ? splitPrefix(relName) : [];
  173. }
  174. /**
  175. * Makes a name map, normalizing the name, and using a plugin
  176. * for normalization if necessary. Grabs a ref to plugin
  177. * too, as an optimization.
  178. */
  179. makeMap = function (name, relParts) {
  180. var plugin,
  181. parts = splitPrefix(name),
  182. prefix = parts[0],
  183. relResourceName = relParts[1];
  184. name = parts[1];
  185. if (prefix) {
  186. prefix = normalize(prefix, relResourceName);
  187. plugin = callDep(prefix);
  188. }
  189. //Normalize according
  190. if (prefix) {
  191. if (plugin && plugin.normalize) {
  192. name = plugin.normalize(name, makeNormalize(relResourceName));
  193. } else {
  194. name = normalize(name, relResourceName);
  195. }
  196. } else {
  197. name = normalize(name, relResourceName);
  198. parts = splitPrefix(name);
  199. prefix = parts[0];
  200. name = parts[1];
  201. if (prefix) {
  202. plugin = callDep(prefix);
  203. }
  204. }
  205. //Using ridiculous property names for space reasons
  206. return {
  207. f: prefix ? prefix + '!' + name : name, //fullName
  208. n: name,
  209. pr: prefix,
  210. p: plugin
  211. };
  212. };
  213. function makeConfig(name) {
  214. return function () {
  215. return (config && config.config && config.config[name]) || {};
  216. };
  217. }
  218. handlers = {
  219. require: function (name) {
  220. return makeRequire(name);
  221. },
  222. exports: function (name) {
  223. var e = defined[name];
  224. if (typeof e !== 'undefined') {
  225. return e;
  226. } else {
  227. return (defined[name] = {});
  228. }
  229. },
  230. module: function (name) {
  231. return {
  232. id: name,
  233. uri: '',
  234. exports: defined[name],
  235. config: makeConfig(name)
  236. };
  237. }
  238. };
  239. main = function (name, deps, callback, relName) {
  240. var cjsModule, depName, ret, map, i, relParts,
  241. args = [],
  242. callbackType = typeof callback,
  243. usingExports;
  244. //Use name if no relName
  245. relName = relName || name;
  246. relParts = makeRelParts(relName);
  247. //Call the callback to define the module, if necessary.
  248. if (callbackType === 'undefined' || callbackType === 'function') {
  249. //Pull out the defined dependencies and pass the ordered
  250. //values to the callback.
  251. //Default to [require, exports, module] if no deps
  252. deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps;
  253. for (i = 0; i < deps.length; i += 1) {
  254. map = makeMap(deps[i], relParts);
  255. depName = map.f;
  256. //Fast path CommonJS standard dependencies.
  257. if (depName === "require") {
  258. args[i] = handlers.require(name);
  259. } else if (depName === "exports") {
  260. //CommonJS module spec 1.1
  261. args[i] = handlers.exports(name);
  262. usingExports = true;
  263. } else if (depName === "module") {
  264. //CommonJS module spec 1.1
  265. cjsModule = args[i] = handlers.module(name);
  266. } else if (hasProp(defined, depName) ||
  267. hasProp(waiting, depName) ||
  268. hasProp(defining, depName)) {
  269. args[i] = callDep(depName);
  270. } else if (map.p) {
  271. map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {});
  272. args[i] = defined[depName];
  273. } else {
  274. throw new Error(name + ' missing ' + depName);
  275. }
  276. }
  277. ret = callback ? callback.apply(defined[name], args) : undefined;
  278. if (name) {
  279. //If setting exports via "module" is in play,
  280. //favor that over return value and exports. After that,
  281. //favor a non-undefined return value over exports use.
  282. if (cjsModule && cjsModule.exports !== undef &&
  283. cjsModule.exports !== defined[name]) {
  284. defined[name] = cjsModule.exports;
  285. } else if (ret !== undef || !usingExports) {
  286. //Use the return value from the function.
  287. defined[name] = ret;
  288. }
  289. }
  290. } else if (name) {
  291. //May just be an object definition for the module. Only
  292. //worry about defining if have a module name.
  293. defined[name] = callback;
  294. }
  295. };
  296. requirejs = require = req = function (deps, callback, relName, forceSync, alt) {
  297. if (typeof deps === "string") {
  298. if (handlers[deps]) {
  299. //callback in this case is really relName
  300. return handlers[deps](callback);
  301. }
  302. //Just return the module wanted. In this scenario, the
  303. //deps arg is the module name, and second arg (if passed)
  304. //is just the relName.
  305. //Normalize module name, if it contains . or ..
  306. return callDep(makeMap(deps, makeRelParts(callback)).f);
  307. } else if (!deps.splice) {
  308. //deps is a config object, not an array.
  309. config = deps;
  310. if (config.deps) {
  311. req(config.deps, config.callback);
  312. }
  313. if (!callback) {
  314. return;
  315. }
  316. if (callback.splice) {
  317. //callback is an array, which means it is a dependency list.
  318. //Adjust args if there are dependencies
  319. deps = callback;
  320. callback = relName;
  321. relName = null;
  322. } else {
  323. deps = undef;
  324. }
  325. }
  326. //Support require(['a'])
  327. callback = callback || function () { };
  328. //If relName is a function, it is an errback handler,
  329. //so remove it.
  330. if (typeof relName === 'function') {
  331. relName = forceSync;
  332. forceSync = alt;
  333. }
  334. //Simulate async callback;
  335. if (forceSync) {
  336. main(undef, deps, callback, relName);
  337. } else {
  338. //Using a non-zero value because of concern for what old browsers
  339. //do, and latest browsers "upgrade" to 4 if lower value is used:
  340. //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
  341. //If want a value immediately, use require('id') instead -- something
  342. //that works in almond on the global level, but not guaranteed and
  343. //unlikely to work in other AMD implementations.
  344. setTimeout(function () {
  345. main(undef, deps, callback, relName);
  346. }, 4);
  347. }
  348. return req;
  349. };
  350. /**
  351. * Just drops the config on the floor, but returns req in case
  352. * the config return value is used.
  353. */
  354. req.config = function (cfg) {
  355. return req(cfg);
  356. };
  357. /**
  358. * Expose module registry for debugging and tooling
  359. */
  360. requirejs._defined = defined;
  361. define = function (name, deps, callback) {
  362. if (typeof name !== 'string') {
  363. throw new Error('See almond README: incorrect module build, no module name');
  364. }
  365. //This module may not have dependencies
  366. if (!deps.splice) {
  367. //deps is not an array, so probably means
  368. //an object literal or factory function for
  369. //the value. Adjust args.
  370. callback = deps;
  371. deps = [];
  372. }
  373. if (!hasProp(defined, name) && !hasProp(waiting, name)) {
  374. waiting[name] = [name, deps, callback];
  375. }
  376. };
  377. define.amd = {
  378. jQuery: true
  379. };
  380. }());
  381. /**
  382. *
  383. * @namespace Cesium
  384. */
  385. //----CesiumMeshVisualizer----
  386. define('Core/RendererUtils',[],function () {
  387. var Cartesian3 = Cesium.Cartesian3;
  388. var CesiumMath = Cesium.Math;
  389. var yUpToZUp = Cesium.Matrix4.fromRotationTranslation(Cesium.Matrix3.fromRotationX(CesiumMath.PI_OVER_TWO));
  390. var scratchTranslation = new Cesium.Cartesian3();
  391. var scratchQuaternion = new Cesium.Quaternion();
  392. var scratchScale = new Cesium.Cartesian3();
  393. var scratchTranslationQuaternionRotationScale = new Cesium.Matrix4();
  394. var computeModelMatrix = new Cesium.Matrix4();
  395. var scratchPosition = new Cesium.Cartesian3();
  396. var clearCommandScratch = new Cesium.ClearCommand({
  397. color: new Cesium.Color(0.0, 0.0, 0.0, 0.0)
  398. });
  399. /**
  400. *
  401. *@constructor
  402. *@memberof Cesium
  403. */
  404. function RendererUtils() { }
  405. /**
  406. *使用帧缓冲技术执行渲染命令渲染到纹理
  407. *@param {Cesium.DrawCommand|Array<Cesium.DrawCommand>}drawCommand 渲染命令集合
  408. *@param {Cesium.FrameState}frameState 帧状态对象可以从Cesium.Scene中获取
  409. *@param {Cesium.Texture}outpuTexture 将渲染到的目标纹理对象
  410. *@param {Cesium.Texture}[outputDepthTexture] 可选输出的深度纹理
  411. */
  412. RendererUtils.renderToTexture = function (drawCommand, frameState, outputTexture, outputDepthTexture) {
  413. var drawCommands = Array.isArray(drawCommand) ? drawCommand : [drawCommand];
  414. var context = frameState.context;
  415. var framebuffer = null, destroy = false;
  416. if (outputTexture instanceof Cesium.Framebuffer) {
  417. framebuffer = outputTexture;
  418. }
  419. if (!framebuffer) {
  420. framebuffer = new Cesium.Framebuffer({
  421. context: context,
  422. colorTextures: [outputTexture],
  423. destroyAttachments: false,
  424. depthTexture: outputDepthTexture
  425. });
  426. destroy = true;
  427. }
  428. var clearCommand = clearCommandScratch;
  429. clearCommand.framebuffer = framebuffer;
  430. clearCommand.renderState = frameState.renderState;
  431. clearCommand.execute(context);
  432. drawCommands.forEach(function (drawCommand) {
  433. drawCommand.framebuffer = framebuffer;
  434. drawCommand.execute(context);
  435. });
  436. if (destroy) {
  437. framebuffer.destroy();
  438. }
  439. }
  440. /**
  441. *
  442. *@param {Cesium.Matrix4}srcMatrix
  443. *@param {Cesium.Matrix4}dstMatrix
  444. *@param {Cesium.Matrix4}
  445. */
  446. RendererUtils.yUp2Zup = function (srcMatrix, dstMatrix) {
  447. return Cesium.Matrix4.multiplyTransformation(srcMatrix, yUpToZUp, dstMatrix);
  448. }
  449. /**
  450. *平移旋转或缩放返回计算之后的模型转换矩阵
  451. *@param {Cesium.Cartesian3}[translation=undefined]
  452. *@param {Object}[rotation=undefined] 旋转参数
  453. *@param {Cesium.Cartesian3}[rotation.axis] 旋转轴
  454. *@param {Number}[rotation.angle] 旋转角度
  455. *@param {Cesium.Cartesian3}[rotation.scale] 缩放
  456. *@param {Cesium.Matrix4}[outModelMatrix] 计算结果矩阵和返回值一样但是传递此参数时则返回值不是新创建的Cesium.Matrix4实例
  457. *@return {Cesium.Matrix4}
  458. */
  459. RendererUtils.computeModelMatrix = function (srcModelMatrix, translation, rotation, scale, outModelMatrix) {
  460. if (arguments.length == 0) {
  461. return srcModelMatrix;
  462. }
  463. var Matrix4 = Cesium.Matrix4;
  464. if (!outModelMatrix) {
  465. outModelMatrix = new Matrix4();
  466. }
  467. Matrix4.clone(srcModelMatrix, outModelMatrix);
  468. if (!translation) {
  469. scratchTranslation.x = 0;
  470. scratchTranslation.y = 0;
  471. scratchTranslation.z = 0;
  472. }
  473. scratchTranslation.x = translation.x;
  474. scratchTranslation.y = translation.y;
  475. scratchTranslation.z = translation.z;
  476. if (!scale) {
  477. scratchScale.x = 0;
  478. scratchScale.y = 0;
  479. scratchScale.z = 0;
  480. }
  481. scratchScale.x = scale.x;
  482. scratchScale.y = scale.y;
  483. scratchScale.z = scale.z;
  484. if (rotation instanceof Cesium.Quaternion) {
  485. Cesium.Quaternion.clone(rotation, scratchQuaternion);
  486. } else {
  487. var axis = rotation.axis;
  488. var angle = rotation.angle;
  489. Cesium.Quaternion.fromAxisAngle(
  490. new Cartesian3(axis.x, axis.y, axis.z),//axis.y=1 y是旋转轴
  491. CesiumMath.toRadians(angle),
  492. scratchQuaternion
  493. );
  494. }
  495. //translate,rotate,scale
  496. Matrix4.fromTranslationQuaternionRotationScale(
  497. scratchTranslation, scratchQuaternion,
  498. scratchScale, scratchTranslationQuaternionRotationScale);
  499. Matrix4.multiplyTransformation(
  500. outModelMatrix,
  501. scratchTranslationQuaternionRotationScale,
  502. outModelMatrix);
  503. return outModelMatrix;
  504. }
  505. return RendererUtils;
  506. });
  507. define('Core/Rotation',[],function () {
  508. /**
  509. *
  510. *@param {Cesium.Cartesian3}axis 旋转轴
  511. *@param {Number}angle 旋转角度
  512. *
  513. *@property {Cesium.Cartesian3}axis 旋转轴
  514. *@property {Number}angle 旋转角度
  515. *@property {Cesium.Event}paramChanged
  516. *@constructor
  517. *@memberof Cesium
  518. */
  519. function Rotation(axis, angle) {
  520. this._axis = axis;
  521. this._angle = angle;
  522. this.paramChanged = new Cesium.Event();
  523. }
  524. Object.defineProperties(Rotation.prototype, {
  525. axis: {
  526. set: function (val) {
  527. if (val.x != this._axis.x
  528. || val.y != this._axis.y
  529. || val.z != this._axis.z) {
  530. this._axis = val;
  531. this.paramChanged.raiseEvent();
  532. }
  533. this._axis = val;
  534. },
  535. get: function () {
  536. return this._axis;
  537. }
  538. },
  539. angle: {
  540. set: function (val) {
  541. if (val != this._angle) {
  542. this._angle = val;
  543. this.paramChanged.raiseEvent();
  544. }
  545. this._angle = val;
  546. },
  547. get: function () {
  548. return this._angle;
  549. }
  550. }
  551. })
  552. return Rotation;
  553. });
  554. define('Util/CSG',[],function () {
  555. // Constructive Solid Geometry (CSG) is a modeling technique that uses Boolean
  556. // operations like union and intersection to combine 3D solids. This library
  557. // implements CSG operations on meshes elegantly and concisely using BSP trees,
  558. // and is meant to serve as an easily understandable implementation of the
  559. // algorithm. All edge cases involving overlapping coplanar polygons in both
  560. // solids are correctly handled.
  561. //
  562. // Example usage:
  563. //
  564. // var cube = CSG.cube();
  565. // var sphere = CSG.sphere({ radius: 1.3 });
  566. // var polygons = cube.subtract(sphere).toPolygons();
  567. //
  568. // ## Implementation Details
  569. //
  570. // All CSG operations are implemented in terms of two functions, `clipTo()` and
  571. // `invert()`, which remove parts of a BSP tree inside another BSP tree and swap
  572. // solid and empty space, respectively. To find the union of `a` and `b`, we
  573. // want to remove everything in `a` inside `b` and everything in `b` inside `a`,
  574. // then combine polygons from `a` and `b` into one solid:
  575. //
  576. // a.clipTo(b);
  577. // b.clipTo(a);
  578. // a.build(b.allPolygons());
  579. //
  580. // The only tricky part is handling overlapping coplanar polygons in both trees.
  581. // The code above keeps both copies, but we need to keep them in one tree and
  582. // remove them in the other tree. To remove them from `b` we can clip the
  583. // inverse of `b` against `a`. The code for union now looks like this:
  584. //
  585. // a.clipTo(b);
  586. // b.clipTo(a);
  587. // b.invert();
  588. // b.clipTo(a);
  589. // b.invert();
  590. // a.build(b.allPolygons());
  591. //
  592. // Subtraction and intersection naturally follow from set operations. If
  593. // union is `A | B`, subtraction is `A - B = ~(~A | B)` and intersection is
  594. // `A & B = ~(~A | ~B)` where `~` is the complement operator.
  595. //
  596. // ## License
  597. //
  598. // Copyright (c) 2011 Evan Wallace (http://madebyevan.com/), under the MIT license.
  599. // # class CSG
  600. // Holds a binary space partition tree representing a 3D solid. Two solids can
  601. // be combined using the `union()`, `subtract()`, and `intersect()` methods.
  602. /**
  603. *源码参见{@link https://github.com/jscad/csg.js} <br/>
  604. *Constructive Solid Geometry (CSG) is a modeling technique that uses Boolean<br/>
  605. *operations like union and intersection to combine 3D solids. This library<br/>
  606. *implements CSG operations on meshes elegantly and concisely using BSP trees,<br/>
  607. *and is meant to serve as an easily understandable implementation of the<br/>
  608. *algorithm. All edge cases involving overlapping coplanar polygons in both<br/>
  609. *solids are correctly handled.<br/>
  610. *
  611. *@example
  612. MeshVisualizer = Cesium.MeshVisualizer;
  613. Mesh = Cesium.Mesh;
  614. MeshMaterial = Cesium.MeshMaterial;
  615. CSG = Cesium.CSG;
  616. GeometryUtils = Cesium.GeometryUtils;
  617. //示例1:
  618. var cube = CSG.cube();
  619. var sphere = CSG.sphere({ radius: 1.3 });
  620. var polygons = cube.subtract(sphere).toPolygons();
  621. //示例2:
  622. var center = Cesium.Cartesian3.fromDegrees(homePosition[0], homePosition[1], 50000);
  623. var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  624. var meshVisualizer = new MeshVisualizer({
  625. modelMatrix: modelMatrix,
  626. up: { z: 1 }
  627. });
  628. viewer.scene.primitives.add(meshVisualizer);
  629. var material = new MeshMaterial({
  630. defaultColor: "rgba(0,0,255,1.0)",
  631. wireframe: true,
  632. side: MeshMaterial.Sides.DOUBLE
  633. });
  634. //创建盒子
  635. var dimensions = new Cesium.Cartesian3(100000, 50000, 50000);
  636. var boxGeometry = Cesium.BoxGeometry.createGeometry(Cesium.BoxGeometry.fromDimensions({
  637. dimensions: dimensions,
  638. vertexFormat: Cesium.VertexFormat.POSITION_ONLY
  639. }));
  640. var box = GeometryUtils.toCSG(boxGeometry);
  641. var boxMesh = new Mesh(box, material);
  642. meshVisualizer.add(boxMesh);
  643. //创建球体
  644. var sphere = new Cesium.SphereGeometry({
  645. radius: 50000.0,
  646. vertexFormat: Cesium.VertexFormat.POSITION_ONLY
  647. });
  648. sphere = Cesium.SphereGeometry.createGeometry(sphere);
  649. sphere = CSG.toCSG(sphere);
  650. var sphereMesh = new Mesh(sphere, material);
  651. sphereMesh.position = new Cesium.Cartesian3(100000, 0, 0)
  652. meshVisualizer.add(sphereMesh);
  653. //并
  654. var unionResult = box.union(sphere);
  655. var unionResultMesh = new Mesh(unionResult, material);
  656. unionResultMesh.position = new Cesium.Cartesian3(300000, 0, 0)
  657. meshVisualizer.add(unionResultMesh);
  658. //交
  659. var intersectResult = box.intersect(sphere);
  660. var intersectResultMesh = new Mesh(intersectResult, material);
  661. intersectResultMesh.position = new Cesium.Cartesian3(500000, 0, 0)
  662. meshVisualizer.add(intersectResultMesh);
  663. //球体减盒子
  664. var subResult = sphere.subtract(box);
  665. var subResultMesh = new Mesh(subResult, material);
  666. subResultMesh.position = new Cesium.Cartesian3(700000, 0, 0)
  667. meshVisualizer.add(subResultMesh);
  668. //盒子减球体
  669. var subResult2 = box.subtract(sphere);
  670. var subResultMesh2 = new Mesh(subResult2, material);
  671. subResultMesh2.position = new Cesium.Cartesian3(900000, 0, 0)
  672. meshVisualizer.add(subResultMesh2);
  673. //渲染CSG创建的几何体
  674. var cube = CSG.cube({
  675. center: [0, 0, 0],
  676. radius: 20000
  677. });
  678. var cubeMtl = new MeshMaterial({
  679. defaultColor: "rgba(255,0,0,1)"
  680. });
  681. meshVisualizer.add(new Mesh({
  682. geometry: cube,
  683. material: cubeMtl,
  684. position: new Cesium.Cartesian3(-100000, 0, 0)
  685. }));
  686. *@memberof Cesium
  687. *@constructor
  688. */
  689. function CSG() {
  690. this.polygons = [];
  691. };
  692. /**
  693. *Construct a CSG solid from a list of `CSG.Polygon` instances.
  694. *@param {Array<Cesium.CSG.Polygon>}
  695. *@param {Array<Cesium.CSG>}
  696. */
  697. CSG.fromPolygons = function (polygons) {
  698. var csg = new CSG();
  699. csg.polygons = polygons;
  700. return csg;
  701. };
  702. CSG.prototype = {
  703. /**
  704. *@return {Cesium.CSG}
  705. */
  706. clone: function () {
  707. var csg = new CSG();
  708. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  709. return csg;
  710. },
  711. /**
  712. *
  713. *@return {Array<Cesium.CSG.Polygon>}
  714. */
  715. toPolygons: function () {
  716. return this.polygons;
  717. },
  718. /**
  719. * Return a new CSG solid representing space in either this solid or in the<br/>
  720. * solid `csg`. Neither this solid nor the solid `csg` are modified.<br/>
  721. * <br/>
  722. * A.union(B)<br/>
  723. * <br/>
  724. *<pre><code>
  725. * +-------+ +-------+
  726. * | | | |
  727. * | A | | |
  728. * | +--+----+ = | +----+
  729. * +----+--+ | +----+ |
  730. * | B | | |
  731. * | | | |
  732. * +-------+ +-------+
  733. *</code></pre>
  734. * @param {Cesium.CSG}csg
  735. * @return {Cesium.CSG}
  736. */
  737. union: function (csg) {
  738. var a = new CSG.Node(this.clone().polygons);
  739. var b = new CSG.Node(csg.clone().polygons);
  740. a.clipTo(b);
  741. b.clipTo(a);
  742. b.invert();
  743. b.clipTo(a);
  744. b.invert();
  745. a.build(b.allPolygons());
  746. return CSG.fromPolygons(a.allPolygons());
  747. },
  748. /**
  749. * Return a new CSG solid representing space in this solid but not in the<br/>
  750. * solid `csg`. Neither this solid nor the solid `csg` are modified.<br/>
  751. * <br/>
  752. * A.subtract(B)<br/>
  753. * <br/>
  754. *<pre><code>
  755. * +-------+ +-------+
  756. * | | | |
  757. * | A | | |
  758. * | +--+----+ = | +--+
  759. * +----+--+ | +----+
  760. * | B |
  761. * | |
  762. * +-------+
  763. *
  764. *</code></pre>
  765. * @param {Cesium.CSG}csg
  766. * @return {Cesium.CSG}
  767. */
  768. subtract: function (csg) {
  769. var a = new CSG.Node(this.clone().polygons);
  770. var b = new CSG.Node(csg.clone().polygons);
  771. a.invert();
  772. a.clipTo(b);
  773. b.clipTo(a);
  774. b.invert();
  775. b.clipTo(a);
  776. b.invert();
  777. a.build(b.allPolygons());
  778. a.invert();
  779. return CSG.fromPolygons(a.allPolygons());
  780. },
  781. /**
  782. * Return a new CSG solid representing space both this solid and in the<br/>
  783. * solid `csg`. Neither this solid nor the solid `csg` are modified.<br/>
  784. * <br/>
  785. * A.intersect(B)<br/>
  786. * <br/>
  787. *<pre><code>
  788. * +-------+
  789. * | |
  790. * | A |
  791. * | +--+----+ = +--+
  792. * +----+--+ | +--+
  793. * | B |
  794. * | |
  795. * +-------+
  796. *
  797. *</code></pre>
  798. * @param {Cesium.CSG}csg
  799. * @return {Cesium.CSG}
  800. */
  801. intersect: function (csg) {
  802. var a = new CSG.Node(this.clone().polygons);
  803. var b = new CSG.Node(csg.clone().polygons);
  804. a.invert();
  805. b.clipTo(a);
  806. b.invert();
  807. a.clipTo(b);
  808. b.clipTo(a);
  809. a.build(b.allPolygons());
  810. a.invert();
  811. return CSG.fromPolygons(a.allPolygons());
  812. },
  813. /**
  814. * Return a new CSG solid with solid and empty space switched. This solid is
  815. * not modified.
  816. * @return {Cesium.CSG}
  817. */
  818. inverse: function () {
  819. var csg = this.clone();
  820. csg.polygons.map(function (p) { p.flip(); });
  821. return csg;
  822. }
  823. };
  824. /**
  825. * Construct an axis-aligned solid cuboid. Optional parameters are `center` and<br/>
  826. * `radius`, which default to `[0, 0, 0]` and `[1, 1, 1]`. The radius can be<br/>
  827. * specified using a single number or a list of three numbers, one for each axis.<br/>
  828. *
  829. *@example
  830. *
  831. * var cube = CSG.cube({
  832. * center: [0, 0, 0],
  833. * radius: 1
  834. * });
  835. *@memberof Cesium.CSG
  836. *@param {Object}options
  837. *@param {Array<Number>|Cesium.CSG.Vector}[options.center=[0, 0, 0]]
  838. *@param {Number|Array<Number>|Cesium.CSG.Vector}[options.radius=1]
  839. *@return {Cesium.CSG}
  840. */
  841. CSG.cube = function (options) {
  842. options = options || {};
  843. var c = new CSG.Vector(options.center || [0, 0, 0]);
  844. var r = !options.radius ? [1, 1, 1] : options.radius.length ?
  845. options.radius : [options.radius, options.radius, options.radius];
  846. return CSG.fromPolygons([
  847. [[0, 4, 6, 2], [-1, 0, 0]],
  848. [[1, 3, 7, 5], [+1, 0, 0]],
  849. [[0, 1, 5, 4], [0, -1, 0]],
  850. [[2, 6, 7, 3], [0, +1, 0]],
  851. [[0, 2, 3, 1], [0, 0, -1]],
  852. [[4, 5, 7, 6], [0, 0, +1]]
  853. ].map(function (info) {
  854. return new CSG.Polygon(info[0].map(function (i) {
  855. var pos = new CSG.Vector(
  856. c.x + r[0] * (2 * !!(i & 1) - 1),
  857. c.y + r[1] * (2 * !!(i & 2) - 1),
  858. c.z + r[2] * (2 * !!(i & 4) - 1)
  859. );
  860. return new CSG.Vertex(pos, new CSG.Vector(info[1]));
  861. }));
  862. }));
  863. };
  864. /**
  865. * Construct a solid sphere. Optional parameters are `center`, `radius`,<br/>
  866. * `slices`, and `stacks`, which default to `[0, 0, 0]`, `1`, `16`, and `8`.<br/>
  867. * The `slices` and `stacks` parameters control the tessellation along the<br/>
  868. * longitude and latitude directions.<br/>
  869. *
  870. *@example
  871. *
  872. * var sphere = CSG.sphere({
  873. * center: [0, 0, 0],
  874. * radius: 1,
  875. * slices: 16,
  876. * stacks: 8
  877. * });
  878. *@memberof Cesium.CSG
  879. *@param {Object}options
  880. *@param {Array<Number>|Cesium.CSG.Vector}[options.center=[0, 0, 0]]
  881. *@param {Number}[options.radius=1]
  882. *@param {Number}[options.slices=16]
  883. *@param {Number}[options.stacks=8]
  884. *@return {Cesium.CSG}
  885. */
  886. CSG.sphere = function (options) {
  887. options = options || {};
  888. var c = new CSG.Vector(options.center || [0, 0, 0]);
  889. var r = options.radius || 1;
  890. var slices = options.slices || 16;
  891. var stacks = options.stacks || 8;
  892. var polygons = [], vertices;
  893. function vertex(theta, phi) {
  894. theta *= Math.PI * 2;
  895. phi *= Math.PI;
  896. var dir = new CSG.Vector(
  897. Math.cos(theta) * Math.sin(phi),
  898. Math.cos(phi),
  899. Math.sin(theta) * Math.sin(phi)
  900. );
  901. vertices.push(new CSG.Vertex(c.plus(dir.times(r)), dir));
  902. }
  903. for (var i = 0; i < slices; i++) {
  904. for (var j = 0; j < stacks; j++) {
  905. vertices = [];
  906. vertex(i / slices, j / stacks);
  907. if (j > 0) vertex((i + 1) / slices, j / stacks);
  908. if (j < stacks - 1) vertex((i + 1) / slices, (j + 1) / stacks);
  909. vertex(i / slices, (j + 1) / stacks);
  910. polygons.push(new CSG.Polygon(vertices));
  911. }
  912. }
  913. return CSG.fromPolygons(polygons);
  914. };
  915. /**
  916. * Construct a solid cylinder. Optional parameters are `start`, `end`,<br/>
  917. * `radius`, and `slices`, which default to `[0, -1, 0]`, `[0, 1, 0]`, `1`, and<br/>
  918. * `16`. The `slices` parameter controls the tessellation.<br/>
  919. *
  920. *@example
  921. *
  922. * var cylinder = CSG.cylinder({
  923. * start: [0, -1, 0],
  924. * end: [0, 1, 0],
  925. * radius: 1,
  926. * slices: 16
  927. * });
  928. *@memberof Cesium.CSG
  929. *@param {Object}options
  930. *@param {Array<Number>|Cesium.CSG.Vector}[options.start=[0, -1, 0]]
  931. *@param {Array<Number>|Cesium.CSG.Vector}[options.end=[0, -1, 0]]
  932. *@param {Number}[options.radius=1]
  933. *@param {Number}[options.slices=16]
  934. *@return {Cesium.CSG}
  935. */
  936. CSG.cylinder = function (options) {
  937. options = options || {};
  938. var s = new CSG.Vector(options.start || [0, -1, 0]);
  939. var e = new CSG.Vector(options.end || [0, 1, 0]);
  940. var ray = e.minus(s);
  941. var r = options.radius || 1;
  942. var slices = options.slices || 16;
  943. var axisZ = ray.unit(), isY = (Math.abs(axisZ.y) > 0.5);
  944. var axisX = new CSG.Vector(isY, !isY, 0).cross(axisZ).unit();
  945. var axisY = axisX.cross(axisZ).unit();
  946. var start = new CSG.Vertex(s, axisZ.negated());
  947. var end = new CSG.Vertex(e, axisZ.unit());
  948. var polygons = [];
  949. function point(stack, slice, normalBlend) {
  950. var angle = slice * Math.PI * 2;
  951. var out = axisX.times(Math.cos(angle)).plus(axisY.times(Math.sin(angle)));
  952. var pos = s.plus(ray.times(stack)).plus(out.times(r));
  953. var normal = out.times(1 - Math.abs(normalBlend)).plus(axisZ.times(normalBlend));
  954. return new CSG.Vertex(pos, normal);
  955. }
  956. for (var i = 0; i < slices; i++) {
  957. var t0 = i / slices, t1 = (i + 1) / slices;
  958. polygons.push(new CSG.Polygon([start, point(0, t0, -1), point(0, t1, -1)]));
  959. polygons.push(new CSG.Polygon([point(0, t1, 0), point(0, t0, 0), point(1, t0, 0), point(1, t1, 0)]));
  960. polygons.push(new CSG.Polygon([end, point(1, t1, 1), point(1, t0, 1)]));
  961. }
  962. return CSG.fromPolygons(polygons);
  963. };
  964. /**
  965. * class Vector<br/>
  966. * Represents a 3D vector.
  967. *@example
  968. *
  969. * new CSG.Vector(1, 2, 3);
  970. * new CSG.Vector([1, 2, 3]);
  971. * new CSG.Vector({ x: 1, y: 2, z: 3 });
  972. *
  973. *@memberof Cesium.CSG
  974. *
  975. *@param {Number|Array<Number>|Cesium.CSG.Vector}xOrArrayXYZOrVec
  976. *@param {Number}[y]
  977. *@param {Number}[z]
  978. *
  979. *@property {Number}x
  980. *@property {Number}y
  981. *@property {Number}z
  982. *
  983. *@constructor
  984. */
  985. CSG.Vector = function (x, y, z) {
  986. if (arguments.length == 3) {
  987. this.x = x;
  988. this.y = y;
  989. this.z = z;
  990. } else if ('x' in x) {
  991. this.x = x.x;
  992. this.y = x.y;
  993. this.z = x.z;
  994. } else {
  995. this.x = x[0];
  996. this.y = x[1];
  997. this.z = x[2];
  998. }
  999. };
  1000. CSG.Vector.prototype = {
  1001. /**
  1002. *@return {Cesium.CSG.Vector}
  1003. */
  1004. clone: function () {
  1005. return new CSG.Vector(this.x, this.y, this.z);
  1006. },
  1007. /**
  1008. *@return {Cesium.CSG.Vector}
  1009. */
  1010. negated: function () {
  1011. return new CSG.Vector(-this.x, -this.y, -this.z);
  1012. },
  1013. /**
  1014. *@param {Cesium.CSG.Vector}a
  1015. *@return {Cesium.CSG.Vector}
  1016. */
  1017. plus: function (a) {
  1018. return new CSG.Vector(this.x + a.x, this.y + a.y, this.z + a.z);
  1019. },
  1020. /**
  1021. *@param {Cesium.CSG.Vector}a
  1022. *@return {Cesium.CSG.Vector}
  1023. */
  1024. minus: function (a) {
  1025. return new CSG.Vector(this.x - a.x, this.y - a.y, this.z - a.z);
  1026. },
  1027. /**
  1028. *@param {Number}a
  1029. *@return {Cesium.CSG.Vector}
  1030. */
  1031. times: function (a) {
  1032. return new CSG.Vector(this.x * a, this.y * a, this.z * a);
  1033. },
  1034. /**
  1035. *@param {Number}a
  1036. *@return {Cesium.CSG.Vector}
  1037. */
  1038. dividedBy: function (a) {
  1039. return new CSG.Vector(this.x / a, this.y / a, this.z / a);
  1040. },
  1041. /**
  1042. *@param {Cesium.CSG.Vector}a
  1043. *@return {Cesium.CSG.Vector}
  1044. */
  1045. dot: function (a) {
  1046. return this.x * a.x + this.y * a.y + this.z * a.z;
  1047. },
  1048. /**
  1049. *@param {Cesium.CSG.Vector}a
  1050. *@param {Number}t
  1051. *@return {Cesium.CSG.Vector}
  1052. */
  1053. lerp: function (a, t) {
  1054. return this.plus(a.minus(this).times(t));
  1055. },
  1056. /**
  1057. *@return {Number}
  1058. */
  1059. length: function () {
  1060. return Math.sqrt(this.dot(this));
  1061. },
  1062. /**
  1063. *@return {Cesium.CSG.Vector}
  1064. */
  1065. unit: function () {
  1066. return this.dividedBy(this.length());
  1067. },
  1068. /**
  1069. *@param {Cesium.CSG.Vector}a
  1070. *@return {Cesium.CSG.Vector}
  1071. */
  1072. cross: function (a) {
  1073. return new CSG.Vector(
  1074. this.y * a.z - this.z * a.y,
  1075. this.z * a.x - this.x * a.z,
  1076. this.x * a.y - this.y * a.x
  1077. );
  1078. }
  1079. };
  1080. /**
  1081. * class Vertex<br/>
  1082. *<br/>
  1083. * Represents a vertex of a polygon. Use your own vertex class instead of this<br/>
  1084. * one to provide additional features like texture coordinates and vertex<br/>
  1085. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,<br/>
  1086. * `flip()`, and `interpolate()` methods that behave analogous to the ones<br/>
  1087. * defined by `CSG.Vertex`. This class provides `normal` so convenience<br/>
  1088. * functions like `CSG.sphere()` can return a smooth vertex normal, but `normal`<br/>
  1089. * is not used anywhere else.<br/>
  1090. *
  1091. *@memberof Cesium.CSG
  1092. *@param {Array<Number>|Cesium.CSG.Vector}pos
  1093. *@param {Array<Number>|Cesium.CSG.Vector}normal
  1094. *
  1095. *@property {Cesium.CSG.Vector}pos
  1096. *@property {Cesium.CSG.Vector}normal
  1097. *
  1098. *@constructor
  1099. */
  1100. CSG.Vertex = function (pos, normal) {
  1101. this.pos = new CSG.Vector(pos);
  1102. this.normal = new CSG.Vector(normal);
  1103. };
  1104. CSG.Vertex.prototype = {
  1105. /**
  1106. *@return {Cesium.CSG.Vertex}
  1107. */
  1108. clone: function () {
  1109. return new CSG.Vertex(this.pos.clone(), this.normal.clone());
  1110. },
  1111. /**
  1112. * Invert all orientation-specific data (e.g. vertex normal). Called when the<br/>
  1113. * orientation of a polygon is flipped.
  1114. *
  1115. */
  1116. flip: function () {
  1117. this.normal = this.normal.negated();
  1118. },
  1119. /**
  1120. * Create a new vertex between this vertex and `other` by linearly<br/>
  1121. * interpolating all properties using a parameter of `t`. Subclasses should<br/>
  1122. * override this to interpolate additional properties.
  1123. *
  1124. *@param {Cesium.CSG.Vertex}
  1125. *@param {Number}
  1126. *@return {Cesium.CSG.Vertex}
  1127. */
  1128. interpolate: function (other, t) {
  1129. return new CSG.Vertex(
  1130. this.pos.lerp(other.pos, t),
  1131. this.normal.lerp(other.normal, t)
  1132. );
  1133. }
  1134. };
  1135. /**
  1136. * class Plane</br/>
  1137. *
  1138. * Represents a plane in 3D space.
  1139. *
  1140. *@memberof Cesium.CSG
  1141. *@param {Array<Number>|Cesium.CSG.Vector}normal
  1142. *@param {Number}w
  1143. *
  1144. *@property {Cesium.CSG.Vector}normal
  1145. *@property {Number}w
  1146. *
  1147. *@constructor
  1148. */
  1149. CSG.Plane = function (normal, w) {
  1150. this.normal = normal;
  1151. this.w = w;
  1152. };
  1153. /**
  1154. * `CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a</br/>
  1155. * point is on the plane.
  1156. */
  1157. CSG.Plane.EPSILON = 1e-5;
  1158. /**
  1159. *
  1160. *
  1161. *@param {Cesium.CSG.Vector}a
  1162. *@param {Cesium.CSG.Vector}b
  1163. *@param {Cesium.CSG.Vector}c
  1164. */
  1165. CSG.Plane.fromPoints = function (a, b, c) {
  1166. var n = b.minus(a).cross(c.minus(a)).unit();
  1167. return new CSG.Plane(n, n.dot(a));
  1168. };
  1169. CSG.Plane.prototype = {
  1170. /**
  1171. *@return {Cesium.CSG.Plane}
  1172. */
  1173. clone: function () {
  1174. return new CSG.Plane(this.normal.clone(), this.w);
  1175. },
  1176. /**
  1177. *
  1178. */
  1179. flip: function () {
  1180. this.normal = this.normal.negated();
  1181. this.w = -this.w;
  1182. },
  1183. /**
  1184. * Split `polygon` by this plane if needed, then put the polygon or polygon<br/>
  1185. * fragments in the appropriate lists. Coplanar polygons go into either<br/>
  1186. * `coplanarFront` or `coplanarBack` depending on their orientation with<br/>
  1187. * respect to this plane. Polygons in front or in back of this plane go into<br/>
  1188. * either `front` or `back`.
  1189. *
  1190. *@param {Cesium.CSG.Polygon}polygon
  1191. *@param {Array<Cesium.CSG.Polygon>}coplanarFront
  1192. *@param {Array<Cesium.CSG.Polygon>}coplanarBack
  1193. *@param {Array<Cesium.CSG.Polygon>}front
  1194. *@param {Array<Cesium.CSG.Polygon>}back
  1195. */
  1196. splitPolygon: function (polygon, coplanarFront, coplanarBack, front, back) {
  1197. var COPLANAR = 0;
  1198. var FRONT = 1;
  1199. var BACK = 2;
  1200. var SPANNING = 3;
  1201. // Classify each point as well as the entire polygon into one of the above
  1202. // four classes.
  1203. var polygonType = 0;
  1204. var types = [];
  1205. for (var i = 0; i < polygon.vertices.length; i++) {
  1206. var t = this.normal.dot(polygon.vertices[i].pos) - this.w;
  1207. var type = (t < -CSG.Plane.EPSILON) ? BACK : (t > CSG.Plane.EPSILON) ? FRONT : COPLANAR;
  1208. polygonType |= type;
  1209. types.push(type);
  1210. }
  1211. // Put the polygon in the correct list, splitting it when necessary.
  1212. switch (polygonType) {
  1213. case COPLANAR:
  1214. (this.normal.dot(polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  1215. break;
  1216. case FRONT:
  1217. front.push(polygon);
  1218. break;
  1219. case BACK:
  1220. back.push(polygon);
  1221. break;
  1222. case SPANNING:
  1223. var f = [], b = [];
  1224. for (var i = 0; i < polygon.vertices.length; i++) {
  1225. var j = (i + 1) % polygon.vertices.length;
  1226. var ti = types[i], tj = types[j];
  1227. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  1228. if (ti != BACK) f.push(vi);
  1229. if (ti != FRONT) b.push(ti != BACK ? vi.clone() : vi);
  1230. if ((ti | tj) == SPANNING) {
  1231. var t = (this.w - this.normal.dot(vi.pos)) / this.normal.dot(vj.pos.minus(vi.pos));
  1232. var v = vi.interpolate(vj, t);
  1233. f.push(v);
  1234. b.push(v.clone());
  1235. }
  1236. }
  1237. if (f.length >= 3) front.push(new CSG.Polygon(f, polygon.shared));
  1238. if (b.length >= 3) back.push(new CSG.Polygon(b, polygon.shared));
  1239. break;
  1240. }
  1241. }
  1242. };
  1243. /**
  1244. * class Polygon<br/>
  1245. *<br/>
  1246. * Represents a convex polygon. The vertices used to initialize a polygon must<br/>
  1247. * be coplanar and form a convex loop. They do not have to be `CSG.Vertex`<br/>
  1248. * instances but they must behave similarly (duck typing can be used for<br/>
  1249. * customization).<br/>
  1250. * <br/>
  1251. * Each convex polygon has a `shared` property, which is shared between all<br/>
  1252. * polygons that are clones of each other or were split from the same polygon.<br/>
  1253. * This can be used to define per-polygon properties (such as surface color).<br/>
  1254. *
  1255. *@memberof Cesium.CSG
  1256. *@param {Array<Cesium.CSG.Vertex>}vertices
  1257. *@param {Boolean}shared
  1258. *
  1259. *@property {Array<Cesium.CSG.Vertex>}vertices
  1260. *@property {Boolean}shared
  1261. *@property {Cesium.CSG.Plane}plane
  1262. *@constructor
  1263. */
  1264. CSG.Polygon = function (vertices, shared) {
  1265. this.vertices = vertices;
  1266. this.shared = shared;
  1267. this.plane = CSG.Plane.fromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  1268. };
  1269. CSG.Polygon.prototype = {
  1270. /**
  1271. *@return {Cesium.CSG.Polygon}
  1272. */
  1273. clone: function () {
  1274. var vertices = this.vertices.map(function (v) { return v.clone(); });
  1275. return new CSG.Polygon(vertices, this.shared);
  1276. },
  1277. /**
  1278. *
  1279. */
  1280. flip: function () {
  1281. this.vertices.reverse().map(function (v) { v.flip(); });
  1282. this.plane.flip();
  1283. }
  1284. };
  1285. /**
  1286. *
  1287. * class Node<br/>
  1288. *<br/>
  1289. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons<br/>
  1290. * by picking a polygon to split along. That polygon (and all other coplanar<br/>
  1291. * polygons) are added directly to that node and the other polygons are added to<br/>
  1292. * the front and/or back subtrees. This is not a leafy BSP tree since there is<br/>
  1293. * no distinction between internal and leaf nodes.<br/>
  1294. *
  1295. *@memberof Cesium.CSG
  1296. *@param {Array<Cesium.CSG.Polygon>}polygons
  1297. *
  1298. *@property {Array<Cesium.CSG.Polygon>}polygons
  1299. *@property {Cesium.CSG.Plane}plane
  1300. *@property {Cesium.CSG.Plane}front
  1301. *@property {Cesium.CSG.Plane}back
  1302. *@constructor
  1303. */
  1304. CSG.Node = function (polygons) {
  1305. this.plane = null;
  1306. this.front = null;
  1307. this.back = null;
  1308. this.polygons = [];
  1309. if (polygons) this.build(polygons);
  1310. };
  1311. CSG.Node.prototype = {
  1312. /**
  1313. *@return {Cesium.CSG.Node}
  1314. */
  1315. clone: function () {
  1316. var node = new CSG.Node();
  1317. node.plane = this.plane && this.plane.clone();
  1318. node.front = this.front && this.front.clone();
  1319. node.back = this.back && this.back.clone();
  1320. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  1321. return node;
  1322. },
  1323. /**
  1324. * Convert solid space to empty space and empty space to solid space.
  1325. */
  1326. invert: function () {
  1327. for (var i = 0; i < this.polygons.length; i++) {
  1328. this.polygons[i].flip();
  1329. }
  1330. this.plane.flip();
  1331. if (this.front) this.front.invert();
  1332. if (this.back) this.back.invert();
  1333. var temp = this.front;
  1334. this.front = this.back;
  1335. this.back = temp;
  1336. },
  1337. /**
  1338. * Recursively remove all polygons in `polygons` that are inside this BSP<br/>
  1339. * tree.
  1340. *@param {Array<Cesium.CSG.Polygon>}polygons
  1341. *@return {Array<Cesium.CSG.Polygon>}
  1342. */
  1343. clipPolygons: function (polygons) {
  1344. if (!this.plane) return polygons.slice();
  1345. var front = [], back = [];
  1346. for (var i = 0; i < polygons.length; i++) {
  1347. this.plane.splitPolygon(polygons[i], front, back, front, back);
  1348. }
  1349. if (this.front) front = this.front.clipPolygons(front);
  1350. if (this.back) back = this.back.clipPolygons(back);
  1351. else back = [];
  1352. return front.concat(back);
  1353. },
  1354. /**
  1355. * Remove all polygons in this BSP tree that are inside the other BSP tree<br/>
  1356. * `bsp`.
  1357. */
  1358. clipTo: function (bsp) {
  1359. this.polygons = bsp.clipPolygons(this.polygons);
  1360. if (this.front) this.front.clipTo(bsp);
  1361. if (this.back) this.back.clipTo(bsp);
  1362. },
  1363. /**
  1364. * Return a list of all polygons in this BSP tree.
  1365. *@return {Array<Cesium.CSG.Polygon>}
  1366. */
  1367. allPolygons: function () {
  1368. var polygons = this.polygons.slice();
  1369. if (this.front) polygons = polygons.concat(this.front.allPolygons());
  1370. if (this.back) polygons = polygons.concat(this.back.allPolygons());
  1371. return polygons;
  1372. },
  1373. /**
  1374. * Build a BSP tree out of `polygons`. When called on an existing tree, the<br/>
  1375. * new polygons are filtered down to the bottom of the tree and become new<br/>
  1376. * nodes there. Each set of polygons is partitioned using the first polygon<br/>
  1377. * (no heuristic is used to pick a good split).<br/>
  1378. */
  1379. build: function (polygons) {
  1380. if (!polygons.length) return;
  1381. if (!this.plane) this.plane = polygons[0].plane.clone();
  1382. var front = [], back = [];
  1383. for (var i = 0; i < polygons.length; i++) {
  1384. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  1385. }
  1386. if (front.length) {
  1387. if (!this.front) this.front = new CSG.Node();
  1388. this.front.build(front);
  1389. }
  1390. if (back.length) {
  1391. if (!this.back) this.back = new CSG.Node();
  1392. this.back.build(back);
  1393. }
  1394. }
  1395. };
  1396. /**
  1397. *@param {Cesium.Geometry}
  1398. *@param {Cesium.Cartesian3}[offset]
  1399. *@return {CSG}
  1400. */
  1401. CSG.toCSG = function (geometry, offset) {
  1402. if (!offset) {
  1403. offset = { x: 0, y: 0, z: 0 };
  1404. }
  1405. if (!geometry.attributes.normal) {
  1406. geometry = Cesium.GeometryPipeline.computeNormal(geometry);
  1407. }
  1408. if (geometry.primitiveType !== Cesium.PrimitiveType.TRIANGLES) {
  1409. throw new Error("暂不支持此类几何体");
  1410. }
  1411. if (!CSG) {
  1412. throw new Error('CSG 库未加载。请从 https://github.com/evanw/csg.js 获取');
  1413. }
  1414. var faceCount = geometry.indices.length / 3;
  1415. var polygons = [], vertices = [];
  1416. var positions = geometry.attributes.position.values;
  1417. var normals = geometry.attributes.normal.values;
  1418. var normalIdx = 0, positionIdx = 0;
  1419. for (var i = 0; i < geometry.indices.length ; i += 3) {
  1420. vertices = [];
  1421. var idx1 = geometry.indices[i];
  1422. var idx2 = geometry.indices[i + 1];
  1423. var idx3 = geometry.indices[i + 2];
  1424. positionIdx = idx1 * 3;
  1425. normalIdx = idx1 * 3;
  1426. vertices.push(new CSG.Vertex(
  1427. [positions[positionIdx++] + offset.x, positions[positionIdx++] + offset.y, positions[positionIdx++] + offset.z],
  1428. [normals[normalIdx++], normals[normalIdx++], normals[normalIdx++]]
  1429. ));
  1430. positionIdx = idx2 * 3;
  1431. normalIdx = idx2 * 3;
  1432. vertices.push(new CSG.Vertex(
  1433. [positions[positionIdx++] + offset.x, positions[positionIdx++] + offset.y, positions[positionIdx++] + offset.z],
  1434. [normals[normalIdx++], normals[normalIdx++], normals[normalIdx++]]
  1435. ));
  1436. positionIdx = idx3 * 3;
  1437. normalIdx = idx3 * 3;
  1438. vertices.push(new CSG.Vertex(
  1439. [positions[positionIdx++] + offset.x, positions[positionIdx++] + offset.y, positions[positionIdx++] + offset.z],
  1440. [normals[normalIdx++], normals[normalIdx++], normals[normalIdx++]]
  1441. ));
  1442. polygons.push(new CSG.Polygon(vertices));
  1443. }
  1444. return CSG.fromPolygons(polygons);
  1445. }
  1446. /**
  1447. *@param {CSG}csg_model
  1448. *@return {Cesium.Geometry}
  1449. */
  1450. CSG.fromCSG = function (csg_model) {
  1451. var i, j, vertices,
  1452. polygons = csg_model.toPolygons();
  1453. if (!CSG) {
  1454. throw new Error('CSG 库未加载。请从 https://github.com/evanw/csg.js 获取');
  1455. }
  1456. var positions = [];
  1457. var normals = [];
  1458. var indices = [];
  1459. for (i = 0; i < polygons.length; i++) {
  1460. // Vertices
  1461. vertices = [];
  1462. for (j = 0; j < polygons[i].vertices.length; j++) {
  1463. vertices.push(this.getGeometryVertice(positions, normals, polygons[i].vertices[j].pos, polygons[i].plane.normal));
  1464. }
  1465. if (vertices[0] === vertices[vertices.length - 1]) {
  1466. vertices.pop();
  1467. }
  1468. for (var j = 2; j < vertices.length; j++) {
  1469. indices.push(vertices[0], vertices[j - 1], vertices[j]);
  1470. }
  1471. }
  1472. positions = new Float32Array(positions);
  1473. normals = new Float32Array(normals);
  1474. indices = new Int32Array(indices);
  1475. var attributes = {};
  1476. attributes.position = new Cesium.GeometryAttribute({
  1477. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  1478. componentsPerAttribute: 3,
  1479. values: positions
  1480. });
  1481. attributes.normal = new Cesium.GeometryAttribute({
  1482. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  1483. componentsPerAttribute: 3,
  1484. values: normals
  1485. });
  1486. var cesGeometry = new Cesium.Geometry({
  1487. attributes: attributes,
  1488. indices: indices,
  1489. primitiveType: Cesium.PrimitiveType.TRIANGLES
  1490. });
  1491. return cesGeometry;
  1492. },
  1493. /**
  1494. *@param {Array<Number>}positions
  1495. *@param {Array<Number>}normals
  1496. *@param {Cesium.CSG.Vector}vertice_position
  1497. *@param {Cesium.CSG.Vector}plane_normal
  1498. *@return {Number}
  1499. *@private
  1500. */
  1501. CSG.getGeometryVertice = function (positions, normals, vertice_position, plane_normal) {
  1502. var i, idx = 0;
  1503. for (i = 0; i < positions.length; i += 3) {
  1504. if (positions[i] === vertice_position.x
  1505. && positions[i + 1] === vertice_position.y
  1506. && positions[i + 2] === vertice_position.z) {
  1507. // Vertice already exists
  1508. return idx;
  1509. }
  1510. idx++;
  1511. };
  1512. positions.push(vertice_position.x, vertice_position.y, vertice_position.z);
  1513. normals.push(plane_normal.x, plane_normal.y, plane_normal.z);
  1514. return idx;
  1515. }
  1516. return CSG;
  1517. });
  1518. define('Util/defineProperty',[],function () {
  1519. /**
  1520. *定义属性并监听属性变化事件,属性值的数据类型可以实现equals接口用于进行更进一步的比较
  1521. *@param {Object}owner
  1522. *@param {String}name
  1523. *@param {Any}defaultVal
  1524. *@param {Function}onChanged
  1525. *@memberof Cesium
  1526. */
  1527. function defineProperty(owner, name, defaultVal, onChanged) {
  1528. owner["_" + name] = defaultVal;
  1529. var value = {
  1530. get: function () {
  1531. return this["_" + name];
  1532. },
  1533. set: function (val) {
  1534. var changed = val != this["_" + name];
  1535. if (this["_" + name] && this["_" + name].equals && val) {
  1536. changed = this["_" + name].equals(val);
  1537. }
  1538. this["_" + name] = val;
  1539. if (typeof onChanged == 'function' && changed) {
  1540. onChanged(changed, owner);
  1541. }
  1542. }
  1543. };
  1544. var properties = {};
  1545. properties[name] = value;
  1546. Object.defineProperties(owner, properties)
  1547. }
  1548. return defineProperty;
  1549. });
  1550. define('Core/MeshMaterial',['Util/defineProperty'], function (defineProperty) {
  1551. var defaultValue = Cesium.defaultValue;
  1552. /**
  1553. *
  1554. *@param {Object}options
  1555. *@param {Object}[options.uniforms]
  1556. *@param {Object}[options.uniformStateUsed]
  1557. *@param {Boolean}[options.translucent]
  1558. *@param {Boolean}[options.wireframe]
  1559. *@param {Enum}[options.side=Cesium.MeshMaterial.Sides.DOUBLE]
  1560. *@param {String|Cesium.Color}[options.defaultColor=Cesium.Color.WHITE]
  1561. *@param {String}[options.vertexShader]
  1562. *@param {String}[options.fragmentShader]
  1563. *
  1564. *
  1565. *@property {Object}uniforms
  1566. *@property {Object}uniformStateUsed
  1567. *@property {Boolean}translucent
  1568. *@property {Boolean}wireframe
  1569. *@property {Enum}side
  1570. *@property {String|Cesium.Color}defaultColor
  1571. *@property {String}vertexShader
  1572. *@property {String}fragmentShader
  1573. *
  1574. *@constructor
  1575. *@memberof Cesium
  1576. */
  1577. function MeshMaterial(options) {
  1578. options = defaultValue(options, {});
  1579. options.uniforms = defaultValue(options.uniforms, {});
  1580. var that = this;
  1581. this._uuid = Cesium.createGuid();
  1582. function initUniform(srcUniforms) {
  1583. var _uniforms = {};
  1584. for (var i in srcUniforms) {
  1585. if (srcUniforms.hasOwnProperty(i) && Cesium.defined(srcUniforms[i])) {
  1586. var item = srcUniforms[i];
  1587. var val = {};
  1588. val.needsUpdate = true;
  1589. if (Array.isArray(item) && item.length >= 3 && item.length <= 4 && typeof item[0] === 'number') {
  1590. srcUniforms[i] = new Cesium.Color(srcUniforms[i][0], srcUniforms[i][1], srcUniforms[i][2], srcUniforms[i][3]);
  1591. } else if (Cesium.defined(item.value)) {
  1592. for (var n in item) {
  1593. if (item.hasOwnProperty(n)) {
  1594. val[n] = item[n];
  1595. }
  1596. }
  1597. }
  1598. if (srcUniforms[i].hasOwnProperty("uuid")) {
  1599. defineProperty(val, "uuid", srcUniforms[i].uuid, function (changed, owner) {
  1600. owner.needsUpdate = changed;
  1601. });
  1602. } else {
  1603. defineProperty(val, "uuid", Cesium.createGuid(), function (changed, owner) {
  1604. owner.needsUpdate = changed;
  1605. });
  1606. }
  1607. if (srcUniforms[i].hasOwnProperty("value")) {
  1608. defineProperty(val, "value", srcUniforms[i].value, function (changed, owner) {
  1609. owner.needsUpdate = changed;
  1610. });
  1611. } else {
  1612. defineProperty(val, "value", srcUniforms[i], function (changed, owner) {
  1613. owner.needsUpdate = changed;
  1614. });
  1615. }
  1616. _uniforms[i] = val;
  1617. //defineProperty(_uniforms, i, val, function (changed) {
  1618. // that.needsUpdate = changed;
  1619. //});
  1620. }
  1621. }
  1622. return _uniforms;
  1623. }
  1624. this._defaultColor = defaultValue(options.defaultColor, Cesium.Color.WHITE);
  1625. if (typeof this._defaultColor == 'string') {
  1626. this._defaultColor = Cesium.Color.fromCssColorString(this._defaultColor);
  1627. }
  1628. this._pickedColor = defaultValue(options.pickedColor, Cesium.Color.YELLOW);
  1629. if (typeof this._pickedColor == 'string') {
  1630. this._pickedColor = Cesium.Color.fromCssColorString(this._pickedColor);
  1631. }
  1632. this._picked = defaultValue(options.picked, 0);
  1633. options.uniforms.pickedColor = this._pickedColor;
  1634. options.uniforms.defaultColor = this._defaultColor;
  1635. options.uniforms.picked = this._picked;
  1636. this._uniforms = initUniform(options.uniforms);
  1637. function onPropertyChanged(changed) {
  1638. that.needsUpdate = changed;
  1639. }
  1640. defineProperty(this, "translucent", defaultValue(options.translucent, false), onPropertyChanged);
  1641. defineProperty(this, "wireframe", defaultValue(options.wireframe, false), onPropertyChanged);
  1642. defineProperty(this, "side", defaultValue(options.side, MeshMaterial.Sides.DOUBLE), onPropertyChanged);
  1643. defineProperty(this, "uniformStateUsed", defaultValue(options.uniformStateUsed, [{
  1644. uniformStateName: "model",
  1645. glslVarName: "modelMatrix"
  1646. }]), onPropertyChanged);
  1647. defineProperty(this, "uniforms", this._uniforms, function () {
  1648. that._uniforms = initUniform(that._uniforms);
  1649. });
  1650. this._vertexShader = '//#inner\n void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n}';
  1651. this._fragmentShader = '//#inner' + this._uuid + '\n uniform float picked;\n uniform vec4 pickedColor;\n uniform vec4 defaultColor;\n void main() {\ngl_FragColor = defaultColor;\n if(picked!=0.0){\ngl_FragColor = pickedColor;}}';// vec4( ' + this._defaultColor.red + ',' + this._defaultColor.green + ',' + this._defaultColor.blue + ',' + this._defaultColor.alpha + ');\n}';
  1652. defineProperty(this, "vertexShader", defaultValue(options.vertexShader, this._vertexShader), onPropertyChanged);
  1653. defineProperty(this, "fragmentShader", defaultValue(options.fragmentShader, this._fragmentShader), onPropertyChanged);
  1654. this.depthTest =defaultValue(options.depthTest, true);
  1655. this.depthMask = defaultValue(options.depthMask, true);
  1656. this.blending = defaultValue(options.blending, true);
  1657. this.needsUpdate = true;
  1658. }
  1659. Object.defineProperties(MeshMaterial.prototype, {
  1660. uuid: {
  1661. get: function () {
  1662. return this._uuid;
  1663. }
  1664. },
  1665. defaultColor: {
  1666. set: function (val) {
  1667. if (typeof val == 'string') {
  1668. val = Cesium.Color.fromCssColorString(val);
  1669. }
  1670. Cesium.Color.clone(val, this._defaultColor);
  1671. },
  1672. get: function () {
  1673. return this._defaultColor;
  1674. }
  1675. }
  1676. });
  1677. /**
  1678. *
  1679. *@memberof Cesium.MeshMaterial
  1680. *@property {Enum}FRONT
  1681. *@property {Enum}BACK
  1682. *@property {Enum}DOUBLE
  1683. */
  1684. MeshMaterial.Sides = {
  1685. FRONT: 3,
  1686. BACK: 1,
  1687. DOUBLE: 2
  1688. }
  1689. return MeshMaterial;
  1690. });
  1691. define('Core/GeometryUtils',[
  1692. 'Util/CSG'
  1693. ], function (CSG) {
  1694. /**
  1695. *
  1696. *@constructor
  1697. *@memberof Cesium
  1698. */
  1699. function GeometryUtils() {
  1700. }
  1701. function getAttrs(geo) {
  1702. var attrNames = [];
  1703. for (var name in geo.attributes) {
  1704. if (geo.attributes.hasOwnProperty(name) && geo.attributes[name]) {
  1705. attrNames.push(name);
  1706. }
  1707. }
  1708. return attrNames
  1709. }
  1710. var scratchPosition = new Cesium.Cartesian3();
  1711. var scratchQuaternion = new Cesium.Quaternion();
  1712. var scratchMatrix4 = new Cesium.Matrix4();
  1713. var scratchRotation = new Cesium.Matrix3();
  1714. /**
  1715. *绕x轴旋转修改顶点坐标
  1716. *@param {Cesium.Geometry}geometry
  1717. *@param {Number}angle 弧度
  1718. */
  1719. GeometryUtils.rotateX = function (geometry, angle) {
  1720. var positions = geometry.attributes.position.values;
  1721. Cesium.Matrix3.fromRotationX(angle, scratchRotation);
  1722. Cesium.Matrix4.fromRotationTranslation(scratchRotation, Cesium.Cartesian3.ZERO, scratchMatrix4);
  1723. for (var i = 0; i < positions.length; i += 3) {
  1724. scratchPosition.x = positions[i];
  1725. scratchPosition.y = positions[i + 1];
  1726. scratchPosition.z = positions[i + 2];
  1727. Cesium.Matrix4.multiplyByPoint(scratchMatrix4, scratchPosition, scratchPosition);
  1728. positions[i] = scratchPosition.x;
  1729. positions[i + 1] = scratchPosition.y;
  1730. positions[i + 2] = scratchPosition.z;
  1731. }
  1732. }
  1733. /**
  1734. *绕y轴旋转修改顶点坐标
  1735. *@param {Cesium.Geometry}geometry
  1736. *@param {Number}angle 弧度
  1737. */
  1738. GeometryUtils.rotateY = function (geometry, angle) {
  1739. var positions = geometry.attributes.position.values;
  1740. Cesium.Matrix3.fromRotationY(angle, scratchRotation);
  1741. Cesium.Matrix4.fromRotationTranslation(scratchRotation, Cesium.Cartesian3.ZERO, scratchMatrix4);
  1742. for (var i = 0; i < positions.length; i += 3) {
  1743. scratchPosition.x = positions[i];
  1744. scratchPosition.y = positions[i + 1];
  1745. scratchPosition.z = positions[i + 2];
  1746. Cesium.Matrix4.multiplyByPoint(scratchMatrix4, scratchPosition, scratchPosition);
  1747. positions[i] = scratchPosition.x;
  1748. positions[i + 1] = scratchPosition.y;
  1749. positions[i + 2] = scratchPosition.z;
  1750. }
  1751. }
  1752. /**
  1753. *绕z轴旋转修改顶点坐标
  1754. *@param {Cesium.Geometry}geometry
  1755. *@param {Number}angle 弧度
  1756. */
  1757. GeometryUtils.rotateZ = function (geometry, angle) {
  1758. var positions = geometry.attributes.position.values;
  1759. Cesium.Matrix3.fromRotationZ(angle, scratchRotation);
  1760. Cesium.Matrix4.fromRotationTranslation(scratchRotation, Cesium.Cartesian3.ZERO, scratchMatrix4);
  1761. for (var i = 0; i < positions.length; i += 3) {
  1762. scratchPosition.x = positions[i];
  1763. scratchPosition.y = positions[i + 1];
  1764. scratchPosition.z = positions[i + 2];
  1765. Cesium.Matrix4.multiplyByPoint(scratchMatrix4, scratchPosition, scratchPosition);
  1766. positions[i] = scratchPosition.x;
  1767. positions[i + 1] = scratchPosition.y;
  1768. positions[i + 2] = scratchPosition.z;
  1769. }
  1770. }
  1771. /**
  1772. *
  1773. *@param {Cesium.Geometry}geometry
  1774. */
  1775. GeometryUtils.computeVertexNormals = function (geometry) {
  1776. var indices = geometry.indices;
  1777. var attributes = geometry.attributes;
  1778. var il = indices.length;
  1779. if (attributes.position) {
  1780. var positions = attributes.position.values;
  1781. if (attributes.normal === undefined) {
  1782. attributes.normal = new Cesium.GeometryAttribute({
  1783. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  1784. componentsPerAttribute: 3,
  1785. values: new Float32Array(positions.length)
  1786. })
  1787. } else {
  1788. // reset existing normals to zero
  1789. var array = attributes.normal.values;
  1790. for (var i = 0; i < il; i++) {
  1791. array[i] = 0;
  1792. }
  1793. }
  1794. var normals = attributes.normal.values;
  1795. var vA, vB, vC;
  1796. var pA = new Cesium.Cartesian3(), pB = new Cesium.Cartesian3(), pC = new Cesium.Cartesian3();
  1797. var cb = new Cesium.Cartesian3(), ab = new Cesium.Cartesian3();
  1798. for (var i = 0; i < il; i += 3) {
  1799. vA = indices[i + 0] * 3;
  1800. vB = indices[i + 1] * 3;
  1801. vC = indices[i + 2] * 3;
  1802. Cesium.Cartesian3.fromArray(positions, vA, pA);
  1803. Cesium.Cartesian3.fromArray(positions, vB, pB);
  1804. Cesium.Cartesian3.fromArray(positions, vC, pC);
  1805. Cesium.Cartesian3.subtract(pC, pB, cb);
  1806. Cesium.Cartesian3.subtract(pA, pB, ab);
  1807. Cesium.Cartesian3.cross(cb, ab, cb);
  1808. normals[vA] += cb.x;
  1809. normals[vA + 1] += cb.y;
  1810. normals[vA + 2] += cb.z;
  1811. normals[vB] += cb.x;
  1812. normals[vB + 1] += cb.y;
  1813. normals[vB + 2] += cb.z;
  1814. normals[vC] += cb.x;
  1815. normals[vC + 1] += cb.y;
  1816. normals[vC + 2] += cb.z;
  1817. }
  1818. normalizeNormals(geometry);
  1819. attributes.normal.needsUpdate = true;
  1820. }
  1821. return geometry;
  1822. }
  1823. function normalizeNormals(geometry) {
  1824. var normals = geometry.attributes.normal.values;
  1825. var x, y, z, n;
  1826. for (var i = 0; i < normals.length; i += 3) {
  1827. x = normals[i];
  1828. y = normals[i + 1];
  1829. z = normals[i + 2];
  1830. n = 1.0 / Math.sqrt(x * x + y * y + z * z);
  1831. normals[i] = x * n;
  1832. normals[i + 1] = y * n;
  1833. normals[i + 2] = z * n;
  1834. }
  1835. }
  1836. /**
  1837. *合并两个或两个以上图形类型primitiveType属性数量名称以及属性值的类型GeometryAttribute的componentDatatypecomponentsPerAttribute等都一致的几何体
  1838. *@param {Array<Cesium.Geometry>}geometries
  1839. *@return {Cesium.Geometry}
  1840. */
  1841. GeometryUtils.mergeGeometries = function (geometries) {
  1842. if (!geometries || !geometries.length) {
  1843. throw new Error("缺少geometries参数");
  1844. }
  1845. if (geometries.length == 1) {
  1846. return geometries[0];
  1847. }
  1848. var geometriesAttrs = [];
  1849. var lengthChanged = false;
  1850. var primitiveTypeChanged = false;
  1851. var primitiveType = geometries[0].primitiveType;
  1852. for (var i = 0; i < geometries.length; i++) {
  1853. geometriesAttrs[i] = getAttrs(geometries[i]);
  1854. if (i > 0) {
  1855. if (primitiveType != geometries[i].primitiveType) {
  1856. primitiveTypeChanged = true;
  1857. break;
  1858. }
  1859. var lastGeoAttrs = geometriesAttrs[i - 1];
  1860. lengthChanged = lastGeoAttrs.length != geometriesAttrs[i].length;
  1861. if (!lengthChanged) {
  1862. for (var j = 0; j < lastGeoAttrs.length; j++) {
  1863. if (lastGeoAttrs[j] != geometriesAttrs[i][j]) {
  1864. lengthChanged = true;
  1865. break;
  1866. }
  1867. }
  1868. }
  1869. }
  1870. primitiveType = geometries[i].primitiveType;
  1871. if (lengthChanged || primitiveTypeChanged) {
  1872. break;
  1873. }
  1874. }
  1875. if (primitiveTypeChanged) {
  1876. throw new Error("待合并的几何体中primitiveType属性不完全一致");
  1877. }
  1878. if (lengthChanged) {
  1879. throw new Error("待合并的几何体中属性数量和和名称不完全一致");
  1880. }
  1881. var newAttrs = {};
  1882. var attrNames = geometriesAttrs[0];
  1883. for (var i = 0; i < attrNames.length; i++) {
  1884. var attrName = attrNames[i];
  1885. var geometry = geometries[0];
  1886. newAttrs[attrName] = {};
  1887. //newAttrs[attrName] = Cesium.clone(geometry.attributes[attrName]);
  1888. for (var n in geometry.attributes[attrName]) {
  1889. if (geometry.attributes[attrName].hasOwnProperty(n)) {
  1890. newAttrs[attrName][n] = geometry.attributes[attrName][n];
  1891. }
  1892. }
  1893. var values = Array.from(newAttrs[attrName].values);
  1894. for (var j = 1; j < geometries.length; j++) {
  1895. geometry = geometries[j];
  1896. for (var vi = 0; vi < geometry.attributes[attrName].values.length; vi++) {
  1897. values.push(geometry.attributes[attrName].values[vi]);
  1898. }
  1899. }
  1900. newAttrs[attrName].values = new newAttrs[attrName].values.constructor(values);
  1901. }
  1902. var indices = [];
  1903. var currIndex = 0;
  1904. for (var j = 0; j < geometries.length; j++) {
  1905. var geometry = geometries[0];
  1906. for (var i = 0; i < geometry.indices.length; i++) {
  1907. indices.push(geometry.indices[i] + currIndex);
  1908. }
  1909. currIndex += geometry.attributes.position.values.length / 3;
  1910. }
  1911. var bs = Cesium.BoundingSphere.fromVertices(newAttrs.position.values);
  1912. var geo = new Cesium.Geometry({
  1913. attributes: newAttrs,
  1914. indices: new Int32Array(indices),
  1915. primitiveType: geometries[0].primitiveType,
  1916. boundingSphere: bs
  1917. });
  1918. return geo;
  1919. }
  1920. var scratchOffset = new Cesium.Cartesian3();
  1921. /**
  1922. *
  1923. *@param {Cesium.Geometry}geometry
  1924. *@param {Cesium.Cartesian3}offset
  1925. */
  1926. GeometryUtils.translate = function (geometry, offset) {
  1927. if (Array.isArray(offset)) {
  1928. scratchOffset.x = offset[0];
  1929. scratchOffset.y = offset[1];
  1930. scratchOffset.z = offset[2];
  1931. } else {
  1932. Cesium.Cartesian3.clone(offset, scratchOffset);
  1933. }
  1934. for (var i = 0; i < geometry.attributes.position.values.length; i += 3) {
  1935. geometry.attributes.position.values[i] += scratchOffset.x;
  1936. geometry.attributes.position.values[i + 1] += scratchOffset.y;
  1937. geometry.attributes.position.values[i + 2] += scratchOffset.z;
  1938. }
  1939. //if (geometry.attributes.normal) {
  1940. // Cesium.GeometryPipeline.computeNormal(geometry);
  1941. //}
  1942. }
  1943. /**
  1944. *
  1945. *@param {TypeArray} array
  1946. *@return {Cesium.ComponentDatatype}
  1947. */
  1948. GeometryUtils.getAttributeComponentType = function (array) {
  1949. var attributeComponentType = Cesium.ComponentDatatype.SHORT;
  1950. if (array instanceof Int8Array) {
  1951. attributeComponentType = Cesium.ComponentDatatype.BYTE;
  1952. } else if (array instanceof Uint8Array || array instanceof Uint8ClampedArray) {
  1953. attributeComponentType = Cesium.ComponentDatatype.UNSIGNED_BYTE;
  1954. } else if (array instanceof Int16Array) {
  1955. attributeComponentType = Cesium.ComponentDatatype.SHORT;
  1956. } else if (array instanceof Uint16Array) {
  1957. attributeComponentType = Cesium.ComponentDatatype.UNSIGNED_SHORT;
  1958. } else if (array instanceof Int32Array) {
  1959. attributeComponentType = Cesium.ComponentDatatype.INT;
  1960. } else if (array instanceof Uint32Array) {
  1961. attributeComponentType = Cesium.ComponentDatatype.UNSIGNED_INT;
  1962. } else if (array instanceof Float32Array) {
  1963. attributeComponentType = Cesium.ComponentDatatype.FLOAT;
  1964. } else if (array instanceof Float64Array) {
  1965. attributeComponentType = Cesium.ComponentDatatype.DOUBLE;
  1966. }
  1967. return attributeComponentType;
  1968. }
  1969. /**
  1970. *
  1971. *@param {Object}geometry
  1972. *@return {Boolean}
  1973. */
  1974. GeometryUtils.isGeometry3js = function (geometry) {
  1975. return (typeof THREE !== 'undefined' && (geometry instanceof THREE.Geometry || geometry instanceof THREE.BufferGeometry))
  1976. || (geometry.attributes && geometry.attributes.position && geometry.index)
  1977. || (geometry.vertices && geometry.faces);
  1978. }
  1979. /**
  1980. *
  1981. *@param {THREE.BufferGeometry}geometry
  1982. *@private
  1983. */
  1984. GeometryUtils.parseBufferGeometry3js = function (geometry) {
  1985. // var start = new Date();
  1986. var attributes = {};
  1987. if (!geometry.attributes.normal) {
  1988. geometry.computeFaceNormals();
  1989. }
  1990. for (var attrName in geometry.attributes) {
  1991. if (geometry.attributes.hasOwnProperty(attrName)) {
  1992. var attr = geometry.getAttribute(attrName);
  1993. if (attr && attr.array.length > 0) {
  1994. attributes[attrName] = new Cesium.GeometryAttribute({
  1995. componentDatatype: GeometryUtils.getAttributeComponentType(attr.array),
  1996. componentsPerAttribute: attr.itemSize,
  1997. values: attr.array,
  1998. normalize: attr.normalized
  1999. });
  2000. }
  2001. }
  2002. }
  2003. var indices = [];
  2004. if (!geometry.index && geometry.groups) {
  2005. geometry.groups.forEach(function (group) {
  2006. for (var i = 0; i < group.count; i++) {
  2007. indices.push(i + group.start);
  2008. }
  2009. })
  2010. indices = new Int32Array(indices);
  2011. } else {
  2012. indices = geometry.index.array;
  2013. }
  2014. var cesGeometry = new Cesium.Geometry({
  2015. attributes: attributes,
  2016. indices: indices,
  2017. primitiveType: Cesium.PrimitiveType.TRIANGLES
  2018. });
  2019. return cesGeometry;
  2020. }
  2021. /**
  2022. *
  2023. *@param {THREE.Geometry}geometry3js
  2024. *@return {Cesium.Geometry}
  2025. */
  2026. GeometryUtils.fromGeometry3js = function (geometry3js) {
  2027. if (geometry3js.attributes && (geometry3js.index || geometry3js.groups.length)) {
  2028. } else {
  2029. geometry3js = new THREE.BufferGeometry().fromGeometry(geometry3js);
  2030. }
  2031. var geometry = GeometryUtils.parseBufferGeometry3js(geometry3js);
  2032. //GeometryUtils.computeVertexNormals(geometry);
  2033. Cesium.GeometryPipeline.computeNormal(geometry);
  2034. return geometry;
  2035. var positions = new Float32Array(geometry3js.vertices.length * 3);
  2036. for (var i = 0; i < geometry3js.vertices.length; i++) {
  2037. positions[i * 3] = geometry3js.vertices[i].x;
  2038. if (!geometry3js.up || geometry3js.up.y) {
  2039. positions[i * 3 + 1] = geometry3js.vertices[i].z;
  2040. positions[i * 3 + 2] = geometry3js.vertices[i].y;
  2041. } else {
  2042. positions[i * 3 + 1] = geometry3js.vertices[i].y;
  2043. positions[i * 3 + 2] = geometry3js.vertices[i].z;
  2044. }
  2045. }
  2046. var indices = new Int32Array(geometry3js.faces.length * 3);
  2047. for (var i = 0; i < geometry3js.faces.length; i++) {
  2048. indices[i * 3] = geometry3js.faces[i].a;
  2049. indices[i * 3 + 1] = geometry3js.faces[i].b;
  2050. indices[i * 3 + 2] = geometry3js.faces[i].c;
  2051. }
  2052. var attributes = {};
  2053. attributes.position = new Cesium.GeometryAttribute({
  2054. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  2055. componentsPerAttribute: 3,
  2056. values: positions
  2057. });
  2058. var cesGeometry = new Cesium.Geometry({
  2059. attributes: attributes,
  2060. indices: indices,
  2061. primitiveType: Cesium.PrimitiveType.TRIANGLES
  2062. });
  2063. return cesGeometry;
  2064. }
  2065. /**
  2066. *
  2067. *@param {Cesium.Geometry}geometry
  2068. *@return {THREE.Geometry}
  2069. */
  2070. GeometryUtils.toGeometry3js = function (geometry) {
  2071. if (typeof THREE === 'undefined') {
  2072. throw new Error("THREE 未加载");
  2073. }
  2074. var positions = geometry.attributes.position.values;
  2075. var positionIdx = 0;
  2076. var geometry3js = new THREE.Geometry();
  2077. for (var i = 0; i < positions.length ; i += 3) {
  2078. positionIdx = i * 3;
  2079. geometry3js.vertices.push(
  2080. new THREE.Vector3(positions[positionIdx], positions[positionIdx + 2], positions[positionIdx + 1])
  2081. );
  2082. }
  2083. for (var i = 0; i < geometry.indices.length ; i += 3) {
  2084. var idx1 = geometry.indices[i];
  2085. var idx2 = geometry.indices[i + 1];
  2086. var idx3 = geometry.indices[i + 2];
  2087. geometry3js.faces.push(new THREE.Face3(idx1, idx2, idx3));
  2088. }
  2089. return geometry3js;
  2090. }
  2091. /**
  2092. *@param {Cesium.Geometry|THREE.Geometry}
  2093. *@param {Cesium.Cartesian3}[offset]
  2094. *@return {CSG}
  2095. */
  2096. GeometryUtils.toCSG = function (geometry, offset) {
  2097. if (!(typeof THREE === 'undefined')) {
  2098. if (geometry instanceof THREE.Geometry) {
  2099. return GeometryUtils._toCSG3js(geometry, offset);
  2100. }
  2101. }
  2102. if (!offset) {
  2103. offset = { x: 0, y: 0, z: 0 };
  2104. }
  2105. if (!geometry.attributes.normal) {
  2106. geometry = Cesium.GeometryPipeline.computeNormal(geometry);
  2107. }
  2108. if (geometry.primitiveType !== Cesium.PrimitiveType.TRIANGLES) {
  2109. throw new Error("暂不支持此类几何体");
  2110. }
  2111. if (!CSG) {
  2112. throw new Error('CSG 库未加载。请从 https://github.com/evanw/csg.js 获取');
  2113. }
  2114. var faceCount = geometry.indices.length / 3;
  2115. var polygons = [], vertices = [];
  2116. var positions = geometry.attributes.position.values;
  2117. var normals = geometry.attributes.normal.values;
  2118. var normalIdx = 0, positionIdx = 0;
  2119. for (var i = 0; i < geometry.indices.length ; i += 3) {
  2120. vertices = [];
  2121. var idx1 = geometry.indices[i];
  2122. var idx2 = geometry.indices[i + 1];
  2123. var idx3 = geometry.indices[i + 2];
  2124. positionIdx = idx1 * 3;
  2125. normalIdx = idx1 * 3;
  2126. vertices.push(new CSG.Vertex(
  2127. [positions[positionIdx++] + offset.x, positions[positionIdx++] + offset.y, positions[positionIdx++] + offset.z],
  2128. [normals[normalIdx++], normals[normalIdx++], normals[normalIdx++]]
  2129. ));
  2130. positionIdx = idx2 * 3;
  2131. normalIdx = idx2 * 3;
  2132. vertices.push(new CSG.Vertex(
  2133. [positions[positionIdx++] + offset.x, positions[positionIdx++] + offset.y, positions[positionIdx++] + offset.z],
  2134. [normals[normalIdx++], normals[normalIdx++], normals[normalIdx++]]
  2135. ));
  2136. positionIdx = idx3 * 3;
  2137. normalIdx = idx3 * 3;
  2138. vertices.push(new CSG.Vertex(
  2139. [positions[positionIdx++] + offset.x, positions[positionIdx++] + offset.y, positions[positionIdx++] + offset.z],
  2140. [normals[normalIdx++], normals[normalIdx++], normals[normalIdx++]]
  2141. ));
  2142. polygons.push(new CSG.Polygon(vertices));
  2143. }
  2144. return CSG.fromPolygons(polygons);
  2145. }
  2146. /**
  2147. *@param {CSG}csg_model
  2148. *@param {Boolean}[toGeometry3js=false]
  2149. *@return {Cesium.Geometry|THREE.Geometry}
  2150. */
  2151. GeometryUtils.fromCSG = function (csg_model, toGeometry3js) {
  2152. if (!(typeof THREE === 'undefined')) {
  2153. if (geometry instanceof THREE.Geometry) {
  2154. return GeometryUtils._fromCSG3js(geometry, offset);
  2155. }
  2156. }
  2157. var i, j, vertices,
  2158. polygons = csg_model.toPolygons();
  2159. if (!CSG) {
  2160. throw new Error('CSG 库未加载。请从 https://github.com/evanw/csg.js 获取');
  2161. }
  2162. var positions = [];
  2163. var normals = [];
  2164. var indices = [];
  2165. for (i = 0; i < polygons.length; i++) {
  2166. // Vertices
  2167. vertices = [];
  2168. for (j = 0; j < polygons[i].vertices.length; j++) {
  2169. vertices.push(this.getGeometryVertice(positions, normals, polygons[i].vertices[j].pos, polygons[i].plane.normal));
  2170. }
  2171. if (vertices[0] === vertices[vertices.length - 1]) {
  2172. vertices.pop();
  2173. }
  2174. for (var j = 2; j < vertices.length; j++) {
  2175. indices.push(vertices[0], vertices[j - 1], vertices[j]);
  2176. }
  2177. }
  2178. positions = new Float32Array(positions);
  2179. normals = new Float32Array(normals);
  2180. indices = new Int32Array(indices);
  2181. var attributes = {};
  2182. attributes.position = new Cesium.GeometryAttribute({
  2183. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  2184. componentsPerAttribute: 3,
  2185. values: positions
  2186. });
  2187. attributes.normal = new Cesium.GeometryAttribute({
  2188. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  2189. componentsPerAttribute: 3,
  2190. values: normals
  2191. });
  2192. var cesGeometry = new Cesium.Geometry({
  2193. attributes: attributes,
  2194. indices: indices,
  2195. primitiveType: Cesium.PrimitiveType.TRIANGLES
  2196. });
  2197. return cesGeometry;
  2198. }
  2199. GeometryUtils._toCSG3js = function (three_model, offset, rotation) {
  2200. if (typeof THREE === 'undefined') {
  2201. throw new Error("THREE 未加载");
  2202. }
  2203. var i, geometry, polygons, vertices, rotation_matrix;
  2204. if (!CSG) {
  2205. throw 'CSG library not loaded. Please get a copy from https://github.com/evanw/csg.js';
  2206. }
  2207. if (three_model instanceof THREE.Mesh) {
  2208. geometry = three_model.geometry;
  2209. offset = offset || three_model.position;
  2210. rotation = rotation || three_model.rotation;
  2211. } else if (three_model instanceof THREE.Geometry) {
  2212. geometry = three_model;
  2213. offset = offset || new THREE.Vector3(0, 0, 0);
  2214. rotation = rotation || new THREE.Euler(0, 0, 0);
  2215. } else {
  2216. throw 'Model type not supported.';
  2217. }
  2218. rotation_matrix = new THREE.Matrix4().makeRotationFromEuler(rotation);
  2219. var polygons = [];
  2220. for (i = 0; i < geometry.faces.length; i++) {
  2221. if (geometry.faces[i] instanceof THREE.Face3) {
  2222. vertices = [];
  2223. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].a].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2224. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].b].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2225. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].c].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2226. polygons.push(new CSG.Polygon(vertices));
  2227. } else if (geometry.faces[i] instanceof THREE.Face4) {
  2228. vertices = [];
  2229. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].a].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2230. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].b].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2231. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].d].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2232. polygons.push(new CSG.Polygon(vertices));
  2233. vertices = [];
  2234. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].b].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2235. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].c].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2236. vertices.push(new CSG.Vertex(geometry.vertices[geometry.faces[i].d].clone().add(offset).applyMatrix4(rotation_matrix), [geometry.faces[i].normal.x, geometry.faces[i].normal.y, geometry.faces[i].normal.z]));
  2237. polygons.push(new CSG.Polygon(vertices));
  2238. } else {
  2239. throw 'Model contains unsupported face.';
  2240. }
  2241. }
  2242. return CSG.fromPolygons(polygons);
  2243. }
  2244. GeometryUtils._fromCSG3js = function (csg_model) {
  2245. if (typeof THREE === 'undefined') {
  2246. throw new Error("THREE 未加载");
  2247. }
  2248. var i, j, vertices, face,
  2249. three_geometry = new THREE.Geometry(),
  2250. polygons = csg_model.toPolygons();
  2251. if (!CSG) {
  2252. throw 'CSG library not loaded. Please get a copy from https://github.com/evanw/csg.js';
  2253. }
  2254. for (i = 0; i < polygons.length; i++) {
  2255. // Vertices
  2256. vertices = [];
  2257. for (j = 0; j < polygons[i].vertices.length; j++) {
  2258. vertices.push(GeometryUtils._getGeometryVertice3js(three_geometry, polygons[i].vertices[j].pos));
  2259. }
  2260. if (vertices[0] === vertices[vertices.length - 1]) {
  2261. vertices.pop();
  2262. }
  2263. for (var j = 2; j < vertices.length; j++) {
  2264. face = new THREE.Face3(vertices[0], vertices[j - 1], vertices[j], new THREE.Vector3().copy(polygons[i].plane.normal));
  2265. three_geometry.faces.push(face);
  2266. three_geometry.faceVertexUvs[0].push(new THREE.Vector2());
  2267. }
  2268. }
  2269. three_geometry.computeBoundingBox();
  2270. return three_geometry;
  2271. },
  2272. GeometryUtils._getGeometryVertice3js = function (geometry, vertice_position) {
  2273. var i;
  2274. for (i = 0; i < geometry.vertices.length; i++) {
  2275. if (geometry.vertices[i].x === vertice_position.x && geometry.vertices[i].y === vertice_position.y && geometry.vertices[i].z === vertice_position.z) {
  2276. // Vertice already exists
  2277. return i;
  2278. }
  2279. };
  2280. geometry.vertices.push(new THREE.Vector3(vertice_position.x, vertice_position.y, vertice_position.z));
  2281. return geometry.vertices.length - 1;
  2282. }
  2283. return GeometryUtils;
  2284. });
  2285. define('Core/Shaders/phong_frag',[],function () {
  2286. var phong_frag = '\n\
  2287. varying vec3 v_position;\n\
  2288. varying vec3 v_normal;\n\
  2289. uniform float picked;\n\
  2290. uniform vec4 pickedColor;\n\
  2291. uniform vec4 defaultColor;\n\
  2292. uniform float specular;\n\
  2293. uniform float shininess;\n\
  2294. uniform vec3 emission;\n\
  2295. void main() {\n\
  2296. vec3 positionToEyeEC = -v_position; \n\
  2297. vec3 normalEC =normalize(v_normal);\n\
  2298. vec4 color=defaultColor;\n\
  2299. if(picked!=0.0){\n\
  2300. color = pickedColor;\n\
  2301. }\n\
  2302. czm_material material;\n\
  2303. material.specular = specular;\n\
  2304. material.shininess = shininess;\n\
  2305. material.normal = normalEC;\n\
  2306. material.emission =emission;//vec3(0.2,0.2,0.2);\n\
  2307. material.diffuse = color.rgb ;\n\
  2308. material.alpha = color.a;\n\
  2309. gl_FragColor = czm_phong(normalize(positionToEyeEC), material,czm_lightDirectionEC);\n\
  2310. }';
  2311. return phong_frag;
  2312. })
  2313. ;
  2314. define('Core/Shaders/phong_vert',[],function () {
  2315. var phong_vert = "\n\
  2316. #ifdef GL_ES\n\
  2317. precision highp float;\n\
  2318. #endif\n\
  2319. \n\
  2320. \n\
  2321. \n\
  2322. varying vec3 v_position;\n\
  2323. varying vec3 v_normal;\n\
  2324. \n\
  2325. varying vec3 v_light0Direction;\n\
  2326. \n\
  2327. void main(void) \n\
  2328. {\n\
  2329. vec4 pos = modelViewMatrix * vec4( position,1.0);\n\
  2330. v_normal = normalMatrix * normal;\n\
  2331. v_position = pos.xyz;\n\
  2332. v_light0Direction = mat3( modelViewMatrix) * vec3(1.0,1.0,1.0);\n\
  2333. gl_Position = projectionMatrix * pos;\n\
  2334. }";
  2335. return phong_vert;
  2336. });
  2337. define('Core/MeshPhongMaterial',[
  2338. 'Core/MeshMaterial',
  2339. 'Core/Shaders/phong_frag',
  2340. 'Core/Shaders/phong_vert'
  2341. ], function (
  2342. MeshMaterial,
  2343. phong_frag,
  2344. phong_vert
  2345. ) {
  2346. /**
  2347. *
  2348. *@constructor
  2349. *@memberof Cesium
  2350. *@extends Cesium.MeshMaterial
  2351. */
  2352. function MeshPhongMaterial(options) {
  2353. options = options ? options : {};
  2354. options.uniforms = options.uniforms ? options.uniforms : {
  2355. shininess: -1,
  2356. emission: [0, 0, 0],
  2357. specular: 0
  2358. };
  2359. options.uniforms.shininess = Cesium.defaultValue(options.uniforms.shininess, 0);
  2360. options.uniforms.emission = Cesium.defaultValue(options.uniforms.emission, [0.2, 0.2, 0.2]);
  2361. options.uniforms.specular = Cesium.defaultValue(options.uniforms.specular, 0);
  2362. MeshMaterial.apply(this, arguments);
  2363. this.vertexShader = phong_vert;
  2364. this.fragmentShader = phong_frag;
  2365. }
  2366. MeshPhongMaterial.prototype = new MeshMaterial();
  2367. return MeshPhongMaterial;
  2368. })
  2369. ;
  2370. define('Core/Mesh',[
  2371. 'Core/Rotation',
  2372. 'Util/CSG',
  2373. 'Core/MeshMaterial',
  2374. 'Core/GeometryUtils',
  2375. 'Core/MeshPhongMaterial'
  2376. ], function (
  2377. Rotation,
  2378. CSG,
  2379. MeshMaterial,
  2380. GeometryUtils,
  2381. MeshPhongMaterial
  2382. ) {
  2383. var defaultValue = Cesium.defaultValue;
  2384. /**
  2385. *
  2386. *@param {Object|geometry}options
  2387. *@param {Cesium.Geometry|Cesium.CSG|THREE.Geometry|THREE.BufferGeometry}options.geometry
  2388. *@param {Cesium.MeshMaterial}options.material
  2389. *@param {Boolean}[options.show=true]
  2390. *@param {Cesium.Cartesian3}[options.position]
  2391. *@param {Cesium.Rotation}[options.rotation]
  2392. *@param {Cesium.Cartesian3}[options.scale]
  2393. *@param {Cesium.MeshMaterial}[material]
  2394. *
  2395. *@property {Cesium.Geometry}geometry
  2396. *@property {Cesium.MeshMaterial}material
  2397. *@property {Boolean}show
  2398. *@property {Cesium.Cartesian3}position
  2399. *@property {Cesium.VolumeRendering.Rotation}rotation
  2400. *@property {Cesium.Cartesian3}scale
  2401. *@property {Boolean}needUpdate
  2402. *@property {Cesium.Mesh|Cesium.LOD}parent
  2403. *
  2404. *@constructor
  2405. *@memberof Cesium
  2406. *@example
  2407. //1.
  2408. var mesh=new Mesh(geomertry,material);
  2409. //2.
  2410. var mesh2=new Mesh({
  2411. geomertry:geomertry2,
  2412. material:material2,
  2413. position:position2
  2414. });
  2415. */
  2416. function Mesh(options) {
  2417. if (Mesh.isGeometrySupported(options)) {
  2418. var geometry = options;
  2419. options = {
  2420. geometry: geometry,
  2421. material: arguments[1]
  2422. };
  2423. }
  2424. if (!options || !options.geometry) {
  2425. throw new Error("geometry是必须参数");
  2426. }
  2427. if (!Mesh.isGeometrySupported(options.geometry)) {
  2428. throw new Error("暂不支持此类型的geometry");
  2429. }
  2430. if (GeometryUtils.isGeometry3js(options.geometry)) {
  2431. options.geometry = GeometryUtils.fromGeometry3js(options.geometry);
  2432. } else if (options.geometry instanceof CSG) {
  2433. if (options.geometry.polygons.length == 0) {
  2434. options.show = false;
  2435. }
  2436. options.geometry = CSG.fromCSG(options.geometry);
  2437. } else if (typeof options.geometry.constructor.createGeometry == 'function') {
  2438. options.geometry = options.geometry.constructor.createGeometry(options.geometry);
  2439. }
  2440. this.uuid = Cesium.createGuid();
  2441. this.show = defaultValue(options.show, true);
  2442. this._geometry = options.geometry;
  2443. this._material = defaultValue(options.material, new MeshMaterial());
  2444. this._position = defaultValue(options.position, new Cesium.Cartesian3(0, 0, 0));
  2445. this._scale = defaultValue(options.scale, new Cesium.Cartesian3(1, 1, 1));
  2446. this._rotation = defaultValue(options.rotation, { axis: new Cesium.Cartesian3(0, 0, 1), angle: 0 });
  2447. this._rotation = new Rotation(this._rotation.axis, this._rotation.angle);
  2448. this._needsUpdate = false;
  2449. this._modelMatrix = new Cesium.Matrix4();
  2450. Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY, this._modelMatrix);
  2451. //用于设置旋转,优先级大于rotation
  2452. this.quaternion = null;
  2453. this._modelMatrixNeedsUpdate = true;
  2454. this._onNeedUpdateChanged = function () {
  2455. this.modelMatrixNeedsUpdate = true;
  2456. };
  2457. this._rotation.paramChanged.removeEventListener(this._onNeedUpdateChanged);
  2458. this._drawCommand = null;
  2459. this._children = [];
  2460. this._parent = null;
  2461. this.userData = {};
  2462. if (!this._geometry.attributes.normal
  2463. && this.material instanceof MeshPhongMaterial
  2464. && this._geometry.primitiveType == Cesium.PrimitiveType.TRIANGLES
  2465. ) {
  2466. Cesium.GeometryPipeline.computeNormal(this._geometry);
  2467. //GeometryUtils.computeVertexNormals(this._geometry);
  2468. }
  2469. }
  2470. Mesh.isGeometrySupported = function (geometry) {
  2471. var supported = (geometry instanceof Cesium.Geometry
  2472. || geometry instanceof CSG
  2473. || typeof geometry.constructor.createGeometry == 'function'
  2474. || GeometryUtils.isGeometry3js(geometry));
  2475. return supported;
  2476. }
  2477. /**
  2478. *
  2479. *@param {Cesium.Mesh|Cesium.LOD}node
  2480. *@param {Cesium.Mesh~TraverseCallback}callback
  2481. */
  2482. Mesh.traverse = function (node, callback) {
  2483. callback(node);
  2484. if (node.children) {
  2485. node.children.forEach(function (child) {
  2486. callback(child);
  2487. })
  2488. }
  2489. }
  2490. /**
  2491. *
  2492. * @callback Cesium.Mesh~TraverseCallback
  2493. * @param {Cesium.Mesh|Cesium.LOD}node
  2494. */
  2495. Object.defineProperties(Mesh.prototype, {
  2496. modelMatrix: {
  2497. get: function () {
  2498. return this._modelMatrix;
  2499. }
  2500. },
  2501. parent: {
  2502. get: function () {
  2503. return this._parent;
  2504. },
  2505. set: function (val) {
  2506. this._parent = val;
  2507. this.modelMatrixNeedsUpdate = true;
  2508. }
  2509. },
  2510. modelMatrixNeedsUpdate: {
  2511. get: function () {
  2512. return this._modelMatrixNeedsUpdate;
  2513. },
  2514. set: function (val) {
  2515. this._modelMatrixNeedsUpdate = val;
  2516. if (this._modelMatrixNeedsUpdate) {
  2517. Mesh.traverse(this, function (mesh) {
  2518. mesh._modelMatrixNeedsUpdate = val;
  2519. });
  2520. }
  2521. }
  2522. },
  2523. children: {
  2524. get: function () {
  2525. return this._children;
  2526. },
  2527. set: function (val) {
  2528. this._children = val;
  2529. this._needsUpdate = true;
  2530. }
  2531. },
  2532. geometry: {
  2533. get: function () {
  2534. return this._geometry;
  2535. },
  2536. set: function (val) {
  2537. this._geometry = val;
  2538. this._needsUpdate = true;
  2539. this.modelMatrixNeedsUpdate = true;
  2540. }
  2541. },
  2542. material: {
  2543. get: function () {
  2544. return this._material;
  2545. },
  2546. set: function (val) {
  2547. this._material = val;
  2548. this._needsUpdate = true;
  2549. }
  2550. },
  2551. needsUpdate: {
  2552. get: function () {
  2553. return this._needsUpdate;
  2554. },
  2555. set: function (val) {
  2556. this._needsUpdate = val;
  2557. }
  2558. },
  2559. rotation: {
  2560. get: function () {
  2561. return this._rotation;
  2562. },
  2563. set: function (val) {
  2564. if (val != this._rotation) {
  2565. this._rotation = val;
  2566. // this._needUpdate = true;
  2567. this.modelMatrixNeedsUpdate = true;
  2568. }
  2569. this._rotation.paramChanged.removeEventListener(this._onNeedUpdateChanged);
  2570. this._rotation = val;
  2571. this._rotation.paramChanged.addEventListener(this._onNeedUpdateChanged);
  2572. }
  2573. },
  2574. position: {
  2575. get: function () {
  2576. return this._position;
  2577. },
  2578. set: function (val) {
  2579. if (val.x != this._position.x || val.y != this._position.y || val.z != this._position.z) {
  2580. this._position = val;
  2581. //this._needsUpdate = true;
  2582. this.modelMatrixNeedsUpdate = true;
  2583. }
  2584. this._position = val;
  2585. }
  2586. },
  2587. scale: {
  2588. get: function () {
  2589. return this._scale;
  2590. },
  2591. set: function (val) {
  2592. if (val.x != this._scale.x || val.y != this._scale.y || val.z != this._scale.z) {
  2593. this._scale = val;
  2594. // this._needsUpdate = true;
  2595. this.modelMatrixNeedsUpdate = true;
  2596. }
  2597. this._scale = val;
  2598. }
  2599. }
  2600. });
  2601. /**
  2602. *@oaram {Cesium.Mesh|Cesium.LOD}child
  2603. */
  2604. Mesh.prototype.add = function (mesh) {
  2605. if (mesh.parent !== this) {
  2606. mesh.parent = this;
  2607. }
  2608. this._children.push(mesh);
  2609. }
  2610. return Mesh;
  2611. })
  2612. ;
  2613. define('Core/Shaders/none_frag',[],function () {
  2614. var none_frag = "\n\
  2615. #ifdef GL_ES\n\
  2616. precision highp float;\n\
  2617. #endif\n\
  2618. \n\
  2619. varying vec3 v_position;\n\
  2620. \n\
  2621. uniform vec4 ambientColor;\n\
  2622. uniform vec4 diffuseColor;\n\
  2623. uniform vec4 specularColor;\n\
  2624. uniform float specularShininess;\n\
  2625. uniform float picked;\n\
  2626. uniform vec4 pickedColor;\n\
  2627. \n\
  2628. void main(void) \n\
  2629. {\n\
  2630. vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n\
  2631. vec4 ambient = ambientColor;\n\
  2632. vec4 diffuse = diffuseColor;\n\
  2633. vec4 specular = specularColor;\n\
  2634. color.xyz += ambient.xyz;\n\
  2635. color.xyz += diffuse.xyz;\n\
  2636. color.xyz += specular.xyz;\n\
  2637. color = vec4(color.rgb * diffuse.a, diffuse.a);\n\
  2638. gl_FragColor = color;\n\
  2639. if(picked!=0.0){\n\
  2640. gl_FragColor =mix(color, pickedColor*0.5,1.0);\n\
  2641. }\n\
  2642. }";
  2643. return none_frag;
  2644. })
  2645. ;
  2646. define('Core/Shaders/none_vert',[],function () {
  2647. var none_vert = "\n\
  2648. #ifdef GL_ES\n\
  2649. precision highp float;\n\
  2650. #endif\n\
  2651. \n\
  2652. \n\
  2653. \n\
  2654. varying vec3 v_position;\n\
  2655. \n\
  2656. void main(void) \n\
  2657. {\n\
  2658. vec4 pos = modelViewMatrix * vec4( position,1.0);\n\
  2659. v_position = pos.xyz;\n\
  2660. gl_Position = projectionMatrix * pos;\n\
  2661. }";
  2662. return none_vert;
  2663. });
  2664. define('Core/Shaders/normals_frag',[],function () {
  2665. var normals_frag = "\n\
  2666. #ifdef GL_ES\n\
  2667. precision highp float;\n\
  2668. #endif\n\
  2669. \n\
  2670. varying vec3 v_position;\n\
  2671. varying vec3 v_normal;\n\
  2672. \n\
  2673. uniform vec4 ambientColor;\n\
  2674. uniform vec4 diffuseColor;\n\
  2675. uniform vec4 specularColor;\n\
  2676. uniform float specularShininess;\n\
  2677. uniform float alpha;\n\
  2678. uniform float picked;\n\
  2679. uniform vec4 pickedColor;\n\
  2680. \n\
  2681. varying vec3 v_light0Direction;\n\
  2682. \n\
  2683. void main(void) \n\
  2684. {\n\
  2685. vec3 normal = normalize(v_normal);\n\
  2686. vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n\
  2687. vec3 diffuseLight = vec3(0.0, 0.0, 0.0);\n\
  2688. vec3 lightColor = vec3(1.0,1.0,1.0);\n\
  2689. vec4 ambient = ambientColor;\n\
  2690. vec4 diffuse = diffuseColor;\n\
  2691. vec4 specular = specularColor;\n\
  2692. \n\
  2693. vec3 specularLight = vec3(0.0, 0.0, 0.0);\n\
  2694. {\n\
  2695. float specularIntensity = 0.0;\n\
  2696. float attenuation = 1.0;\n\
  2697. vec3 l = normalize(v_light0Direction);\n\
  2698. vec3 viewDir = -normalize(v_position);\n\
  2699. vec3 h = normalize(l+viewDir);\n\
  2700. specularIntensity = max(0.0, pow(max(dot(normal,h), 0.0) , specularShininess)) * attenuation;\n\
  2701. specularLight += lightColor * specularIntensity;\n\
  2702. diffuseLight += lightColor * max(dot(normal,l), 0.0) * attenuation;\n\
  2703. }\n\
  2704. //specular.xyz *= specularLight;\n\
  2705. //diffuse.xyz *= diffuseLight;\n\
  2706. color.xyz += ambient.xyz;\n\
  2707. color.xyz += diffuse.xyz;\n\
  2708. color.xyz += specular.xyz;\n\
  2709. color = vec4(color.rgb * diffuse.a, diffuse.a*alpha);\n\
  2710. gl_FragColor = color;\n\
  2711. if(picked!=0.0){\n\
  2712. gl_FragColor =mix(color, pickedColor*0.5,1.0);\n\
  2713. }\n\
  2714. }";
  2715. return normals_frag;
  2716. });
  2717. define('Core/Shaders/normals_vert',[],function () {
  2718. var normals_vert = "\n\
  2719. #ifdef GL_ES\n\
  2720. precision highp float;\n\
  2721. #endif\n\
  2722. \n\
  2723. \n\
  2724. \n\
  2725. varying vec3 v_position;\n\
  2726. varying vec3 v_normal;\n\
  2727. \n\
  2728. varying vec3 v_light0Direction;\n\
  2729. \n\
  2730. void main(void) \n\
  2731. {\n\
  2732. vec4 pos = modelViewMatrix * vec4( position,1.0);\n\
  2733. v_normal = normalMatrix * normal;\n\
  2734. v_position = pos.xyz;\n\
  2735. v_light0Direction = mat3( modelViewMatrix) * vec3(1.0,1.0,1.0);\n\
  2736. gl_Position = projectionMatrix * pos;\n\
  2737. }";
  2738. return normals_vert;
  2739. });
  2740. define('Core/Shaders/texture_frag',[],function () {
  2741. var texture_frag = "\n\
  2742. #ifdef GL_ES\n\
  2743. precision highp float;\n\
  2744. #endif\n\
  2745. \n\
  2746. varying vec3 v_position;\n\
  2747. varying vec2 v_texcoord0;\n\
  2748. \n\
  2749. uniform vec4 ambientColor;\n\
  2750. uniform sampler2D diffuseColorMap;\n\
  2751. uniform vec4 specularColor;\n\
  2752. uniform float specularShininess;\n\
  2753. uniform float picked;\n\
  2754. uniform vec4 pickedColor;\n\
  2755. \n\
  2756. uniform float alpha;\n\
  2757. \n\
  2758. void main(void) \n\
  2759. {\n\
  2760. vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n\
  2761. vec3 diffuseLight = vec3(0.0, 0.0, 0.0);\n\
  2762. vec3 lightColor = vec3(1.0,1.0,1.0);\n\
  2763. vec4 ambient = ambientColor;\n\
  2764. vec4 diffuse = texture2D(diffuseColorMap, v_texcoord0);\n\
  2765. vec4 specular = specularColor;\n\
  2766. color.xyz += ambient.xyz;\n\
  2767. color.xyz += diffuse.xyz;\n\
  2768. color.xyz += specular.xyz;\n\
  2769. color = vec4(diffuse.rgb * diffuse.a, diffuse.a*alpha);\n\
  2770. gl_FragColor = color;\n\
  2771. if(picked!=0.0){\n\
  2772. gl_FragColor =mix(color, pickedColor*0.5,1.0);\n\
  2773. }\n\
  2774. }";
  2775. return texture_frag;
  2776. })
  2777. ;
  2778. define('Core/Shaders/texture_vert',[],function () {
  2779. var texture_vert = "\n\
  2780. #ifdef GL_ES\n\
  2781. precision highp float;\n\
  2782. #endif\n\
  2783. \n\
  2784. \n\
  2785. \n\
  2786. varying vec3 v_position;\n\
  2787. varying vec2 v_texcoord0;\n\
  2788. \n\
  2789. void main(void) \n\
  2790. {\n\
  2791. vec4 pos = modelViewMatrix * vec4( position,1.0);\n\
  2792. v_texcoord0 = uv;\n\
  2793. v_position = pos.xyz;\n\
  2794. gl_Position = projectionMatrix * pos;\n\
  2795. }";
  2796. return texture_vert;
  2797. });
  2798. define('Core/Shaders/texture_normals_frag',[],function () {
  2799. var texture_normals_frag = "\n\
  2800. #ifdef GL_ES\n\
  2801. precision highp float;\n\
  2802. #endif\n\
  2803. \n\
  2804. varying vec3 v_position;\n\
  2805. varying vec2 v_texcoord0;\n\
  2806. varying vec3 v_normal;\n\
  2807. \n\
  2808. uniform vec4 ambientColor;\n\
  2809. uniform sampler2D diffuseColorMap;\n\
  2810. uniform vec4 specularColor;\n\
  2811. uniform float specularShininess;\n\
  2812. uniform float picked;\n\
  2813. uniform vec4 pickedColor;\n\
  2814. \n\
  2815. varying vec3 v_light0Direction;\n\
  2816. \n\
  2817. void main(void) \n\
  2818. {\n\
  2819. vec3 normal = normalize(v_normal);\n\
  2820. vec4 color = vec4(0.0, 0.0, 0.0, 0.0);\n\
  2821. vec3 diffuseLight = vec3(0.0, 0.0, 0.0);\n\
  2822. vec3 lightColor = vec3(1.0,1.0,1.0);\n\
  2823. vec4 ambient = ambientColor;\n\
  2824. vec4 diffuse = texture2D(diffuseColorMap, v_texcoord0);\n\
  2825. vec4 specular = specularColor;\n\
  2826. \n\
  2827. vec3 specularLight = vec3(0.0, 0.0, 0.0);\n\
  2828. {\n\
  2829. float specularIntensity = 0.0;\n\
  2830. float attenuation = 1.0;\n\
  2831. vec3 l = normalize(v_light0Direction);\n\
  2832. vec3 viewDir = -normalize(v_position);\n\
  2833. vec3 h = normalize(l+viewDir);\n\
  2834. specularIntensity = max(0.0, pow(max(dot(normal,h), 0.0) , specularShininess)) * attenuation;\n\
  2835. specularLight += lightColor * specularIntensity;\n\
  2836. diffuseLight += lightColor * max(dot(normal,l), 0.0) * attenuation;\n\
  2837. }\n\
  2838. //specular.xyz *= specularLight;\n\
  2839. //diffuse.xyz *= diffuseLight;\n\
  2840. color.xyz += ambient.xyz;\n\
  2841. color.xyz += diffuse.xyz;\n\
  2842. color.xyz += specular.xyz;\n\
  2843. color = vec4(diffuse.rgb * diffuse.a, diffuse.a);\n\
  2844. gl_FragColor = color;\n\
  2845. if(picked!=0.0){\n\
  2846. gl_FragColor = pickedColor*color;\n\
  2847. }\n\
  2848. }";
  2849. return texture_normals_frag;
  2850. });
  2851. define('Core/Shaders/texture_normals_vert',[],function () {
  2852. var texture_normals_vert = "\n\
  2853. #ifdef GL_ES\n\
  2854. precision highp float;\n\
  2855. #endif\n\
  2856. \n\
  2857. \n\
  2858. \n\
  2859. varying vec3 v_position;\n\
  2860. varying vec2 v_texcoord0;\n\
  2861. varying vec3 v_normal;\n\
  2862. \n\
  2863. varying vec3 v_light0Direction;\n\
  2864. \n\
  2865. void main(void) \n\
  2866. {\n\
  2867. vec4 pos = modelViewMatrix * vec4( position,1.0);\n\
  2868. v_normal = normalMatrix * normal;\n\
  2869. v_texcoord0 =uv;\n\
  2870. v_position = pos.xyz;\n\
  2871. v_light0Direction = mat3( modelViewMatrix) * vec3(1.0,1.0,1.0);\n\
  2872. gl_Position = projectionMatrix * pos;\n\
  2873. }";
  2874. return texture_normals_vert;
  2875. });
  2876. define('Core/Shaders/ShaderChunk',[
  2877. "Core/Shaders/none_frag",
  2878. "Core/Shaders/none_vert",
  2879. "Core/Shaders/normals_frag",
  2880. "Core/Shaders/normals_vert",
  2881. "Core/Shaders/texture_frag",
  2882. "Core/Shaders/texture_vert",
  2883. "Core/Shaders/texture_normals_frag",
  2884. "Core/Shaders/texture_normals_vert"
  2885. ], function (
  2886. none_frag,
  2887. none_vert,
  2888. normals_frag,
  2889. normals_vert,
  2890. texture_frag,
  2891. texture_vert,
  2892. texture_normals_frag,
  2893. texture_normals_vert
  2894. ) {
  2895. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  2896. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  2897. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  2898. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";
  2899. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  2900. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  2901. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  2902. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t}\n\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\n\tfloat b = 3.45068 + (4.18814 + y) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( c
  2903. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  2904. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n";
  2905. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  2906. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  2907. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  2908. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  2909. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  2910. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  2911. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  2912. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n";
  2913. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelTo
  2914. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n";
  2915. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  2916. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  2917. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  2918. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  2919. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  2920. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = min( floor( D ) / 255.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract(Le);\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n\treturn vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  2921. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = asin( flipNormal * reflectVec.y ) * RECIPROCAL_PI + 0.5;\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  2922. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";
  2923. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";
  2924. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n";
  2925. var fog_vertex = "\n#ifdef USE_FOG\nfogDepth = -mvPosition.z;\n#endif";
  2926. var fog_pars_vertex = "#ifdef USE_FOG\n varying float fogDepth;\n#endif\n";
  2927. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  2928. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif\n";
  2929. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n";
  2930. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  2931. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  2932. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  2933. var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor
  2934. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  2935. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  2936. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";
  2937. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\n\t\tvec4 t = texture2D( ltcMat, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( 1, 0, t.y ),\n\t\t\tvec3( 0, t.z, 0 ),\n\t\t\tvec3( t.w, 0, t.x )\n\t\t);\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness )
  2938. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  2939. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  2940. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  2941. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  2942. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  2943. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  2944. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  2945. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  2946. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  2947. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif\n";
  2948. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  2949. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  2950. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  2951. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";
  2952. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  2953. var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  2954. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  2955. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  2956. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  2957. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\ngl_Position = projectionMatrix * mvPosition;\n";
  2958. var dithering_fragment = "#if defined( DITHERING )\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif\n";
  2959. var dithering_pars_fragment = "#if defined( DITHERING )\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif\n";
  2960. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif\n";
  2961. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  2962. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tshadow = (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy +
  2963. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n#endif\n";
  2964. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n#endif\n";
  2965. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  2966. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  2967. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";
  2968. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif\n";
  2969. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  2970. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  2971. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  2972. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  2973. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  2974. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  2975. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";
  2976. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  2977. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  2978. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  2979. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  2980. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n#endif\n";
  2981. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  2982. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  2983. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  2984. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  2985. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  2986. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  2987. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  2988. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  2989. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  2990. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}\n";
  2991. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  2992. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}\n";
  2993. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  2994. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  2995. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  2996. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  2997. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}\n";
  2998. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  2999. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}\n";
  3000. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  3001. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  3002. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}\n";
  3003. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  3004. var shadow_vert = "#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  3005. var ShaderChunk = {
  3006. alphamap_fragment: alphamap_fragment,
  3007. alphamap_pars_fragment: alphamap_pars_fragment,
  3008. alphatest_fragment: alphatest_fragment,
  3009. aomap_fragment: aomap_fragment,
  3010. aomap_pars_fragment: aomap_pars_fragment,
  3011. begin_vertex: begin_vertex,
  3012. beginnormal_vertex: beginnormal_vertex,
  3013. bsdfs: bsdfs,
  3014. bumpmap_pars_fragment: bumpmap_pars_fragment,
  3015. clipping_planes_fragment: clipping_planes_fragment,
  3016. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  3017. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  3018. clipping_planes_vertex: clipping_planes_vertex,
  3019. color_fragment: color_fragment,
  3020. color_pars_fragment: color_pars_fragment,
  3021. color_pars_vertex: color_pars_vertex,
  3022. color_vertex: color_vertex,
  3023. common: common,
  3024. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  3025. defaultnormal_vertex: defaultnormal_vertex,
  3026. displacementmap_pars_vertex: displacementmap_pars_vertex,
  3027. displacementmap_vertex: displacementmap_vertex,
  3028. emissivemap_fragment: emissivemap_fragment,
  3029. emissivemap_pars_fragment: emissivemap_pars_fragment,
  3030. encodings_fragment: encodings_fragment,
  3031. encodings_pars_fragment: encodings_pars_fragment,
  3032. envmap_fragment: envmap_fragment,
  3033. envmap_pars_fragment: envmap_pars_fragment,
  3034. envmap_pars_vertex: envmap_pars_vertex,
  3035. envmap_vertex: envmap_vertex,
  3036. fog_vertex: fog_vertex,
  3037. fog_pars_vertex: fog_pars_vertex,
  3038. fog_fragment: fog_fragment,
  3039. fog_pars_fragment: fog_pars_fragment,
  3040. gradientmap_pars_fragment: gradientmap_pars_fragment,
  3041. lightmap_fragment: lightmap_fragment,
  3042. lightmap_pars_fragment: lightmap_pars_fragment,
  3043. lights_lambert_vertex: lights_lambert_vertex,
  3044. lights_pars: lights_pars,
  3045. lights_phong_fragment: lights_phong_fragment,
  3046. lights_phong_pars_fragment: lights_phong_pars_fragment,
  3047. lights_physical_fragment: lights_physical_fragment,
  3048. lights_physical_pars_fragment: lights_physical_pars_fragment,
  3049. lights_template: lights_template,
  3050. logdepthbuf_fragment: logdepthbuf_fragment,
  3051. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  3052. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  3053. logdepthbuf_vertex: logdepthbuf_vertex,
  3054. map_fragment: map_fragment,
  3055. map_pars_fragment: map_pars_fragment,
  3056. map_particle_fragment: map_particle_fragment,
  3057. map_particle_pars_fragment: map_particle_pars_fragment,
  3058. metalnessmap_fragment: metalnessmap_fragment,
  3059. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  3060. morphnormal_vertex: morphnormal_vertex,
  3061. morphtarget_pars_vertex: morphtarget_pars_vertex,
  3062. morphtarget_vertex: morphtarget_vertex,
  3063. normal_flip: normal_flip,
  3064. normal_fragment: normal_fragment,
  3065. normalmap_pars_fragment: normalmap_pars_fragment,
  3066. packing: packing,
  3067. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  3068. project_vertex: project_vertex,
  3069. dithering_fragment: dithering_fragment,
  3070. dithering_pars_fragment: dithering_pars_fragment,
  3071. roughnessmap_fragment: roughnessmap_fragment,
  3072. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  3073. shadowmap_pars_fragment: shadowmap_pars_fragment,
  3074. shadowmap_pars_vertex: shadowmap_pars_vertex,
  3075. shadowmap_vertex: shadowmap_vertex,
  3076. shadowmask_pars_fragment: shadowmask_pars_fragment,
  3077. skinbase_vertex: skinbase_vertex,
  3078. skinning_pars_vertex: skinning_pars_vertex,
  3079. skinning_vertex: skinning_vertex,
  3080. skinnormal_vertex: skinnormal_vertex,
  3081. specularmap_fragment: specularmap_fragment,
  3082. specularmap_pars_fragment: specularmap_pars_fragment,
  3083. tonemapping_fragment: tonemapping_fragment,
  3084. tonemapping_pars_fragment: tonemapping_pars_fragment,
  3085. uv_pars_fragment: uv_pars_fragment,
  3086. uv_pars_vertex: uv_pars_vertex,
  3087. uv_vertex: uv_vertex,
  3088. uv2_pars_fragment: uv2_pars_fragment,
  3089. uv2_pars_vertex: uv2_pars_vertex,
  3090. uv2_vertex: uv2_vertex,
  3091. worldpos_vertex: worldpos_vertex,
  3092. cube_frag: cube_frag,
  3093. cube_vert: cube_vert,
  3094. depth_frag: depth_frag,
  3095. depth_vert: depth_vert,
  3096. distanceRGBA_frag: distanceRGBA_frag,
  3097. distanceRGBA_vert: distanceRGBA_vert,
  3098. equirect_frag: equirect_frag,
  3099. equirect_vert: equirect_vert,
  3100. linedashed_frag: linedashed_frag,
  3101. linedashed_vert: linedashed_vert,
  3102. meshbasic_frag: meshbasic_frag,
  3103. meshbasic_vert: meshbasic_vert,
  3104. meshlambert_frag: meshlambert_frag,
  3105. meshlambert_vert: meshlambert_vert,
  3106. meshphong_frag: meshphong_frag,
  3107. meshphong_vert: meshphong_vert,
  3108. meshphysical_frag: meshphysical_frag,
  3109. meshphysical_vert: meshphysical_vert,
  3110. normal_frag: normal_frag,
  3111. normal_vert: normal_vert,
  3112. points_frag: points_frag,
  3113. points_vert: points_vert,
  3114. shadow_frag: shadow_frag,
  3115. shadow_vert: shadow_vert,
  3116. none_frag: none_frag,
  3117. none_vert:none_vert,
  3118. normals_frag: normals_frag,
  3119. normals_vert: normals_vert,
  3120. texture_frag: texture_frag,
  3121. texture_vert: texture_vert,
  3122. texture_normals_frag: texture_normals_frag,
  3123. texture_normals_vert: texture_normals_vert
  3124. };
  3125. ShaderChunk.parseIncludes = function (string) {
  3126. var pattern = /#include +<([\w\d.]+)>/g;
  3127. function replace(match, include) {
  3128. var replace = ShaderChunk[include];
  3129. if (replace === undefined) {
  3130. throw new Error('Can not resolve #include <' + include + '>');
  3131. }
  3132. return ShaderChunk.parseIncludes(replace);
  3133. }
  3134. return string.replace(pattern, replace);
  3135. }
  3136. return ShaderChunk;
  3137. });
  3138. define('Core/FramebufferTexture',[], function () {
  3139. /**
  3140. *帧缓存纹理类可以将一个mesh渲染到帧缓存并作为纹理提供给其他mesh<br/>
  3141. *需要配合{@link Cesium.MeshVisualizer}{@link Cesium.Mesh}{@link Cesium.MeshMaterial}使用
  3142. *@param {Cesium.Mesh}mesh
  3143. *
  3144. *@property {Cesium.Mesh}mesh
  3145. *@property {Cesium.Texture}texture
  3146. *
  3147. *@constructor
  3148. *@memberof Cesium
  3149. *@example
  3150. MeshVisualizer = Cesium.MeshVisualizer;
  3151. Mesh = Cesium.Mesh;
  3152. MeshMaterial = Cesium.MeshMaterial;
  3153. FramebufferTexture = Cesium.FramebufferTexture;
  3154. Shaders = VolumeRendering.Shaders;
  3155. var center2 = Cesium.Cartesian3.fromDegrees(homePosition[0]+3.5, homePosition[1] , 50000);
  3156. var modelMatrix2 = Cesium.Transforms.eastNorthUpToFixedFrame(center2);
  3157. var meshVisualizer = new MeshVisualizer({
  3158. modelMatrix: modelMatrix2,
  3159. up: { y: 1 },
  3160. scale: new Cesium.Cartesian3(2,2,2)
  3161. });
  3162. viewer.scene.primitives.add(meshVisualizer);
  3163. var guiControls = new function () {
  3164. this.model = 'bonsai';
  3165. this.steps = 256.0;
  3166. this.alphaCorrection = 1.0;
  3167. this.color1 = "#00FA58";
  3168. this.stepPos1 = 0.1;
  3169. this.color2 = "#CC6600";
  3170. this.stepPos2 = 0.7;
  3171. this.color3 = "#F2F200";
  3172. this.stepPos3 = 1.0;
  3173. };
  3174. function updateTransferFunction() {
  3175. var canvas = document.createElement('canvas');
  3176. canvas.height = 20;
  3177. canvas.width = 256;
  3178. var ctx = canvas.getContext('2d');
  3179. var grd = ctx.createLinearGradient(0, 0, canvas.width - 1, canvas.height - 1);
  3180. grd.addColorStop(guiControls.stepPos1, guiControls.color1);
  3181. grd.addColorStop(guiControls.stepPos2, guiControls.color2);
  3182. grd.addColorStop(guiControls.stepPos3, guiControls.color3);
  3183. ctx.fillStyle = grd;
  3184. ctx.fillRect(0, 0, canvas.width - 1, canvas.height - 1);
  3185. return canvas;
  3186. }
  3187. var dimensions = new Cesium.Cartesian3(50000, 50000, 50000);
  3188. var boxGeometry = Cesium.BoxGeometry.createGeometry(Cesium.BoxGeometry.fromDimensions({
  3189. dimensions: dimensions,
  3190. vertexFormat: Cesium.VertexFormat.POSITION_ONLY
  3191. }));
  3192. var materialFirstPass = new MeshMaterial({
  3193. vertexShader: Shaders.vertexShaderFirstPass,
  3194. fragmentShader: Shaders.fragmentShaderFirstPass,
  3195. side: MeshMaterial.Sides.BACK,
  3196. uniforms: {
  3197. dimensions: dimensions
  3198. }
  3199. });
  3200. var meshFirstPass = new Mesh(boxGeometry, materialFirstPass);
  3201. var rtTexture = new FramebufferTexture(meshFirstPass);//这里使用FramebufferTexture
  3202. var transferTexture = updateTransferFunction();
  3203. var materialSecondPass = new MeshMaterial({
  3204. vertexShader: Shaders.vertexShaderSecondPass,
  3205. fragmentShader: Shaders.fragmentShaderSecondPass,
  3206. side: MeshMaterial.Sides.FRONT,
  3207. uniforms: {
  3208. alpha: 1,
  3209. dimensions: dimensions,
  3210. tex: rtTexture,
  3211. cubeTex: "./teapot.raw.png",
  3212. transferTex: transferTexture,
  3213. steps: guiControls.steps,
  3214. alphaCorrection: guiControls.alphaCorrection
  3215. }
  3216. });
  3217. var meshSecondPass = new Mesh(boxGeometry, materialSecondPass);
  3218. meshVisualizer.add(meshSecondPass);
  3219. */
  3220. function FramebufferTexture(mesh,renderTarget) {
  3221. this.mesh = mesh;
  3222. this.texture = renderTarget;
  3223. }
  3224. return FramebufferTexture;
  3225. });
  3226. define('Core/LOD',[
  3227. 'Core/Rotation',
  3228. 'Core/RendererUtils'
  3229. ], function (
  3230. Rotation,
  3231. RendererUtils
  3232. ) {
  3233. var defaultValue = Cesium.defaultValue;
  3234. /**
  3235. *
  3236. *@param {Object|geometry}options
  3237. *@param {Boolean}[options.show=true]
  3238. *@param {Cesium.Cartesian3}[options.position]
  3239. *@param {Cesium.Rotation}[options.rotation]
  3240. *@param {Cesium.Cartesian3}[options.scale]
  3241. *
  3242. *@property {Boolean}show
  3243. *@property {Cesium.Cartesian3}position
  3244. *@property {Cesium.Rotation}rotation
  3245. *@property {Cesium.Cartesian3}scale
  3246. *@property {Boolean}needUpdate
  3247. *
  3248. *@constructor
  3249. *@memberof Cesium
  3250. *@example
  3251. MeshVisualizer = Cesium.MeshVisualizer;
  3252. Mesh = Cesium.Mesh;
  3253. MeshMaterial = Cesium.MeshMaterial;
  3254. LOD = Cesium.LOD;
  3255. var center = Cesium.Cartesian3.fromDegrees(homePosition[0], homePosition[1], 50000);
  3256. var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  3257. var meshVisualizer = new MeshVisualizer({
  3258. modelMatrix: modelMatrix,
  3259. up: { z: 1 }
  3260. });
  3261. viewer.scene.primitives.add(meshVisualizer);
  3262. var material = new MeshMaterial({
  3263. defaultColor: "rgba(200,0,0,1.0)",
  3264. wireframe: true,
  3265. side: MeshMaterial.Sides.FRONT
  3266. });
  3267. var radius = 20000;
  3268. var sphereL0 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({
  3269. radius: radius,
  3270. vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
  3271. stackPartitions:4,
  3272. slicePartitions: 4
  3273. }));
  3274. var sphereL1 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({
  3275. radius: radius,
  3276. vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
  3277. stackPartitions: 8,
  3278. slicePartitions: 8
  3279. }));
  3280. var sphereL2 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({
  3281. radius: radius,
  3282. vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
  3283. stackPartitions: 16,
  3284. slicePartitions: 16
  3285. }));
  3286. var sphereL3 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({
  3287. radius: radius,
  3288. vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
  3289. stackPartitions: 32,
  3290. slicePartitions: 32
  3291. }));
  3292. var sphereL4 = Cesium.SphereGeometry.createGeometry(new Cesium.SphereGeometry({
  3293. radius: radius,
  3294. vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
  3295. stackPartitions: 64,
  3296. slicePartitions: 64
  3297. }));
  3298. var geometries = [
  3299. [sphereL4, 5],
  3300. [sphereL3, 200],
  3301. [sphereL2, 300],
  3302. [sphereL1, 500],
  3303. [sphereL0, 2000]
  3304. ];
  3305. var maxAvailableDistance = 10000000;
  3306. var i, j, mesh, lod;
  3307. var scale = new Cesium.Cartesian3(1, 1, 1);
  3308. for (j = 0; j < 1000; j++) {
  3309. lod = new LOD();
  3310. for (i = 0; i < geometries.length; i++) {
  3311. mesh = new Mesh(geometries[i][0], material);
  3312. mesh.scale = scale;
  3313. lod.addLevel(mesh, geometries[i][1] * 1000);
  3314. }
  3315. lod.maxAvailableDistance = maxAvailableDistance;
  3316. lod.position.x = 1500000 * (0.5 - Math.random());
  3317. lod.position.y = 1750000 * (0.5 - Math.random());
  3318. lod.position.z = 130000 * (0.5 - Math.random());
  3319. meshVisualizer.add(lod);
  3320. }
  3321. */
  3322. function LOD(options) {
  3323. options = defaultValue(options, {});
  3324. this.uuid = Cesium.createGuid();
  3325. this.show = defaultValue(options.show, true);
  3326. this.maxAvailableDistance = defaultValue(options.maxAvailableDistance, Number.MAX_VALUE);
  3327. this._position = defaultValue(options.position, new Cesium.Cartesian3(0, 0, 0));
  3328. this._scale = defaultValue(options.scale, new Cesium.Cartesian3(1, 1, 1));
  3329. this._rotation = defaultValue(options.rotation, { axis: new Cesium.Cartesian3(0, 0, 1), angle: 0 });
  3330. this._rotation = new Rotation(this._rotation.axis, this._rotation.angle);
  3331. this._boundingSphere = new Cesium.BoundingSphere();
  3332. this._needsUpdate = false;
  3333. this._modelMatrixNeedsUpdate = true;
  3334. this._modelMatrix = new Cesium.Matrix4();
  3335. Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY, this._modelMatrix);
  3336. this._onNeedUpdateChanged = function () {
  3337. this._modelMatrixNeedsUpdate = true;
  3338. };
  3339. this._rotation.paramChanged.removeEventListener(this._onNeedUpdateChanged);
  3340. this._children = [];
  3341. this._parent = null;
  3342. this.type = 'LOD';
  3343. Object.defineProperties(this, {
  3344. levels: {
  3345. enumerable: true,
  3346. value: []
  3347. }
  3348. });
  3349. }
  3350. function removeByValue(arr, val) {
  3351. for (var i = 0; i < arr.length; i++) {
  3352. if (arr[i] == val) {
  3353. arr.splice(i, 1);
  3354. break;
  3355. }
  3356. }
  3357. }
  3358. LOD.prototype = {
  3359. constructor: LOD,
  3360. /**
  3361. *
  3362. *@param {Number}x
  3363. *@param {Number}y
  3364. *@param {Number}z
  3365. */
  3366. setPosition: function (x, y, z) {
  3367. var changed = false;
  3368. if (arguments.length == 1) {
  3369. if (typeof x == 'number') {
  3370. if (x != this._position.x) changed = true;
  3371. this._position.x = x;
  3372. } else if (x instanceof Cesium.Cartesian3) {
  3373. if (x != this._position.x
  3374. || y != this._position.y
  3375. || z != this._position.z) {
  3376. changed = true;
  3377. }
  3378. this._position.x = x.x;
  3379. this._position.y = x.y;
  3380. this._position.z = x.z;
  3381. }
  3382. }
  3383. if (arguments.length == 2 && typeof y == 'number') {
  3384. if (y != this._position.y) changed = true;
  3385. this._position.y = y;
  3386. }
  3387. if (arguments.length == 3 && typeof z == 'number') {
  3388. if (z != this._position.z) changed = true;
  3389. this._position.z = z;
  3390. }
  3391. if (changed) {
  3392. this._modelMatrixNeedsUpdate = true;
  3393. }
  3394. },
  3395. /**
  3396. *
  3397. *@param {Number}x
  3398. *@param {Number}y
  3399. *@param {Number}z
  3400. */
  3401. setScale: function (x, y, z) {
  3402. var changed = false;
  3403. if (arguments.length == 1) {
  3404. if (typeof x == 'number') {
  3405. if (x != this._scale.x) changed = true;
  3406. this._scale.x = x;
  3407. } else if (x instanceof Cesium.Cartesian3) {
  3408. if (x != this._scale.x
  3409. || y != this._scale.y
  3410. || z != this._scale.z) {
  3411. changed = true;
  3412. }
  3413. this._scale.x = x.x;
  3414. this._scale.y = x.y;
  3415. this._scale.z = x.z;
  3416. }
  3417. }
  3418. if (arguments.length == 2 && typeof y == 'number') {
  3419. if (y != this._scale.y) changed = true;
  3420. this._scale.y = y;
  3421. }
  3422. if (arguments.length == 3 && typeof z == 'number') {
  3423. if (z != this._scale.z) changed = true;
  3424. this._scale.z = z;
  3425. }
  3426. if (changed) {
  3427. this._modelMatrixNeedsUpdate = true;
  3428. }
  3429. },
  3430. /**
  3431. *@param {Cesium.Mesh}mesh
  3432. *@param {Number}distance
  3433. */
  3434. addLevel: function (object, distance) {
  3435. if (distance === undefined) distance = 0;
  3436. distance = Math.abs(distance);
  3437. var levels = this.levels;
  3438. for (var l = 0; l < levels.length; l++) {
  3439. if (distance < levels[l].distance) {
  3440. break;
  3441. }
  3442. }
  3443. levels.splice(l, 0, { distance: distance, object: object });
  3444. object.parent = this;
  3445. this._children.push(object);
  3446. if (this.levels[0].object.geometry) {
  3447. this._boundingSphere.radius = this.levels[0].object.geometry.boundingSphere.radius;
  3448. } else if (this.levels[0].object.boundingSphere) {
  3449. this._boundingSphere.radius = this.levels[0].object.boundingSphere.radius;
  3450. }
  3451. },
  3452. update: function () {
  3453. var actualPosition = new Cesium.Cartesian3();
  3454. return function update(parentModelMatrix, frameState) {
  3455. var levels = this.levels;
  3456. if (levels.length > 1) {
  3457. if (this._modelMatrixNeedsUpdate) {
  3458. RendererUtils.computeModelMatrix(
  3459. parentModelMatrix,
  3460. this.position,
  3461. this.rotation,
  3462. this.scale,
  3463. this.modelMatrix
  3464. );
  3465. this._modelMatrixNeedsUpdate = false;
  3466. }
  3467. Cesium.Matrix4.getTranslation(this.modelMatrix, actualPosition);
  3468. Cesium.Cartesian3.clone(actualPosition, this._boundingSphere.center);
  3469. var bs = this._boundingSphere;
  3470. var distance = Math.max(0.0, Cesium.Cartesian3.distance(bs.center, frameState.camera.positionWC) - bs.radius);
  3471. var show = this.maxAvailableDistance > distance;
  3472. show = show && frameState.cullingVolume.computeVisibility(this._boundingSphere) !== Cesium.Intersect.OUTSIDE;
  3473. levels[0].object.show = show;
  3474. for (var i = 1, l = levels.length; i < l; i++) {
  3475. if (distance >= levels[i].distance) {
  3476. levels[i - 1].object.show = false;
  3477. levels[i].object.show = show;
  3478. } else {
  3479. break;
  3480. }
  3481. }
  3482. for (; i < l; i++) {
  3483. levels[i].object.show = false;
  3484. }
  3485. }
  3486. };
  3487. }(),
  3488. getObjectForDistance: function (distance) {
  3489. var levels = this.levels;
  3490. for (var i = 1, l = levels.length; i < l; i++) {
  3491. if (distance < levels[i].distance) {
  3492. break;
  3493. }
  3494. }
  3495. return levels[i - 1].object;
  3496. }
  3497. };
  3498. Object.defineProperties(LOD.prototype, {
  3499. modelMatrix: {
  3500. get: function () {
  3501. return this._modelMatrix;
  3502. }
  3503. },
  3504. parent: {
  3505. get: function () {
  3506. return this._parent;
  3507. },
  3508. set: function (val) {
  3509. if (val && ((val._children && Array.isArray(val._children)) || (val.children && Array.isArray(val.children)))) {
  3510. if (this._parent && this._parent != val) {
  3511. var children = this._parent._children ? this._parent._children : this._parent.children;
  3512. if (Array.isArray(children)) {
  3513. removeByValue(children, this);
  3514. }
  3515. }
  3516. this._parent = val;
  3517. if (typeof this._parent.add === 'function') {
  3518. this._parent.add(this);
  3519. } else {
  3520. var children = val._children ? val._children : val.children;
  3521. children.push(this);
  3522. }
  3523. }
  3524. this._needsUpdate = true;
  3525. }
  3526. },
  3527. children: {
  3528. get: function () {
  3529. return this._children;
  3530. },
  3531. set: function (val) {
  3532. this._children = val;
  3533. this._needsUpdate = true;
  3534. }
  3535. },
  3536. needsUpdate: {
  3537. get: function () {
  3538. return this._needsUpdate;
  3539. },
  3540. set: function (val) {
  3541. this._needsUpdate = val;
  3542. }
  3543. },
  3544. rotation: {
  3545. get: function () {
  3546. return this._rotation;
  3547. },
  3548. set: function (val) {
  3549. if (val != this._rotation) {
  3550. this._rotation = val;
  3551. this._needUpdate = true;
  3552. }
  3553. this._rotation.paramChanged.removeEventListener(this._onNeedUpdateChanged);
  3554. this._rotation = val;
  3555. this._rotation.paramChanged.addEventListener(this._onNeedUpdateChanged);
  3556. }
  3557. },
  3558. position: {
  3559. get: function () {
  3560. return this._position;
  3561. },
  3562. set: function (val) {
  3563. if (val.x != this._position.x || val.y != this._position.y || val.z != this._position.z) {
  3564. this._position = val;
  3565. this._needsUpdate = true;
  3566. }
  3567. this._position = val;
  3568. }
  3569. },
  3570. scale: {
  3571. get: function () {
  3572. return this._scale;
  3573. },
  3574. set: function (val) {
  3575. if (val.x != this._scale.x || val.y != this._scale.y || val.z != this._scale.z) {
  3576. this._scale = val;
  3577. this._needsUpdate = true;
  3578. }
  3579. this._scale = val;
  3580. }
  3581. }
  3582. });
  3583. return LOD;
  3584. });
  3585. define('Core/ArrowGeometry',[
  3586. 'Core/GeometryUtils'
  3587. ], function (
  3588. GeometryUtils
  3589. ) {
  3590. /**
  3591. *
  3592. <pre><code>
  3593. +
  3594. + + |
  3595. + + headLength
  3596. + + |
  3597. ++++headWidth++++
  3598. + + |
  3599. + + |
  3600. + + |
  3601. + + length
  3602. + + |
  3603. + + |
  3604. + + |
  3605. ++++
  3606. width
  3607. </code> </pre>
  3608. *@param {Object}[options]
  3609. *@param {Number}[options.length=50000]
  3610. *@param {Number}[options.width=250]
  3611. *@param {Number}[options.headLength=5000]
  3612. *@param {Number}[options.headWidth=1000]
  3613. *@param {Boolean}[options.reverse=false]
  3614. *
  3615. *@property {Number}length
  3616. *@property {Number}width
  3617. *@property {Number}headLength
  3618. *@property {Number}headWidth
  3619. *@property {Boolean}reverse
  3620. *
  3621. *@constructor
  3622. *@memberof Cesium
  3623. */
  3624. function ArrowGeometry(options) {
  3625. options = Cesium.defaultValue(options, {});
  3626. this.length = Cesium.defaultValue(options.length, 50000);
  3627. this.width = Cesium.defaultValue(options.width, 125);
  3628. this.headLength = Cesium.defaultValue(options.headLength, 5000);
  3629. this.headWidth = Cesium.defaultValue(options.headWidth, 1000);
  3630. this.reverse = Cesium.defaultValue(options.reverse, false);
  3631. }
  3632. /**
  3633. *
  3634. *@param {Cesium.ArrowGeometry}
  3635. *@return {Cesium.Geometry}
  3636. */
  3637. ArrowGeometry.createGeometry = function (arrowGeometry) {
  3638. var length = arrowGeometry.length;
  3639. var width = arrowGeometry.width;
  3640. var headLength = arrowGeometry.headLength;
  3641. var headWidth = arrowGeometry.headWidth;
  3642. var reverse = arrowGeometry.reverse;
  3643. var line = Cesium.CylinderGeometry.createGeometry(new Cesium.CylinderGeometry({
  3644. length: length,
  3645. topRadius: width,
  3646. bottomRadius: width,
  3647. }));
  3648. var arrow;
  3649. if (reverse) {
  3650. arrow = Cesium.CylinderGeometry.createGeometry(new Cesium.CylinderGeometry({
  3651. length: headLength,
  3652. topRadius: headWidth,
  3653. bottomRadius: 0,
  3654. }));
  3655. GeometryUtils.translate(arrow, [0, 0, -(length + headLength) / 2]);
  3656. } else {
  3657. arrow = Cesium.CylinderGeometry.createGeometry(new Cesium.CylinderGeometry({
  3658. length: headLength,
  3659. topRadius: 0,
  3660. bottomRadius: headWidth,
  3661. }));
  3662. GeometryUtils.translate(arrow, [0, 0, (length + headLength) / 2]);
  3663. }
  3664. var lineWithArrow = GeometryUtils.mergeGeometries([line, arrow]);
  3665. return lineWithArrow;
  3666. }
  3667. return ArrowGeometry;
  3668. });
  3669. define('Core/PlaneGeometry',[],function () {
  3670. /**
  3671. *
  3672. <pre><code>
  3673. p1++++++++++++p4
  3674. + + +
  3675. + + +
  3676. + + +
  3677. + + +
  3678. + + +
  3679. p2++++++++++++p3
  3680. </code> </pre>
  3681. *@param {Object}options
  3682. *@param {Array<Number|Cesium.Cartesian3>}options.positions [p1,p2,p3,p4]或者[p1.x,p1.y,p1.z,p2.x,...,p4.z]
  3683. *
  3684. *@property {Array<Number|Cesium.Cartesian3>}positions
  3685. *
  3686. *@constructor
  3687. *@memberof Cesium
  3688. */
  3689. function PlaneGeometry(options) {//positions, widthSegments, heightSegments) {
  3690. this.type = 'PlaneGeometry';
  3691. if (!options || !options.positions) {
  3692. throw new Error("缺少positions参数");
  3693. }
  3694. if (options.positions.length != 4 && options.positions.length / 3 != 4) {
  3695. throw new Error("positions参数必须包含四个顶点的位置坐标");
  3696. }
  3697. this.positions = options.positions;
  3698. }
  3699. /**
  3700. *
  3701. *@param {Cesium.PlaneGeometry}
  3702. *@return {Cesium.Geometry}
  3703. */
  3704. PlaneGeometry.createGeometry = function (planeGeometry) {
  3705. var positions = planeGeometry.positions;
  3706. var positionsVal;
  3707. if (Array.isArray(positions)) {
  3708. if (positions[0] instanceof Cesium.Cartesian3) {
  3709. positionsVal = new Float32Array(12);
  3710. for (var i = 0; i < positions.length; i++) {
  3711. var p = positions[i];
  3712. positionsVal[i * 3] = p.x;
  3713. positionsVal[i * 3 + 1] = p.y;
  3714. positionsVal[i * 3 + 2] = p.z;
  3715. }
  3716. } else if (typeof positions[0] === 'number') {
  3717. positionsVal = new Float32Array(positionsVal);
  3718. } else {
  3719. throw new Error("positions参数有误");
  3720. }
  3721. } else {
  3722. throw new Error("positions参数必须是数组类型");
  3723. }
  3724. var indices = new Int32Array([0, 1, 3, 1, 2, 3]);
  3725. var attributes = {
  3726. position: new Cesium.GeometryAttribute({
  3727. componentDatatype: Cesium.ComponentDatatype.DOUBLE,
  3728. componentsPerAttribute: 3,
  3729. values: positions
  3730. })
  3731. };
  3732. var bs = Cesium.BoundingSphere.fromVertices(positions);
  3733. var geo = new Cesium.Geometry({
  3734. attributes: attributes,
  3735. indices: new Int32Array(indices),
  3736. primitiveType: Cesium.PrimitiveType.TRIANGLES,
  3737. boundingSphere: bs
  3738. });
  3739. return geo;
  3740. }
  3741. return PlaneGeometry
  3742. });
  3743. define('Core/ReferenceMesh',[
  3744. 'Core/ArrowGeometry',
  3745. 'Core/PlaneGeometry',
  3746. 'Core/Mesh',
  3747. 'Core/MeshMaterial',
  3748. 'Core/Rotation',
  3749. 'Core/RendererUtils'
  3750. ], function (
  3751. ArrowGeometry,
  3752. PlaneGeometry,
  3753. Mesh,
  3754. MeshMaterial,
  3755. Rotation,
  3756. RendererUtils
  3757. ) {
  3758. var defaultValue = Cesium.defaultValue;
  3759. /**
  3760. *
  3761. *@param {Object}[options]
  3762. *@param {Cesium.ArrowGeometry}[options.axisParameter]
  3763. *@param {Boolean}[options.show=true]
  3764. *@param {Cesium.Cartesian3}[options.position]
  3765. *@param {Cesium.VolumeRendering.Rotation}[options.rotation]
  3766. *@param {Cesium.Cartesian3}[options.scale]
  3767. *
  3768. *@property {Boolean}show
  3769. *@property {Cesium.Cartesian3}position
  3770. *@property {Cesium.Rotation}rotation
  3771. *@property {Cesium.Cartesian3}scale
  3772. *@property {Boolean}needUpdate
  3773. *
  3774. *@constructor
  3775. *@memberof Cesium
  3776. */
  3777. function ReferenceMesh(options) {
  3778. options = Cesium.defaultValue(options, {});
  3779. this._axisParameter = new ArrowGeometry(options.axisParameter);
  3780. this._axisParameterY = new ArrowGeometry(options.axisParameter);
  3781. this._axisParameterY.reverse = true;
  3782. var materialZ = new MeshMaterial({
  3783. defaultColor: "rgba(255,0,0,1)",
  3784. wireframe: false,
  3785. side: MeshMaterial.Sides.DOUBLE,
  3786. translucent: false,
  3787. });
  3788. var materialY = new MeshMaterial({
  3789. defaultColor: "rgba(0,255,0,1)",
  3790. wireframe: false,
  3791. side: MeshMaterial.Sides.DOUBLE,
  3792. translucent: true,
  3793. });
  3794. var materialX = new MeshMaterial({
  3795. defaultColor: "rgba(0,0,255,1)",
  3796. wireframe: false,
  3797. side: MeshMaterial.Sides.DOUBLE,
  3798. translucent: false,
  3799. });
  3800. var axisLine = ArrowGeometry.createGeometry(new ArrowGeometry(this._axisParameter));
  3801. var axisLineY = ArrowGeometry.createGeometry(new ArrowGeometry(this._axisParameterY));
  3802. var meshZ = new Mesh(axisLine, materialZ);
  3803. var meshY = new Mesh(axisLineY, materialY);
  3804. var meshX = new Mesh(axisLine, materialX);
  3805. meshZ.position.z = this._axisParameter.length / 2;
  3806. meshY.position.y = -this._axisParameter.length / 2;
  3807. meshY.rotation.axis.y = 1;
  3808. meshY.rotation.angle = -180;
  3809. meshX.position.x = this._axisParameter.length / 2;
  3810. meshX.rotation.axis.x = 1;
  3811. meshX.rotation.angle = -180;
  3812. meshX.parent = this;
  3813. meshY.parent = this;
  3814. meshZ.parent = this;
  3815. this._children = [meshX, meshY, meshZ];
  3816. this.x = meshX;
  3817. this.y = meshY;
  3818. this.z = meshZ;
  3819. this.uuid = Cesium.createGuid();
  3820. this.show = defaultValue(options.show, true);
  3821. this._position = defaultValue(options.position, new Cesium.Cartesian3(0, 0, 0));
  3822. this._scale = defaultValue(options.scale, new Cesium.Cartesian3(1, 1, 1));
  3823. this._rotation = defaultValue(options.rotation, { axis: new Cesium.Cartesian3(0, 0, 1), angle: 0 });
  3824. this._rotation = new Rotation(this._rotation.axis, this._rotation.angle);
  3825. this._needsUpdate = true;
  3826. this._modelMatrixNeedsUpdate = true;
  3827. this._modelMatrix = new Cesium.Matrix4();
  3828. Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY, this._modelMatrix);
  3829. this._onNeedUpdateChanged = function () {
  3830. this._modelMatrixNeedsUpdate = true;
  3831. };
  3832. this._rotation.paramChanged.removeEventListener(this._onNeedUpdateChanged);
  3833. this._parent = null;
  3834. }
  3835. function removeByValue(arr, val) {
  3836. for (var i = 0; i < arr.length; i++) {
  3837. if (arr[i] == val) {
  3838. arr.splice(i, 1);
  3839. break;
  3840. }
  3841. }
  3842. }
  3843. Object.defineProperties(ReferenceMesh.prototype, {
  3844. modelMatrix: {
  3845. get: function () {
  3846. return this._modelMatrix;
  3847. }
  3848. },
  3849. parent: {
  3850. get: function () {
  3851. return this._parent;
  3852. },
  3853. set: function (val) {
  3854. if (val && ((val._children && Array.isArray(val._children)) || (val.children && Array.isArray(val.children)))) {
  3855. if (this._parent && this._parent != val) {
  3856. var children = this._parent._children ? this._parent._children : this._parent.children;
  3857. if (Array.isArray(children)) {
  3858. removeByValue(children, this);
  3859. }
  3860. }
  3861. this._parent = val;
  3862. if (typeof this._parent.add === 'function') {
  3863. this._parent.add(this);
  3864. } else {
  3865. var children = val._children ? val._children : val.children;
  3866. children.push(this);
  3867. }
  3868. }
  3869. this.modelMatrixNeedsUpdate = true;
  3870. }
  3871. },
  3872. modelMatrixNeedsUpdate: {
  3873. get: function () {
  3874. return this._modelMatrixNeedsUpdate;
  3875. },
  3876. set: function (val) {
  3877. this._modelMatrixNeedsUpdate = val;
  3878. if (this._modelMatrixNeedsUpdate) {
  3879. Mesh.traverse(this, function (mesh) {
  3880. mesh._modelMatrixNeedsUpdate = val;
  3881. });
  3882. }
  3883. }
  3884. },
  3885. children: {
  3886. get: function () {
  3887. return this._children;
  3888. }
  3889. },
  3890. needsUpdate: {
  3891. get: function () {
  3892. return this._needsUpdate;
  3893. },
  3894. set: function (val) {
  3895. this._needsUpdate = val;
  3896. }
  3897. },
  3898. rotation: {
  3899. get: function () {
  3900. return this._rotation;
  3901. },
  3902. set: function (val) {
  3903. if (val != this._rotation) {
  3904. this._rotation = val;
  3905. this.modelMatrixNeedsUpdate = true;
  3906. }
  3907. this._rotation.paramChanged.removeEventListener(this._onNeedUpdateChanged);
  3908. this._rotation = val;
  3909. this._rotation.paramChanged.addEventListener(this._onNeedUpdateChanged);
  3910. }
  3911. },
  3912. position: {
  3913. get: function () {
  3914. return this._position;
  3915. },
  3916. set: function (val) {
  3917. if (val.x != this._position.x || val.y != this._position.y || val.z != this._position.z) {
  3918. this._position = val;
  3919. this.modelMatrixNeedsUpdate = true;
  3920. }
  3921. this._position = val;
  3922. }
  3923. },
  3924. scale: {
  3925. get: function () {
  3926. return this._scale;
  3927. },
  3928. set: function (val) {
  3929. if (val.x != this._scale.x || val.y != this._scale.y || val.z != this._scale.z) {
  3930. this._scale = val;
  3931. this.modelMatrixNeedsUpdate = true;
  3932. }
  3933. this._scale = val;
  3934. }
  3935. }
  3936. });
  3937. /**
  3938. *
  3939. *@param {Cesium.Matrix4}meshVisulizerModelMatrix
  3940. *@param {Cesium.FrameState}frameState
  3941. */
  3942. ReferenceMesh.prototype.update = function (parentModelMatrix, frameState) {
  3943. if (this._modelMatrixNeedsUpdate || this._needsUpdate) {
  3944. RendererUtils.computeModelMatrix(
  3945. parentModelMatrix,
  3946. this.position,
  3947. this.rotation,
  3948. this.scale,
  3949. this.modelMatrix
  3950. );
  3951. this._modelMatrixNeedsUpdate = false;
  3952. }
  3953. }
  3954. return ReferenceMesh;
  3955. });
  3956. /* This Source Code Form is subject to the terms of the Mozilla Public
  3957. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3958. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  3959. function TIFFParser() {
  3960. this.tiffDataView = undefined;
  3961. this.littleEndian = undefined;
  3962. this.fileDirectories = [];
  3963. };
  3964. TIFFParser.prototype = {
  3965. isLittleEndian: function () {
  3966. // Get byte order mark.
  3967. var BOM = this.getBytes(2, 0);
  3968. // Find out the endianness.
  3969. if (BOM === 0x4949) {
  3970. this.littleEndian = true;
  3971. } else if (BOM === 0x4D4D) {
  3972. this.littleEndian = false;
  3973. } else {
  3974. console.log( BOM );
  3975. throw TypeError("Invalid byte order value.");
  3976. }
  3977. return this.littleEndian;
  3978. },
  3979. hasTowel: function () {
  3980. // Check for towel.
  3981. if (this.getBytes(2, 2) !== 42) {
  3982. throw RangeError("You forgot your towel!");
  3983. return false;
  3984. }
  3985. return true;
  3986. },
  3987. getFieldTagName: function (fieldTag) {
  3988. // See: http://www.digitizationguidelines.gov/guidelines/TIFF_Metadata_Final.pdf
  3989. // See: http://www.digitalpreservation.gov/formats/content/tiff_tags.shtml
  3990. var fieldTagNames = {
  3991. // TIFF Baseline
  3992. 0x013B: 'Artist',
  3993. 0x0102: 'BitsPerSample',
  3994. 0x0109: 'CellLength',
  3995. 0x0108: 'CellWidth',
  3996. 0x0140: 'ColorMap',
  3997. 0x0103: 'Compression',
  3998. 0x8298: 'Copyright',
  3999. 0x0132: 'DateTime',
  4000. 0x0152: 'ExtraSamples',
  4001. 0x010A: 'FillOrder',
  4002. 0x0121: 'FreeByteCounts',
  4003. 0x0120: 'FreeOffsets',
  4004. 0x0123: 'GrayResponseCurve',
  4005. 0x0122: 'GrayResponseUnit',
  4006. 0x013C: 'HostComputer',
  4007. 0x010E: 'ImageDescription',
  4008. 0x0101: 'ImageLength',
  4009. 0x0100: 'ImageWidth',
  4010. 0x010F: 'Make',
  4011. 0x0119: 'MaxSampleValue',
  4012. 0x0118: 'MinSampleValue',
  4013. 0x0110: 'Model',
  4014. 0x00FE: 'NewSubfileType',
  4015. 0x0112: 'Orientation',
  4016. 0x0106: 'PhotometricInterpretation',
  4017. 0x011C: 'PlanarConfiguration',
  4018. 0x0128: 'ResolutionUnit',
  4019. 0x0116: 'RowsPerStrip',
  4020. 0x0115: 'SamplesPerPixel',
  4021. 0x0131: 'Software',
  4022. 0x0117: 'StripByteCounts',
  4023. 0x0111: 'StripOffsets',
  4024. 0x00FF: 'SubfileType',
  4025. 0x0107: 'Threshholding',
  4026. 0x011A: 'XResolution',
  4027. 0x011B: 'YResolution',
  4028. // TIFF Extended
  4029. 0x0146: 'BadFaxLines',
  4030. 0x0147: 'CleanFaxData',
  4031. 0x0157: 'ClipPath',
  4032. 0x0148: 'ConsecutiveBadFaxLines',
  4033. 0x01B1: 'Decode',
  4034. 0x01B2: 'DefaultImageColor',
  4035. 0x010D: 'DocumentName',
  4036. 0x0150: 'DotRange',
  4037. 0x0141: 'HalftoneHints',
  4038. 0x015A: 'Indexed',
  4039. 0x015B: 'JPEGTables',
  4040. 0x011D: 'PageName',
  4041. 0x0129: 'PageNumber',
  4042. 0x013D: 'Predictor',
  4043. 0x013F: 'PrimaryChromaticities',
  4044. 0x0214: 'ReferenceBlackWhite',
  4045. 0x0153: 'SampleFormat',
  4046. 0x022F: 'StripRowCounts',
  4047. 0x014A: 'SubIFDs',
  4048. 0x0124: 'T4Options',
  4049. 0x0125: 'T6Options',
  4050. 0x0145: 'TileByteCounts',
  4051. 0x0143: 'TileLength',
  4052. 0x0144: 'TileOffsets',
  4053. 0x0142: 'TileWidth',
  4054. 0x012D: 'TransferFunction',
  4055. 0x013E: 'WhitePoint',
  4056. 0x0158: 'XClipPathUnits',
  4057. 0x011E: 'XPosition',
  4058. 0x0211: 'YCbCrCoefficients',
  4059. 0x0213: 'YCbCrPositioning',
  4060. 0x0212: 'YCbCrSubSampling',
  4061. 0x0159: 'YClipPathUnits',
  4062. 0x011F: 'YPosition',
  4063. // EXIF
  4064. 0x9202: 'ApertureValue',
  4065. 0xA001: 'ColorSpace',
  4066. 0x9004: 'DateTimeDigitized',
  4067. 0x9003: 'DateTimeOriginal',
  4068. 0x8769: 'Exif IFD',
  4069. 0x9000: 'ExifVersion',
  4070. 0x829A: 'ExposureTime',
  4071. 0xA300: 'FileSource',
  4072. 0x9209: 'Flash',
  4073. 0xA000: 'FlashpixVersion',
  4074. 0x829D: 'FNumber',
  4075. 0xA420: 'ImageUniqueID',
  4076. 0x9208: 'LightSource',
  4077. 0x927C: 'MakerNote',
  4078. 0x9201: 'ShutterSpeedValue',
  4079. 0x9286: 'UserComment',
  4080. // IPTC
  4081. 0x83BB: 'IPTC',
  4082. // ICC
  4083. 0x8773: 'ICC Profile',
  4084. // XMP
  4085. 0x02BC: 'XMP',
  4086. // GDAL
  4087. 0xA480: 'GDAL_METADATA',
  4088. 0xA481: 'GDAL_NODATA',
  4089. // Photoshop
  4090. 0x8649: 'Photoshop',
  4091. };
  4092. var fieldTagName;
  4093. if (fieldTag in fieldTagNames) {
  4094. fieldTagName = fieldTagNames[fieldTag];
  4095. } else {
  4096. //console.log( "Unknown Field Tag:", fieldTag);
  4097. fieldTagName = "Tag" + fieldTag;
  4098. }
  4099. return fieldTagName;
  4100. },
  4101. getFieldTypeName: function (fieldType) {
  4102. var fieldTypeNames = {
  4103. 0x0001: 'BYTE',
  4104. 0x0002: 'ASCII',
  4105. 0x0003: 'SHORT',
  4106. 0x0004: 'LONG',
  4107. 0x0005: 'RATIONAL',
  4108. 0x0006: 'SBYTE',
  4109. 0x0007: 'UNDEFINED',
  4110. 0x0008: 'SSHORT',
  4111. 0x0009: 'SLONG',
  4112. 0x000A: 'SRATIONAL',
  4113. 0x000B: 'FLOAT',
  4114. 0x000C: 'DOUBLE',
  4115. };
  4116. var fieldTypeName;
  4117. if (fieldType in fieldTypeNames) {
  4118. fieldTypeName = fieldTypeNames[fieldType];
  4119. }
  4120. return fieldTypeName;
  4121. },
  4122. getFieldTypeLength: function (fieldTypeName) {
  4123. var fieldTypeLength;
  4124. if (['BYTE', 'ASCII', 'SBYTE', 'UNDEFINED'].indexOf(fieldTypeName) !== -1) {
  4125. fieldTypeLength = 1;
  4126. } else if (['SHORT', 'SSHORT'].indexOf(fieldTypeName) !== -1) {
  4127. fieldTypeLength = 2;
  4128. } else if (['LONG', 'SLONG', 'FLOAT'].indexOf(fieldTypeName) !== -1) {
  4129. fieldTypeLength = 4;
  4130. } else if (['RATIONAL', 'SRATIONAL', 'DOUBLE'].indexOf(fieldTypeName) !== -1) {
  4131. fieldTypeLength = 8;
  4132. }
  4133. return fieldTypeLength;
  4134. },
  4135. getBits: function (numBits, byteOffset, bitOffset) {
  4136. bitOffset = bitOffset || 0;
  4137. var extraBytes = Math.floor(bitOffset / 8);
  4138. var newByteOffset = byteOffset + extraBytes;
  4139. var totalBits = bitOffset + numBits;
  4140. var shiftRight = 32 - numBits;
  4141. if (totalBits <= 0) {
  4142. console.log( numBits, byteOffset, bitOffset );
  4143. throw RangeError("No bits requested");
  4144. } else if (totalBits <= 8) {
  4145. var shiftLeft = 24 + bitOffset;
  4146. var rawBits = this.tiffDataView.getUint8(newByteOffset, this.littleEndian);
  4147. } else if (totalBits <= 16) {
  4148. var shiftLeft = 16 + bitOffset;
  4149. var rawBits = this.tiffDataView.getUint16(newByteOffset, this.littleEndian);
  4150. } else if (totalBits <= 32) {
  4151. var shiftLeft = bitOffset;
  4152. var rawBits = this.tiffDataView.getUint32(newByteOffset, this.littleEndian);
  4153. } else {
  4154. console.log( numBits, byteOffset, bitOffset );
  4155. throw RangeError("Too many bits requested");
  4156. }
  4157. var chunkInfo = {
  4158. 'bits': ((rawBits << shiftLeft) >>> shiftRight),
  4159. 'byteOffset': newByteOffset + Math.floor(totalBits / 8),
  4160. 'bitOffset': totalBits % 8,
  4161. };
  4162. return chunkInfo;
  4163. },
  4164. getBytes: function (numBytes, offset) {
  4165. if (numBytes <= 0) {
  4166. console.log( numBytes, offset );
  4167. throw RangeError("No bytes requested");
  4168. } else if (numBytes <= 1) {
  4169. return this.tiffDataView.getUint8(offset, this.littleEndian);
  4170. } else if (numBytes <= 2) {
  4171. return this.tiffDataView.getUint16(offset, this.littleEndian);
  4172. } else if (numBytes <= 3) {
  4173. return this.tiffDataView.getUint32(offset, this.littleEndian) >>> 8;
  4174. } else if (numBytes <= 4) {
  4175. return this.tiffDataView.getUint32(offset, this.littleEndian);
  4176. } else {
  4177. console.log( numBytes, offset );
  4178. throw RangeError("Too many bytes requested");
  4179. }
  4180. },
  4181. getFieldValues: function (fieldTagName, fieldTypeName, typeCount, valueOffset) {
  4182. var fieldValues = [];
  4183. var fieldTypeLength = this.getFieldTypeLength(fieldTypeName);
  4184. var fieldValueSize = fieldTypeLength * typeCount;
  4185. if (fieldValueSize <= 4) {
  4186. // The value is stored at the big end of the valueOffset.
  4187. if (this.littleEndian === false) {
  4188. var value = valueOffset >>> ((4 - fieldTypeLength) * 8);
  4189. } else {
  4190. var value = valueOffset;
  4191. }
  4192. fieldValues.push(value);
  4193. } else {
  4194. for (var i = 0; i < typeCount; i++) {
  4195. var indexOffset = fieldTypeLength * i;
  4196. if (fieldTypeLength >= 8) {
  4197. if (['RATIONAL', 'SRATIONAL'].indexOf(fieldTypeName) !== -1) {
  4198. // Numerator
  4199. fieldValues.push(this.getBytes(4, valueOffset + indexOffset));
  4200. // Denominator
  4201. fieldValues.push(this.getBytes(4, valueOffset + indexOffset + 4));
  4202. // } else if (['DOUBLE'].indexOf(fieldTypeName) !== -1) {
  4203. // fieldValues.push(this.getBytes(4, valueOffset + indexOffset) + this.getBytes(4, valueOffset + indexOffset + 4));
  4204. } else {
  4205. console.log( fieldTypeName, typeCount, fieldValueSize );
  4206. throw TypeError("Can't handle this field type or size");
  4207. }
  4208. } else {
  4209. fieldValues.push(this.getBytes(fieldTypeLength, valueOffset + indexOffset));
  4210. }
  4211. }
  4212. }
  4213. if (fieldTypeName === 'ASCII') {
  4214. fieldValues.forEach(function(e, i, a) { a[i] = String.fromCharCode(e); });
  4215. }
  4216. return fieldValues;
  4217. },
  4218. clampColorSample: function(colorSample, bitsPerSample) {
  4219. var multiplier = Math.pow(2, 8 - bitsPerSample);
  4220. return Math.floor((colorSample * multiplier) + (multiplier - 1));
  4221. },
  4222. makeRGBAFillValue: function(r, g, b, a) {
  4223. if(typeof a === 'undefined') {
  4224. a = 1.0;
  4225. }
  4226. return "rgba(" + r + ", " + g + ", " + b + ", " + a + ")";
  4227. },
  4228. parseFileDirectory: function (byteOffset) {
  4229. var numDirEntries = this.getBytes(2, byteOffset);
  4230. var tiffFields = [];
  4231. for (var i = byteOffset + 2, entryCount = 0; entryCount < numDirEntries; i += 12, entryCount++) {
  4232. var fieldTag = this.getBytes(2, i);
  4233. var fieldType = this.getBytes(2, i + 2);
  4234. var typeCount = this.getBytes(4, i + 4);
  4235. var valueOffset = this.getBytes(4, i + 8);
  4236. var fieldTagName = this.getFieldTagName( fieldTag );
  4237. var fieldTypeName = this.getFieldTypeName( fieldType );
  4238. var fieldValues = this.getFieldValues(fieldTagName, fieldTypeName, typeCount, valueOffset);
  4239. tiffFields[fieldTagName] = { 'type': fieldTypeName, 'values': fieldValues };
  4240. }
  4241. this.fileDirectories.push( tiffFields );
  4242. var nextIFDByteOffset = this.getBytes(4, i);
  4243. if (nextIFDByteOffset === 0x00000000) {
  4244. return this.fileDirectories;
  4245. } else {
  4246. return this.parseFileDirectory(nextIFDByteOffset);
  4247. }
  4248. },
  4249. parseTIFF: function (tiffArrayBuffer, canvas) {
  4250. canvas = canvas || document.createElement('canvas');
  4251. this.tiffDataView = new DataView(tiffArrayBuffer);
  4252. this.canvas = canvas;
  4253. this.littleEndian = this.isLittleEndian(this.tiffDataView);
  4254. if (!this.hasTowel(this.tiffDataView, this.littleEndian)) {
  4255. return;
  4256. }
  4257. var firstIFDByteOffset = this.getBytes(4, 4);
  4258. this.fileDirectories = this.parseFileDirectory(firstIFDByteOffset);
  4259. var fileDirectory = this.fileDirectories[0];
  4260. //console.log( fileDirectory );
  4261. var imageWidth = fileDirectory.ImageWidth.values[0];
  4262. var imageLength = fileDirectory.ImageLength.values[0];
  4263. this.canvas.width = imageWidth;
  4264. this.canvas.height = imageLength;
  4265. var strips = [];
  4266. var compression = (fileDirectory.Compression) ? fileDirectory.Compression.values[0] : 1;
  4267. var samplesPerPixel = fileDirectory.SamplesPerPixel.values[0];
  4268. var sampleProperties = [];
  4269. var bitsPerPixel = 0;
  4270. var hasBytesPerPixel = false;
  4271. fileDirectory.BitsPerSample.values.forEach(function(bitsPerSample, i, bitsPerSampleValues) {
  4272. sampleProperties[i] = {
  4273. 'bitsPerSample': bitsPerSample,
  4274. 'hasBytesPerSample': false,
  4275. 'bytesPerSample': undefined,
  4276. };
  4277. if ((bitsPerSample % 8) === 0) {
  4278. sampleProperties[i].hasBytesPerSample = true;
  4279. sampleProperties[i].bytesPerSample = bitsPerSample / 8;
  4280. }
  4281. bitsPerPixel += bitsPerSample;
  4282. }, this);
  4283. if ((bitsPerPixel % 8) === 0) {
  4284. hasBytesPerPixel = true;
  4285. var bytesPerPixel = bitsPerPixel / 8;
  4286. }
  4287. var stripOffsetValues = fileDirectory.StripOffsets.values;
  4288. var numStripOffsetValues = stripOffsetValues.length;
  4289. // StripByteCounts is supposed to be required, but see if we can recover anyway.
  4290. if (fileDirectory.StripByteCounts) {
  4291. var stripByteCountValues = fileDirectory.StripByteCounts.values;
  4292. } else {
  4293. console.log("Missing StripByteCounts!");
  4294. // Infer StripByteCounts, if possible.
  4295. if (numStripOffsetValues === 1) {
  4296. var stripByteCountValues = [Math.ceil((imageWidth * imageLength * bitsPerPixel) / 8)];
  4297. } else {
  4298. throw Error("Cannot recover from missing StripByteCounts");
  4299. }
  4300. }
  4301. // Loop through strips and decompress as necessary.
  4302. for (var i = 0; i < numStripOffsetValues; i++) {
  4303. var stripOffset = stripOffsetValues[i];
  4304. strips[i] = [];
  4305. var stripByteCount = stripByteCountValues[i];
  4306. // Loop through pixels.
  4307. for (var byteOffset = 0, bitOffset = 0, jIncrement = 1, getHeader = true, pixel = [], numBytes = 0, sample = 0, currentSample = 0; byteOffset < stripByteCount; byteOffset += jIncrement) {
  4308. // Decompress strip.
  4309. switch (compression) {
  4310. // Uncompressed
  4311. case 1:
  4312. // Loop through samples (sub-pixels).
  4313. for (var m = 0, pixel = []; m < samplesPerPixel; m++) {
  4314. if (sampleProperties[m].hasBytesPerSample) {
  4315. // XXX: This is wrong!
  4316. var sampleOffset = sampleProperties[m].bytesPerSample * m;
  4317. pixel.push(this.getBytes(sampleProperties[m].bytesPerSample, stripOffset + byteOffset + sampleOffset));
  4318. } else {
  4319. var sampleInfo = this.getBits(sampleProperties[m].bitsPerSample, stripOffset + byteOffset, bitOffset);
  4320. pixel.push(sampleInfo.bits);
  4321. byteOffset = sampleInfo.byteOffset - stripOffset;
  4322. bitOffset = sampleInfo.bitOffset;
  4323. throw RangeError("Cannot handle sub-byte bits per sample");
  4324. }
  4325. }
  4326. strips[i].push(pixel);
  4327. if (hasBytesPerPixel) {
  4328. jIncrement = bytesPerPixel;
  4329. } else {
  4330. jIncrement = 0;
  4331. throw RangeError("Cannot handle sub-byte bits per pixel");
  4332. }
  4333. break;
  4334. // CITT Group 3 1-Dimensional Modified Huffman run-length encoding
  4335. case 2:
  4336. // XXX: Use PDF.js code?
  4337. break;
  4338. // Group 3 Fax
  4339. case 3:
  4340. // XXX: Use PDF.js code?
  4341. break;
  4342. // Group 4 Fax
  4343. case 4:
  4344. // XXX: Use PDF.js code?
  4345. break;
  4346. // LZW
  4347. case 5:
  4348. // XXX: Use PDF.js code?
  4349. break;
  4350. // Old-style JPEG (TIFF 6.0)
  4351. case 6:
  4352. // XXX: Use PDF.js code?
  4353. break;
  4354. // New-style JPEG (TIFF Specification Supplement 2)
  4355. case 7:
  4356. // XXX: Use PDF.js code?
  4357. break;
  4358. // PackBits
  4359. case 32773:
  4360. // Are we ready for a new block?
  4361. if (getHeader) {
  4362. getHeader = false;
  4363. var blockLength = 1;
  4364. var iterations = 1;
  4365. // The header byte is signed.
  4366. var header = this.tiffDataView.getInt8(stripOffset + byteOffset, this.littleEndian);
  4367. if ((header >= 0) && (header <= 127)) { // Normal pixels.
  4368. blockLength = header + 1;
  4369. } else if ((header >= -127) && (header <= -1)) { // Collapsed pixels.
  4370. iterations = -header + 1;
  4371. } else /*if (header === -128)*/ { // Placeholder byte?
  4372. getHeader = true;
  4373. }
  4374. } else {
  4375. var currentByte = this.getBytes(1, stripOffset + byteOffset);
  4376. // Duplicate bytes, if necessary.
  4377. for (var m = 0; m < iterations; m++) {
  4378. if (sampleProperties[sample].hasBytesPerSample) {
  4379. // We're reading one byte at a time, so we need to handle multi-byte samples.
  4380. currentSample = (currentSample << (8 * numBytes)) | currentByte;
  4381. numBytes++;
  4382. // Is our sample complete?
  4383. if (numBytes === sampleProperties[sample].bytesPerSample) {
  4384. pixel.push(currentSample);
  4385. currentSample = numBytes = 0;
  4386. sample++;
  4387. }
  4388. } else {
  4389. throw RangeError("Cannot handle sub-byte bits per sample");
  4390. }
  4391. // Is our pixel complete?
  4392. if (sample === samplesPerPixel)
  4393. {
  4394. strips[i].push(pixel);
  4395. pixel = [];
  4396. sample = 0;
  4397. }
  4398. }
  4399. blockLength--;
  4400. // Is our block complete?
  4401. if (blockLength === 0) {
  4402. getHeader = true;
  4403. }
  4404. }
  4405. jIncrement = 1;
  4406. break;
  4407. // Unknown compression algorithm
  4408. default:
  4409. // Do not attempt to parse the image data.
  4410. break;
  4411. }
  4412. }
  4413. // console.log( strips[i] );
  4414. }
  4415. // console.log( strips );
  4416. if (canvas.getContext) {
  4417. var ctx = this.canvas.getContext("2d");
  4418. // Set a default fill style.
  4419. ctx.fillStyle = this.makeRGBAFillValue(255, 255, 255, 0);
  4420. // If RowsPerStrip is missing, the whole image is in one strip.
  4421. if (fileDirectory.RowsPerStrip) {
  4422. var rowsPerStrip = fileDirectory.RowsPerStrip.values[0];
  4423. } else {
  4424. var rowsPerStrip = imageLength;
  4425. }
  4426. var numStrips = strips.length;
  4427. var imageLengthModRowsPerStrip = imageLength % rowsPerStrip;
  4428. var rowsInLastStrip = (imageLengthModRowsPerStrip === 0) ? rowsPerStrip : imageLengthModRowsPerStrip;
  4429. var numRowsInStrip = rowsPerStrip;
  4430. var numRowsInPreviousStrip = 0;
  4431. var photometricInterpretation = fileDirectory.PhotometricInterpretation.values[0];
  4432. var extraSamplesValues = [];
  4433. var numExtraSamples = 0;
  4434. if (fileDirectory.ExtraSamples) {
  4435. extraSamplesValues = fileDirectory.ExtraSamples.values;
  4436. numExtraSamples = extraSamplesValues.length;
  4437. }
  4438. if (fileDirectory.ColorMap) {
  4439. var colorMapValues = fileDirectory.ColorMap.values;
  4440. var colorMapSampleSize = Math.pow(2, sampleProperties[0].bitsPerSample);
  4441. }
  4442. // Loop through the strips in the image.
  4443. for (var i = 0; i < numStrips; i++) {
  4444. // The last strip may be short.
  4445. if ((i + 1) === numStrips) {
  4446. numRowsInStrip = rowsInLastStrip;
  4447. }
  4448. var numPixels = strips[i].length;
  4449. var yPadding = numRowsInPreviousStrip * i;
  4450. // Loop through the rows in the strip.
  4451. for (var y = 0, j = 0; y < numRowsInStrip, j < numPixels; y++) {
  4452. // Loop through the pixels in the row.
  4453. for (var x = 0; x < imageWidth; x++, j++) {
  4454. var pixelSamples = strips[i][j];
  4455. var red = 0;
  4456. var green = 0;
  4457. var blue = 0;
  4458. var opacity = 1.0;
  4459. if (numExtraSamples > 0) {
  4460. for (var k = 0; k < numExtraSamples; k++) {
  4461. if (extraSamplesValues[k] === 1 || extraSamplesValues[k] === 2) {
  4462. // Clamp opacity to the range [0,1].
  4463. opacity = pixelSamples[3 + k] / 256;
  4464. break;
  4465. }
  4466. }
  4467. }
  4468. switch (photometricInterpretation) {
  4469. // Bilevel or Grayscale
  4470. // WhiteIsZero
  4471. case 0:
  4472. if (sampleProperties[0].hasBytesPerSample) {
  4473. var invertValue = Math.pow(0x10, sampleProperties[0].bytesPerSample * 2);
  4474. }
  4475. // Invert samples.
  4476. pixelSamples.forEach(function(sample, index, samples) { samples[index] = invertValue - sample; });
  4477. // Bilevel or Grayscale
  4478. // BlackIsZero
  4479. case 1:
  4480. red = green = blue = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
  4481. break;
  4482. // RGB Full Color
  4483. case 2:
  4484. red = this.clampColorSample(pixelSamples[0], sampleProperties[0].bitsPerSample);
  4485. green = this.clampColorSample(pixelSamples[1], sampleProperties[1].bitsPerSample);
  4486. blue = this.clampColorSample(pixelSamples[2], sampleProperties[2].bitsPerSample);
  4487. break;
  4488. // RGB Color Palette
  4489. case 3:
  4490. if (colorMapValues === undefined) {
  4491. throw Error("Palette image missing color map");
  4492. }
  4493. var colorMapIndex = pixelSamples[0];
  4494. red = this.clampColorSample(colorMapValues[colorMapIndex], 16);
  4495. green = this.clampColorSample(colorMapValues[colorMapSampleSize + colorMapIndex], 16);
  4496. blue = this.clampColorSample(colorMapValues[(2 * colorMapSampleSize) + colorMapIndex], 16);
  4497. break;
  4498. // Transparency mask
  4499. case 4:
  4500. throw RangeError( 'Not Yet Implemented: Transparency mask' );
  4501. break;
  4502. // CMYK
  4503. case 5:
  4504. throw RangeError( 'Not Yet Implemented: CMYK' );
  4505. break;
  4506. // YCbCr
  4507. case 6:
  4508. throw RangeError( 'Not Yet Implemented: YCbCr' );
  4509. break;
  4510. // CIELab
  4511. case 8:
  4512. throw RangeError( 'Not Yet Implemented: CIELab' );
  4513. break;
  4514. // Unknown Photometric Interpretation
  4515. default:
  4516. throw RangeError( 'Unknown Photometric Interpretation:', photometricInterpretation );
  4517. break;
  4518. }
  4519. ctx.fillStyle = this.makeRGBAFillValue(red, green, blue, opacity);
  4520. ctx.fillRect(x, yPadding + y, 1, 1);
  4521. }
  4522. }
  4523. numRowsInPreviousStrip = numRowsInStrip;
  4524. }
  4525. }
  4526. /* for (var i = 0, numFileDirectories = this.fileDirectories.length; i < numFileDirectories; i++) {
  4527. // Stuff
  4528. }*/
  4529. return this.canvas;
  4530. },
  4531. }
  4532. if (typeof module === "undefined") {
  4533. this.TIFFParser = TIFFParser;
  4534. } else {
  4535. module.exports = TIFFParser;
  4536. }
  4537. if (typeof define === "function") {
  4538. define('ThirdParty/tiff-js/tiff',[],function () { return TIFFParser; });
  4539. }
  4540. ;
  4541. //define(function () {
  4542. /**
  4543. *@class
  4544. *@memberof Cesium
  4545. */
  4546. function Path() { }
  4547. /**
  4548. *
  4549. *获取文件扩展名后缀
  4550. *@param {String}fname 文件名
  4551. */
  4552. Path.GetExtension = function (fname) {
  4553. var start = fname.lastIndexOf(".");
  4554. if (start >= 0) {
  4555. return fname.substring(start, fname.length);
  4556. }
  4557. return "";
  4558. }
  4559. /**
  4560. *
  4561. *获取文件扩展名后缀
  4562. *@param {String}fname 文件名
  4563. */
  4564. Path.GetFileName = function (fname) {
  4565. var start = fname.lastIndexOf("/");
  4566. if (start < 0) {
  4567. return fname;
  4568. }
  4569. return fname.substring(start + 1, fname.length);
  4570. }
  4571. /**
  4572. *
  4573. *获取文件夹
  4574. *@param {String}fname 文件名
  4575. */
  4576. Path.GetDirectoryName = function (fname) {
  4577. var start = fname.lastIndexOf("/");
  4578. if (start < 0) {
  4579. return "";
  4580. }
  4581. return fname.substring(0, start);
  4582. }
  4583. /**
  4584. *
  4585. *获取文件夹
  4586. *@param {String}fname 文件名
  4587. */
  4588. Path.Combine = function (dir, fname) {
  4589. return dir + fname;
  4590. }
  4591. Path.ChangeExtension = function (fname, newExt) {
  4592. return fname.replace(Path.GetExtension(fname), newExt);
  4593. }
  4594. // return Path;
  4595. //});
  4596. if (typeof module === "undefined") {
  4597. this.Path = Path;
  4598. } else {
  4599. module.exports = Path;
  4600. }
  4601. if (typeof define === "function") {
  4602. define('Util/Path',[],function () { return Path; });
  4603. }
  4604. ;
  4605. define('Core/Shaders/ShaderLib',[
  4606. 'Core/Shaders/ShaderChunk'
  4607. ], function (
  4608. ShaderChunk
  4609. ) {
  4610. /**
  4611. * Uniforms library for shared webgl shaders
  4612. */
  4613. var UniformsLib = {
  4614. common: {
  4615. diffuse: { value: new Cesium.Color(0xeeeeee) },
  4616. opacity: { value: 1.0 },
  4617. map: { value: null },
  4618. offsetRepeat: { value: new Cesium.Cartesian4(0, 0, 1, 1) },
  4619. specularMap: { value: null },
  4620. alphaMap: { value: null },
  4621. envMap: { value: null },
  4622. flipEnvMap: { value: -1 },
  4623. reflectivity: { value: 1.0 },
  4624. refractionRatio: { value: 0.98 }
  4625. },
  4626. aomap: {
  4627. aoMap: { value: null },
  4628. aoMapIntensity: { value: 1 }
  4629. },
  4630. lightmap: {
  4631. lightMap: { value: null },
  4632. lightMapIntensity: { value: 1 }
  4633. },
  4634. emissivemap: {
  4635. emissiveMap: { value: null }
  4636. },
  4637. bumpmap: {
  4638. bumpMap: { value: null },
  4639. bumpScale: { value: 1 }
  4640. },
  4641. normalmap: {
  4642. normalMap: { value: null },
  4643. normalScale: { value: new Cesium.Cartesian2(1, 1) }
  4644. },
  4645. displacementmap: {
  4646. displacementMap: { value: null },
  4647. displacementScale: { value: 1 },
  4648. displacementBias: { value: 0 }
  4649. },
  4650. roughnessmap: {
  4651. roughnessMap: { value: null }
  4652. },
  4653. metalnessmap: {
  4654. metalnessMap: { value: null }
  4655. },
  4656. gradientmap: {
  4657. gradientMap: { value: null }
  4658. },
  4659. fog: {
  4660. fogDensity: { value: 0.00025 },
  4661. fogNear: { value: 1 },
  4662. fogFar: { value: 2000 },
  4663. fogColor: { value: new Cesium.Color(0xffffff) }
  4664. },
  4665. lights: {
  4666. ambientLightColor: { value: [] },
  4667. directionalLights: {
  4668. value: [], properties: {
  4669. direction: {},
  4670. color: {},
  4671. shadow: {},
  4672. shadowBias: {},
  4673. shadowRadius: {},
  4674. shadowMapSize: {}
  4675. }
  4676. },
  4677. directionalShadowMap: { value: [] },
  4678. directionalShadowMatrix: { value: [] },
  4679. spotLights: {
  4680. value: [], properties: {
  4681. color: {},
  4682. position: {},
  4683. direction: {},
  4684. distance: {},
  4685. coneCos: {},
  4686. penumbraCos: {},
  4687. decay: {},
  4688. shadow: {},
  4689. shadowBias: {},
  4690. shadowRadius: {},
  4691. shadowMapSize: {}
  4692. }
  4693. },
  4694. spotShadowMap: { value: [] },
  4695. spotShadowMatrix: { value: [] },
  4696. pointLights: {
  4697. value: [], properties: {
  4698. color: {},
  4699. position: {},
  4700. decay: {},
  4701. distance: {},
  4702. shadow: {},
  4703. shadowBias: {},
  4704. shadowRadius: {},
  4705. shadowMapSize: {}
  4706. }
  4707. },
  4708. pointShadowMap: { value: [] },
  4709. pointShadowMatrix: { value: [] },
  4710. hemisphereLights: {
  4711. value: [], properties: {
  4712. direction: {},
  4713. skyColor: {},
  4714. groundColor: {}
  4715. }
  4716. },
  4717. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  4718. rectAreaLights: {
  4719. value: [], properties: {
  4720. color: {},
  4721. position: {},
  4722. width: {},
  4723. height: {}
  4724. }
  4725. }
  4726. },
  4727. points: {
  4728. diffuse: { value: new Cesium.Color(0xeeeeee) },
  4729. opacity: { value: 1.0 },
  4730. size: { value: 1.0 },
  4731. scale: { value: 1.0 },
  4732. map: { value: null },
  4733. offsetRepeat: { value: new Cesium.Cartesian4(0, 0, 1, 1) }
  4734. }
  4735. };
  4736. /**
  4737. * Uniform Utilities
  4738. */
  4739. var UniformsUtils = {
  4740. merge: function (uniforms) {
  4741. var merged = {};
  4742. for (var u = 0; u < uniforms.length; u++) {
  4743. var tmp = this.clone(uniforms[u]);
  4744. for (var p in tmp) {
  4745. merged[p] = tmp[p];
  4746. }
  4747. }
  4748. return merged;
  4749. },
  4750. clone: function (uniforms_src) {
  4751. var uniforms_dst = {};
  4752. for (var u in uniforms_src) {
  4753. uniforms_dst[u] = {};
  4754. for (var p in uniforms_src[u]) {
  4755. var parameter_src = uniforms_src[u][p];
  4756. if (parameter_src && (parameter_src instanceof Cesium.Color ||
  4757. parameter_src instanceof Cesium.Matrix3 || parameter_src instanceof Cesium.Matrix4 ||
  4758. parameter_src instanceof Cesium.Cartesian2 || parameter_src instanceof Cesium.Cartesian3
  4759. || parameter_src instanceof Cesium.Cartesian4
  4760. //||parameter_src.isTexture
  4761. )) {
  4762. uniforms_dst[u][p] = parameter_src.constructor.clone(parameter_src);//.clone();
  4763. } else if (Array.isArray(parameter_src)) {
  4764. uniforms_dst[u][p] = parameter_src.slice();
  4765. } else {
  4766. uniforms_dst[u][p] = parameter_src;
  4767. }
  4768. }
  4769. }
  4770. return uniforms_dst;
  4771. }
  4772. };
  4773. /**
  4774. * @author alteredq / http://alteredqualia.com/
  4775. * @author mrdoob / http://mrdoob.com/
  4776. * @author mikael emtinger / http://gomo.se/
  4777. */
  4778. var ShaderLib = {
  4779. basic: {
  4780. uniforms: UniformsUtils.merge([
  4781. UniformsLib.common,
  4782. UniformsLib.aomap,
  4783. UniformsLib.lightmap,
  4784. UniformsLib.fog
  4785. ]),
  4786. vertexShader: ShaderChunk.meshbasic_vert,
  4787. fragmentShader: ShaderChunk.meshbasic_frag
  4788. },
  4789. lambert: {
  4790. uniforms: UniformsUtils.merge([
  4791. UniformsLib.common,
  4792. UniformsLib.aomap,
  4793. UniformsLib.lightmap,
  4794. UniformsLib.emissivemap,
  4795. UniformsLib.fog,
  4796. UniformsLib.lights,
  4797. {
  4798. emissive: { value: new Cesium.Color(0x000000) }
  4799. }
  4800. ]),
  4801. vertexShader: ShaderChunk.meshlambert_vert,
  4802. fragmentShader: ShaderChunk.meshlambert_frag
  4803. },
  4804. phong: {
  4805. uniforms: UniformsUtils.merge([
  4806. UniformsLib.common,
  4807. UniformsLib.aomap,
  4808. UniformsLib.lightmap,
  4809. UniformsLib.emissivemap,
  4810. UniformsLib.bumpmap,
  4811. UniformsLib.normalmap,
  4812. UniformsLib.displacementmap,
  4813. UniformsLib.gradientmap,
  4814. UniformsLib.fog,
  4815. UniformsLib.lights,
  4816. {
  4817. emissive: { value: new Cesium.Color(0x000000) },
  4818. specular: { value: new Cesium.Color(0x111111) },
  4819. shininess: { value: 30 }
  4820. }
  4821. ]),
  4822. vertexShader: ShaderChunk.meshphong_vert,
  4823. fragmentShader: ShaderChunk.meshphong_frag
  4824. },
  4825. standard: {
  4826. uniforms: UniformsUtils.merge([
  4827. UniformsLib.common,
  4828. UniformsLib.aomap,
  4829. UniformsLib.lightmap,
  4830. UniformsLib.emissivemap,
  4831. UniformsLib.bumpmap,
  4832. UniformsLib.normalmap,
  4833. UniformsLib.displacementmap,
  4834. UniformsLib.roughnessmap,
  4835. UniformsLib.metalnessmap,
  4836. UniformsLib.fog,
  4837. UniformsLib.lights,
  4838. {
  4839. emissive: { value: new Cesium.Color(0x000000) },
  4840. roughness: { value: 0.5 },
  4841. metalness: { value: 0.5 },
  4842. envMapIntensity: { value: 1 } // temporary
  4843. }
  4844. ]),
  4845. vertexShader: ShaderChunk.meshphysical_vert,
  4846. fragmentShader: ShaderChunk.meshphysical_frag
  4847. },
  4848. points: {
  4849. uniforms: UniformsUtils.merge([
  4850. UniformsLib.points,
  4851. UniformsLib.fog
  4852. ]),
  4853. vertexShader: ShaderChunk.points_vert,
  4854. fragmentShader: ShaderChunk.points_frag
  4855. },
  4856. dashed: {
  4857. uniforms: UniformsUtils.merge([
  4858. UniformsLib.common,
  4859. UniformsLib.fog,
  4860. {
  4861. scale: { value: 1 },
  4862. dashSize: { value: 1 },
  4863. totalSize: { value: 2 }
  4864. }
  4865. ]),
  4866. vertexShader: ShaderChunk.linedashed_vert,
  4867. fragmentShader: ShaderChunk.linedashed_frag
  4868. },
  4869. depth: {
  4870. uniforms: UniformsUtils.merge([
  4871. UniformsLib.common,
  4872. UniformsLib.displacementmap
  4873. ]),
  4874. vertexShader: ShaderChunk.depth_vert,
  4875. fragmentShader: ShaderChunk.depth_frag
  4876. },
  4877. normal: {
  4878. uniforms: UniformsUtils.merge([
  4879. UniformsLib.common,
  4880. UniformsLib.bumpmap,
  4881. UniformsLib.normalmap,
  4882. UniformsLib.displacementmap,
  4883. {
  4884. opacity: { value: 1.0 }
  4885. }
  4886. ]),
  4887. vertexShader: ShaderChunk.normal_vert,
  4888. fragmentShader: ShaderChunk.normal_frag
  4889. },
  4890. /* -------------------------------------------------------------------------
  4891. // Cube map shader
  4892. ------------------------------------------------------------------------- */
  4893. cube: {
  4894. uniforms: {
  4895. tCube: { value: null },
  4896. tFlip: { value: -1 },
  4897. opacity: { value: 1.0 }
  4898. },
  4899. vertexShader: ShaderChunk.cube_vert,
  4900. fragmentShader: ShaderChunk.cube_frag
  4901. },
  4902. /* -------------------------------------------------------------------------
  4903. // Cube map shader
  4904. ------------------------------------------------------------------------- */
  4905. equirect: {
  4906. uniforms: {
  4907. tEquirect: { value: null },
  4908. tFlip: { value: -1 }
  4909. },
  4910. vertexShader: ShaderChunk.equirect_vert,
  4911. fragmentShader: ShaderChunk.equirect_frag
  4912. },
  4913. distanceRGBA: {
  4914. uniforms: {
  4915. lightPos: { value: new Cesium.Cartesian3() }
  4916. },
  4917. vertexShader: ShaderChunk.distanceRGBA_vert,
  4918. fragmentShader: ShaderChunk.distanceRGBA_frag
  4919. }
  4920. };
  4921. ShaderLib.physical = {
  4922. uniforms: UniformsUtils.merge([
  4923. ShaderLib.standard.uniforms,
  4924. {
  4925. clearCoat: { value: 0 },
  4926. clearCoatRoughness: { value: 0 }
  4927. }
  4928. ]),
  4929. vertexShader: ShaderChunk.meshphysical_vert,
  4930. fragmentShader: ShaderChunk.meshphysical_frag
  4931. };
  4932. return ShaderLib;
  4933. });
  4934. define('Core/MaterialUtils',[
  4935. 'Core/Shaders/ShaderChunk',
  4936. 'Core/Shaders/ShaderLib',
  4937. 'Core/MeshMaterial'
  4938. ], function (
  4939. ShaderChunk,
  4940. ShaderLib,
  4941. MeshMaterial
  4942. ) {
  4943. var shaderIDs = {
  4944. MeshDepthMaterial: 'depth',
  4945. MeshNormalMaterial: 'normal',
  4946. MeshBasicMaterial: 'basic',
  4947. MeshLambertMaterial: 'lambert',
  4948. MeshPhongMaterial: 'phong',
  4949. MeshToonMaterial: 'phong',
  4950. MeshStandardMaterial: 'physical',
  4951. MeshPhysicalMaterial: 'physical',
  4952. LineBasicMaterial: 'basic',
  4953. LineDashedMaterial: 'dashed',
  4954. PointsMaterial: 'points'
  4955. };
  4956. /**
  4957. *
  4958. *@constructor
  4959. *@memberof Cesium
  4960. */
  4961. function MaterialUtils() {
  4962. }
  4963. /**
  4964. *
  4965. *@param {THREE.Material}material3js
  4966. *@return {Cesium.MeshMaterial}
  4967. */
  4968. MaterialUtils.fromMaterial3js = function (material3js) {
  4969. var shaderID = shaderIDs[material3js.type];
  4970. material3js["is" + material3js.type] = true;
  4971. var shader = THREE.ShaderLib[shaderID];
  4972. if (!shader) {
  4973. shader = material3js;
  4974. }
  4975. var material = new MeshMaterial({
  4976. vertexShader: shader.vertexShader,
  4977. fragmentShader: shader.fragmentShader,
  4978. uniforms: cloneUniforms(shader.uniforms)
  4979. });
  4980. material.material3js = material3js;
  4981. MaterialUtils.updateMaterialFrom3js(material);
  4982. return material;
  4983. }
  4984. function cloneUniforms(uniforms3js) {
  4985. var uniforms = {};
  4986. for (var i in uniforms3js) {
  4987. if (uniforms3js.hasOwnProperty(i)) {
  4988. uniforms[i] = {
  4989. value: {}
  4990. };
  4991. for (var n in uniforms3js[i]) {
  4992. if (n!=="value") {
  4993. uniforms[i][n] = uniforms3js[i][n];
  4994. }
  4995. }
  4996. if (uniforms3js[i].t) {
  4997. switch (uniforms3js[i].t) {
  4998. default:
  4999. }
  5000. }
  5001. bindUniformValue(uniforms[i], uniforms3js[i].value);
  5002. }
  5003. }
  5004. return uniforms;
  5005. }
  5006. /**
  5007. *
  5008. *@param {Cesium.MeshMaterial}materialWidth3js
  5009. *@private
  5010. */
  5011. MaterialUtils.updateMaterialFrom3js = function (materialWidth3js) {
  5012. if (!materialWidth3js || !materialWidth3js.material3js) {
  5013. return;
  5014. }
  5015. var material3js = materialWidth3js.material3js;
  5016. materialWidth3js.translucent = material3js.transparent;
  5017. materialWidth3js.wireframe = material3js.wireframe;
  5018. var m_uniforms = materialWidth3js.uniforms;
  5019. var material = materialWidth3js.material3js;
  5020. if (material.isMeshBasicMaterial ||
  5021. material.isMeshLambertMaterial ||
  5022. material.isMeshPhongMaterial ||
  5023. material.isMeshStandardMaterial ||
  5024. material.isMeshNormalMaterial ||
  5025. material.isMeshDepthMaterial) {
  5026. refreshUniformsCommon(m_uniforms, material);
  5027. }
  5028. // refresh single material specific uniforms
  5029. if (material.isLineBasicMaterial) {
  5030. refreshUniformsLine(m_uniforms, material);
  5031. } else if (material.isLineDashedMaterial) {
  5032. refreshUniformsLine(m_uniforms, material);
  5033. refreshUniformsDash(m_uniforms, material);
  5034. } else if (material.isPointsMaterial) {
  5035. refreshUniformsPoints(m_uniforms, material);
  5036. } else if (material.isMeshLambertMaterial) {
  5037. refreshUniformsLambert(m_uniforms, material);
  5038. } else if (material.isMeshToonMaterial) {
  5039. refreshUniformsToon(m_uniforms, material);
  5040. } else if (material.isMeshPhongMaterial) {
  5041. refreshUniformsPhong(m_uniforms, material);
  5042. } else if (material.isMeshPhysicalMaterial) {
  5043. refreshUniformsPhysical(m_uniforms, material);
  5044. } else if (material.isMeshStandardMaterial) {
  5045. refreshUniformsStandard(m_uniforms, material);
  5046. } else if (material.isMeshDepthMaterial) {
  5047. if (material.displacementMap) {
  5048. bindUniformValue(m_uniforms.displacementMap, material.displacementMap);
  5049. bindUniformValue(m_uniforms.displacementScale, material.displacementScale);
  5050. bindUniformValue(m_uniforms.displacementBias, material.displacementBias);
  5051. }
  5052. } else if (material.isMeshNormalMaterial) {
  5053. refreshUniformsNormal(m_uniforms, material);
  5054. } else {
  5055. for (var i in material.uniforms) {
  5056. if (material.uniforms.hasOwnProperty(i)) {
  5057. bindUniformValue(m_uniforms[i], material.uniforms[i].value);
  5058. }
  5059. }
  5060. }
  5061. //if (material.lights) {
  5062. // // wire up the material to this renderer's lighting state
  5063. // //uniforms.ambientLightColor.value = _lights.ambient;
  5064. // //uniforms.directionalLights.value = _lights.directional;
  5065. // //uniforms.spotLights.value = _lights.spot;
  5066. // //uniforms.rectAreaLights.value = _lights.rectArea;
  5067. // //uniforms.pointLights.value = _lights.point;
  5068. // //uniforms.hemisphereLights.value = _lights.hemi;
  5069. // //uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  5070. // //uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  5071. // //uniforms.spotShadowMap.value = _lights.spotShadowMap;
  5072. // //uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  5073. // //uniforms.pointShadowMap.value = _lights.pointShadowMap;
  5074. // //uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  5075. // // TODO (abelnation): add area lights shadow info to uniforms
  5076. //} else {
  5077. m_uniforms.ambientLightColor = { value: new Cesium.Color(0.06666666666666667, 0.06666666666666667, 0.06666666666666667) };
  5078. //}
  5079. }
  5080. /**
  5081. *
  5082. *@param {Object}material3js
  5083. *@return {Boolean}
  5084. */
  5085. MaterialUtils.isMaterial3js = function (material3js) {
  5086. return typeof THREE !== 'undefined' && material3js instanceof THREE.Material;
  5087. }
  5088. // Uniforms (refresh bindUniformValue(uniforms objects)
  5089. function refreshUniformsCommon(uniforms, material) {
  5090. bindUniformValue(uniforms.opacity, material.opacity);
  5091. bindUniformValue(uniforms.diffuse, material.color);
  5092. if (material.emissive) {
  5093. var val3js = new material.emissive.constructor().copy(material.emissive).multiplyScalar(material.emissiveIntensity)
  5094. bindUniformValue(uniforms.emissive, val3js);
  5095. }
  5096. bindUniformValue(uniforms.map, material.map);
  5097. bindUniformValue(uniforms.specularMap, material.specularMap);
  5098. bindUniformValue(uniforms.alphaMap, material.alphaMap);
  5099. if (material.lightMap) {
  5100. bindUniformValue(uniforms.lightMap, material.lightMap);
  5101. bindUniformValue(uniforms.lightMapIntensity, material.lightMapIntensity);
  5102. }
  5103. if (material.aoMap) {
  5104. bindUniformValue(uniforms.aoMap, material.aoMap);
  5105. bindUniformValue(uniforms.aoMapIntensity, material.aoMapIntensity);
  5106. }
  5107. // uv repeat and offset setting priorities
  5108. // 1. color map
  5109. // 2. specular map
  5110. // 3. normal map
  5111. // 4. bump map
  5112. // 5. alpha map
  5113. // 6. emissive map
  5114. var uvScaleMap
  5115. if (material.map) {
  5116. uvScaleMap = material.map
  5117. } else if (material.specularMap) {
  5118. uvScaleMap = material.specularMap
  5119. } else if (material.displacementMap) {
  5120. uvScaleMap = material.displacementMap
  5121. } else if (material.normalMap) {
  5122. uvScaleMap = material.normalMap
  5123. } else if (material.bumpMap) {
  5124. uvScaleMap = material.bumpMap
  5125. } else if (material.roughnessMap) {
  5126. uvScaleMap = material.roughnessMap
  5127. } else if (material.metalnessMap) {
  5128. uvScaleMap = material.metalnessMap
  5129. } else if (material.alphaMap) {
  5130. uvScaleMap = material.alphaMap
  5131. } else if (material.emissiveMap) {
  5132. uvScaleMap = material.emissiveMap
  5133. }
  5134. if (uvScaleMap !== undefined) {
  5135. // backwards compatibility
  5136. if (uvScaleMap.isWebGLRenderTarget) {
  5137. uvScaleMap = uvScaleMap.texture
  5138. }
  5139. var offset = uvScaleMap.offset
  5140. var repeat = uvScaleMap.repeat
  5141. bindUniformValue(uniforms.offsetRepeat, offset);
  5142. }
  5143. bindUniformValue(uniforms.envMap, material.envMap);
  5144. // don't flip CubeTexture envMaps, flip everything else:
  5145. // WebGLRenderTargetCube will be flipped for backwards compatibility
  5146. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  5147. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  5148. bindUniformValue(uniforms.flipEnvMap, (!(material.envMap && material.envMap.isCubeTexture)) ? 1 : -1);
  5149. bindUniformValue(uniforms.reflectivity, material.reflectivity);
  5150. bindUniformValue(uniforms.refractionRatio, material.refractionRatio);
  5151. }
  5152. function refreshUniformsLine(uniforms, material) {
  5153. bindUniformValue(uniforms.diffuse, material.color);
  5154. bindUniformValue(uniforms.opacity, material.opacity);
  5155. }
  5156. function refreshUniformsDash(uniforms, material) {
  5157. bindUniformValue(uniforms.dashSize, material.dashSize);
  5158. bindUniformValue(uniforms.totalSize, material.dashSize + material.gapSize);
  5159. bindUniformValue(uniforms.scale, material.scale);
  5160. }
  5161. function refreshUniformsPoints(uniforms, material) {
  5162. bindUniformValue(uniforms.diffuse, material.color);
  5163. bindUniformValue(uniforms.opacity, material.opacity);
  5164. bindUniformValue(uniforms.size, material.size * _pixelRatio);
  5165. bindUniformValue(uniforms.scale, _height * 0.5);
  5166. bindUniformValue(uniforms.map, material.map);
  5167. if (material.map !== null) {
  5168. var offset = material.map.offset;
  5169. var repeat = material.map.repeat;
  5170. bindUniformValue(uniforms.offsetRepeat.value.set(offset.x, offset.y, repeat.x, repeat.y));
  5171. }
  5172. }
  5173. function refreshUniformsFog(uniforms, fog) {
  5174. bindUniformValue(uniforms.fogColor, fog.color);
  5175. if (fog.isFog) {
  5176. bindUniformValue(uniforms.fogNear, fog.near);
  5177. bindUniformValue(uniforms.fogFar, fog.far);
  5178. } else if (fog.isFogExp2) {
  5179. bindUniformValue(uniforms.fogDensity, fog.density);
  5180. }
  5181. }
  5182. function refreshUniformsLambert(uniforms, material) {
  5183. if (material.emissiveMap) {
  5184. bindUniformValue(uniforms.emissiveMap, material.emissiveMap);
  5185. }
  5186. }
  5187. function refreshUniformsPhong(uniforms, material) {
  5188. bindUniformValue(uniforms.specular, material.specular);
  5189. bindUniformValue(uniforms.shininess, Math.max(material.shininess, 1e-4)); // to prevent pow( 0.0, 0.0 )
  5190. if (material.emissiveMap) {
  5191. bindUniformValue(uniforms.emissiveMap, material.emissiveMap);
  5192. }
  5193. if (material.bumpMap) {
  5194. bindUniformValue(uniforms.bumpMap, material.bumpMap);
  5195. bindUniformValue(uniforms.bumpScale, material.bumpScale);
  5196. }
  5197. if (material.normalMap) {
  5198. bindUniformValue(uniforms.normalMap, material.normalMap);
  5199. bindUniformValue(uniforms.normalScale.value.copy(material.normalScale));
  5200. }
  5201. if (material.displacementMap) {
  5202. bindUniformValue(uniforms.displacementMap, material.displacementMap);
  5203. bindUniformValue(uniforms.displacementScale, material.displacementScale);
  5204. bindUniformValue(uniforms.displacementBias, material.displacementBias);
  5205. }
  5206. }
  5207. function refreshUniformsToon(uniforms, material) {
  5208. refreshUniformsPhong(uniforms, material);
  5209. if (material.gradientMap) {
  5210. bindUniformValue(uniforms.gradientMap, material.gradientMap);
  5211. }
  5212. }
  5213. function refreshUniformsStandard(uniforms, material) {
  5214. bindUniformValue(uniforms.roughness, material.roughness);
  5215. bindUniformValue(uniforms.metalness, material.metalness);
  5216. if (material.roughnessMap) {
  5217. bindUniformValue(uniforms.roughnessMap, material.roughnessMap);
  5218. }
  5219. if (material.metalnessMap) {
  5220. bindUniformValue(uniforms.metalnessMap, material.metalnessMap);
  5221. }
  5222. if (material.emissiveMap) {
  5223. bindUniformValue(uniforms.emissiveMap, material.emissiveMap);
  5224. }
  5225. if (material.bumpMap) {
  5226. bindUniformValue(uniforms.bumpMap, material.bumpMap);
  5227. bindUniformValue(uniforms.bumpScale, material.bumpScale);
  5228. }
  5229. if (material.normalMap) {
  5230. bindUniformValue(uniforms.normalMap, material.normalMap);
  5231. bindUniformValue(uniforms.normalScale.value.copy(material.normalScale));
  5232. }
  5233. if (material.displacementMap) {
  5234. bindUniformValue(uniforms.displacementMap, material.displacementMap);
  5235. bindUniformValue(uniforms.displacementScale, material.displacementScale);
  5236. bindUniformValue(uniforms.displacementBias, material.displacementBias);
  5237. }
  5238. if (material.envMap) {
  5239. //bindUniformValue(uniforms.envMap, material.envMap); // part of bindUniformValue(uniforms common
  5240. bindUniformValue(uniforms.envMapIntensity, material.envMapIntensity);
  5241. }
  5242. }
  5243. function refreshUniformsPhysical(uniforms, material) {
  5244. bindUniformValue(uniforms.clearCoat, material.clearCoat);
  5245. bindUniformValue(uniforms.clearCoatRoughness, material.clearCoatRoughness);
  5246. refreshUniformsStandard(uniforms, material)
  5247. }
  5248. function refreshUniformsNormal(uniforms, material) {
  5249. if (material.bumpMap) {
  5250. bindUniformValue(uniforms.bumpMap, material.bumpMap);
  5251. bindUniformValue(uniforms.bumpScale, material.bumpScale);
  5252. }
  5253. if (material.normalMap) {
  5254. bindUniformValue(uniforms.normalMap, material.normalMap);
  5255. bindUniformValue(uniforms.normalScale.value.copy(material.normalScale));
  5256. }
  5257. if (material.displacementMap) {
  5258. bindUniformValue(uniforms.displacementMap, material.displacementMap);
  5259. bindUniformValue(uniforms.displacementScale, material.displacementScale);
  5260. bindUniformValue(uniforms.displacementBias, material.displacementBias);
  5261. }
  5262. }
  5263. function bindUniformValue(valCesium, val3js) {
  5264. var type = typeof val3js;
  5265. if (type === 'undefined') {
  5266. valCesium.value = undefined;
  5267. return;
  5268. }
  5269. if (val3js === null) {
  5270. valCesium.value = null; return;
  5271. }
  5272. if (typeof valCesium.value !== "undefined"
  5273. && valCesium.value != null
  5274. && (valCesium.value.constructor
  5275. && valCesium.value.constructor.clone
  5276. && val3js.constructor == valCesium.value.constructor)) {
  5277. valCesium.value = valCesium.value.constructor.clone(val3js);
  5278. } else {
  5279. switch (type) {
  5280. case "number":
  5281. case "string":
  5282. valCesium.value = val3js;
  5283. break;
  5284. case "object":
  5285. if (val3js instanceof THREE.Vector2) {
  5286. if (!valCesium.value.constructor.clone) {
  5287. valCesium.value = new Cesium.Cartesian2();
  5288. }
  5289. }
  5290. if (val3js instanceof THREE.Vector3) {
  5291. if (!valCesium.value.constructor.clone) {
  5292. valCesium.value = new Cesium.Cartesian3();
  5293. }
  5294. }
  5295. if (val3js instanceof THREE.Vector4) {
  5296. if (!valCesium.value.constructor.clone) {
  5297. valCesium.value = new Cesium.Cartesian4();
  5298. }
  5299. }
  5300. if (val3js instanceof THREE.Matrix3) {
  5301. if (!valCesium.value.constructor.clone) {
  5302. valCesium.value = new Cesium.Matrix3();
  5303. }
  5304. }
  5305. if (val3js instanceof THREE.Matrix4) {
  5306. if (!valCesium.value.constructor.clone) {
  5307. valCesium.value = new Cesium.Matrix4();
  5308. }
  5309. }
  5310. if (val3js instanceof THREE.Color) {
  5311. if (!valCesium.value.constructor.clone) {
  5312. valCesium.value = new Cesium.Color(val3js.r, val3js.g, val3js.b, val3js.a);
  5313. }
  5314. } else if (valCesium.value != null && valCesium.value.constructor.clone) {
  5315. valCesium.value.constructor.clone(val3js, valCesium.value);
  5316. } else if (val3js instanceof THREE.Texture) {
  5317. if (valCesium.value != val3js.image) {
  5318. valCesium.value = val3js.image;
  5319. var sampler = {};
  5320. sampler.magnificationFilter = Cesium.WebGLConstants.LINEAR;
  5321. sampler.minificationFilter = Cesium.WebGLConstants.NEAREST_MIPMAP_LINEAR;
  5322. sampler.wrapS = Cesium.WebGLConstants.REPEAT;
  5323. sampler.wrapT = Cesium.WebGLConstants.REPEAT;
  5324. valCesium.sampler = sampler;
  5325. valCesium.flipY = val3js.flipY;
  5326. valCesium.needsUpdate = true;
  5327. }
  5328. } else {
  5329. valCesium.value = val3js;
  5330. }
  5331. break;
  5332. default:
  5333. console.log("未知uniform.value类型");
  5334. break;
  5335. }
  5336. }
  5337. }
  5338. return MaterialUtils;
  5339. });
  5340. define('Core/MeshUtils',[
  5341. 'Core/MaterialUtils',
  5342. 'Core/GeometryUtils',
  5343. 'Core/Mesh'
  5344. ], function (
  5345. MaterialUtils,
  5346. GeometryUtils,
  5347. Mesh
  5348. ) {
  5349. /**
  5350. *
  5351. *@constructor
  5352. *@memberof Cesium
  5353. */
  5354. function MeshUtils() {
  5355. }
  5356. /**
  5357. *
  5358. *@param {THREE.Mesh}mesh3js
  5359. *@return {Cesium.Mesh}
  5360. */
  5361. MeshUtils.fromMesh3js = function (mesh3js) {
  5362. if (!MeshUtils.isMesh3js(mesh3js)) {
  5363. return undefined;
  5364. }
  5365. var geometry = mesh3js.geometry;
  5366. if (GeometryUtils.isGeometry3js(geometry)) {
  5367. geometry = GeometryUtils.fromGeometry3js(geometry);
  5368. //if (mesh3js.material.type === "MeshNormalMaterial" || mesh3js.material.type === "MeshPhongMaterial") {
  5369. // GeometryUtils.computeVertexNormals(geometry)
  5370. //}
  5371. }
  5372. var material = mesh3js.material;
  5373. if (MaterialUtils.isMaterial3js(material)) {
  5374. material = MaterialUtils.fromMaterial3js(material);
  5375. }
  5376. var mesh = new Mesh({
  5377. geometry: geometry,
  5378. material: material,
  5379. position: mesh3js.position,
  5380. scale: mesh3js.scale
  5381. });
  5382. mesh.quaternion = mesh3js.quaternion;
  5383. return mesh;
  5384. }
  5385. /**
  5386. *
  5387. *@param {Object}mesh
  5388. *@return {Boolean}
  5389. */
  5390. MeshUtils.isMesh3js = function (mesh) {
  5391. return typeof THREE !== 'undefined' && mesh instanceof THREE.Mesh;
  5392. }
  5393. return MeshUtils;
  5394. });
  5395. define('Core/ShaderUtils',[ ], function (
  5396. ) {
  5397. /**
  5398. *
  5399. *@memberof Cesium
  5400. *@constructor
  5401. */
  5402. function ShaderUtils() {
  5403. }
  5404. /**
  5405. *
  5406. *
  5407. */
  5408. ShaderUtils.processShader3js = function (material3js, shader) {
  5409. var program = new WebGLProgram(material3js, shader);
  5410. return program;
  5411. }
  5412. if (typeof THREE=='undefined') {
  5413. return ShaderUtils;
  5414. }
  5415. var shaderIDs = {
  5416. MeshDepthMaterial: 'depth',
  5417. MeshNormalMaterial: 'normal',
  5418. MeshBasicMaterial: 'basic',
  5419. MeshLambertMaterial: 'lambert',
  5420. MeshPhongMaterial: 'phong',
  5421. MeshToonMaterial: 'phong',
  5422. MeshStandardMaterial: 'physical',
  5423. MeshPhysicalMaterial: 'physical',
  5424. LineBasicMaterial: 'basic',
  5425. LineDashedMaterial: 'dashed',
  5426. PointsMaterial: 'points'
  5427. };
  5428. var parameterNames = [
  5429. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  5430. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  5431. "roughnessMap", "metalnessMap", "gradientMap",
  5432. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  5433. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  5434. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  5435. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  5436. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  5437. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  5438. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  5439. ];
  5440. var ShaderChunk = THREE.ShaderChunk;
  5441. var ShaderLib = THREE.ShaderLib;
  5442. var BackSide = THREE.BackSide,
  5443. DoubleSide = THREE.DoubleSide,
  5444. FlatShading = THREE.FlatShading,
  5445. CubeUVRefractionMapping = THREE.CubeUVRefractionMapping,
  5446. CubeUVReflectionMapping = THREE.CubeUVReflectionMapping,
  5447. GammaEncoding = THREE.GammaEncoding,
  5448. LinearEncoding = THREE.LinearEncoding,
  5449. NoToneMapping = THREE.NoToneMapping,
  5450. AddOperation = THREE.AddOperation,
  5451. MixOperation = THREE.MixOperation,
  5452. MultiplyOperation = THREE.MultiplyOperation,
  5453. EquirectangularRefractionMapping = THREE.EquirectangularRefractionMapping,
  5454. CubeRefractionMapping = THREE.CubeRefractionMapping,
  5455. SphericalReflectionMapping = THREE.SphericalReflectionMapping,
  5456. EquirectangularReflectionMapping = THREE.EquirectangularReflectionMapping,
  5457. CubeReflectionMapping = THREE.CubeReflectionMapping,
  5458. PCFSoftShadowMap = THREE.PCFSoftShadowMap,
  5459. PCFShadowMap = THREE.PCFShadowMap,
  5460. CineonToneMapping = THREE.CineonToneMapping,
  5461. Uncharted2ToneMapping = THREE.Uncharted2ToneMapping,
  5462. ReinhardToneMapping = THREE.ReinhardToneMapping,
  5463. LinearToneMapping = THREE.LinearToneMapping,
  5464. GammaEncoding = THREE.GammaEncoding,
  5465. RGBDEncoding = THREE.RGBDEncoding,
  5466. RGBM16Encoding = THREE.RGBM16Encoding,
  5467. RGBM7Encoding = THREE.RGBM7Encoding,
  5468. RGBEEncoding = THREE.RGBEEncoding,
  5469. sRGBEncoding = THREE.sRGBEncoding;
  5470. function getTextureEncodingFromMap(map, gammaOverrideLinear) {
  5471. var encoding;
  5472. if (!map) {
  5473. encoding = LinearEncoding;
  5474. } else if (map.isTexture) {
  5475. encoding = map.encoding;
  5476. } else if (map.isWebGLRenderTarget) {
  5477. console.warn("THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead.");
  5478. encoding = map.texture.encoding;
  5479. }
  5480. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  5481. if (encoding === LinearEncoding && gammaOverrideLinear) {
  5482. encoding = GammaEncoding;
  5483. }
  5484. return encoding;
  5485. }
  5486. function getParameters(material) {//, lights, fog, nClipPlanes, nClipIntersection, object) {
  5487. var shaderID = shaderIDs[material.type];
  5488. // heuristics to create shader parameters according to lights in the scene
  5489. // (not to blow over maxLights budget)
  5490. //var maxBones = allocateBones(object);
  5491. //var precision = renderer.getPrecision();
  5492. //if (material.precision !== null) {
  5493. // precision = capabilities.getMaxPrecision(material.precision);
  5494. // if (precision !== material.precision) {
  5495. // console.warn('THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.');
  5496. // }
  5497. //}
  5498. var currentRenderTarget = null;// renderer.getCurrentRenderTarget();
  5499. var renderer = {};
  5500. var parameters = {
  5501. shaderID: shaderID,
  5502. precision: "high",//precision,
  5503. supportsVertexTextures: true,// capabilities.vertexTextures,
  5504. outputEncoding: getTextureEncodingFromMap((!currentRenderTarget) ? null : currentRenderTarget.texture, renderer.gammaOutput),
  5505. map: !!material.map,
  5506. mapEncoding: getTextureEncodingFromMap(material.map, renderer.gammaInput),
  5507. envMap: !!material.envMap,
  5508. envMapMode: material.envMap && material.envMap.mapping,
  5509. envMapEncoding: getTextureEncodingFromMap(material.envMap, renderer.gammaInput),
  5510. envMapCubeUV: (!!material.envMap) && ((material.envMap.mapping === CubeUVReflectionMapping) || (material.envMap.mapping === CubeUVRefractionMapping)),
  5511. lightMap: !!material.lightMap,
  5512. aoMap: !!material.aoMap,
  5513. emissiveMap: !!material.emissiveMap,
  5514. emissiveMapEncoding: getTextureEncodingFromMap(material.emissiveMap, renderer.gammaInput),
  5515. bumpMap: !!material.bumpMap,
  5516. normalMap: !!material.normalMap,
  5517. displacementMap: !!material.displacementMap,
  5518. roughnessMap: !!material.roughnessMap,
  5519. metalnessMap: !!material.metalnessMap,
  5520. specularMap: !!material.specularMap,
  5521. alphaMap: !!material.alphaMap,
  5522. gradientMap: !!material.gradientMap,
  5523. combine: material.combine,
  5524. vertexColors: material.vertexColors,
  5525. fog: false,//!!fog,
  5526. useFog: material.fog,
  5527. fogExp: false,//(fog && fog.isFogExp2),
  5528. flatShading: material.shading === FlatShading,
  5529. sizeAttenuation: material.sizeAttenuation,
  5530. logarithmicDepthBuffer: false,// capabilities.logarithmicDepthBuffer,
  5531. skinning: material.skinning,
  5532. //maxBones: maxBones,
  5533. //useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  5534. morphTargets: material.morphTargets,
  5535. morphNormals: material.morphNormals,
  5536. //maxMorphTargets: renderer.maxMorphTargets,
  5537. //maxMorphNormals: renderer.maxMorphNormals,
  5538. numDirLights: 0,// lights.directional.length,
  5539. numPointLights: 0,// lights.point.length,
  5540. numSpotLights: 0,// lights.spot.length,
  5541. numRectAreaLights: 0,// lights.rectArea.length,
  5542. numHemiLights: 0,// lights.hemi.length,
  5543. numClippingPlanes: 0,//nClipPlanes,
  5544. numClipIntersection: 0,//nClipIntersection,
  5545. //shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  5546. //shadowMapType: renderer.shadowMap.type,
  5547. //toneMapping: renderer.toneMapping,
  5548. //physicallyCorrectLights: renderer.physicallyCorrectLights,
  5549. premultipliedAlpha: material.premultipliedAlpha,
  5550. alphaTest: material.alphaTest,
  5551. doubleSided: material.side === DoubleSide,
  5552. flipSided: material.side === BackSide,
  5553. depthPacking: (material.depthPacking !== undefined) ? material.depthPacking : false
  5554. };
  5555. return parameters;
  5556. };
  5557. /**
  5558. * @author mrdoob / http://mrdoob.com/
  5559. */
  5560. var programIdCount = 0;
  5561. function getEncodingComponents(encoding) {
  5562. switch (encoding) {
  5563. case LinearEncoding:
  5564. return ['Linear', '( value )'];
  5565. case sRGBEncoding:
  5566. return ['sRGB', '( value )'];
  5567. case RGBEEncoding:
  5568. return ['RGBE', '( value )'];
  5569. case RGBM7Encoding:
  5570. return ['RGBM', '( value, 7.0 )'];
  5571. case RGBM16Encoding:
  5572. return ['RGBM', '( value, 16.0 )'];
  5573. case RGBDEncoding:
  5574. return ['RGBD', '( value, 256.0 )'];
  5575. case GammaEncoding:
  5576. return ['Gamma', '( value, float( GAMMA_FACTOR ) )'];
  5577. default:
  5578. throw new Error('unsupported encoding: ' + encoding);
  5579. }
  5580. }
  5581. function getTexelDecodingFunction(functionName, encoding) {
  5582. var components = getEncodingComponents(encoding);
  5583. return "vec4 " + functionName + "( vec4 value ) { return " + components[0] + "ToLinear" + components[1] + " ; }";
  5584. }
  5585. function getTexelEncodingFunction(functionName, encoding) {
  5586. var components = getEncodingComponents(encoding);
  5587. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[0] + components[1] + " ; }";
  5588. }
  5589. function getToneMappingFunction(functionName, toneMapping) {
  5590. var toneMappingName;
  5591. switch (toneMapping) {
  5592. case LinearToneMapping:
  5593. toneMappingName = "Linear";
  5594. break;
  5595. case ReinhardToneMapping:
  5596. toneMappingName = "Reinhard";
  5597. break;
  5598. case Uncharted2ToneMapping:
  5599. toneMappingName = "Uncharted2";
  5600. break;
  5601. case CineonToneMapping:
  5602. toneMappingName = "OptimizedCineon";
  5603. break;
  5604. default:
  5605. throw new Error('unsupported toneMapping: ' + toneMapping);
  5606. }
  5607. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  5608. }
  5609. function generateExtensions(extensions, parameters, rendererExtensions) {
  5610. extensions = extensions || {};
  5611. var chunks = [
  5612. (extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading) ? '#extension GL_OES_standard_derivatives : enable' : '',
  5613. (extensions.fragDepth || parameters.logarithmicDepthBuffer) && rendererExtensions.get('EXT_frag_depth') ? '#extension GL_EXT_frag_depth : enable' : '',
  5614. (extensions.drawBuffers) && rendererExtensions.get('WEBGL_draw_buffers') ? '#extension GL_EXT_draw_buffers : require' : '',
  5615. (extensions.shaderTextureLOD || parameters.envMap) && rendererExtensions.get('EXT_shader_texture_lod') ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  5616. ];
  5617. return chunks.filter(filterEmptyLine).join('\n');
  5618. }
  5619. function generateDefines(defines) {
  5620. var chunks = [];
  5621. for (var name in defines) {
  5622. var value = defines[name];
  5623. if (value === false) continue;
  5624. chunks.push('#define ' + name + ' ' + value);
  5625. }
  5626. return chunks.join('\n');
  5627. }
  5628. function filterEmptyLine(string) {
  5629. return string !== '';
  5630. }
  5631. function replaceLightNums(string, parameters) {
  5632. return string
  5633. .replace(/NUM_DIR_LIGHTS/g, parameters.numDirLights)
  5634. .replace(/NUM_SPOT_LIGHTS/g, parameters.numSpotLights)
  5635. .replace(/NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights)
  5636. .replace(/NUM_POINT_LIGHTS/g, parameters.numPointLights)
  5637. .replace(/NUM_HEMI_LIGHTS/g, parameters.numHemiLights);
  5638. }
  5639. function parseIncludes(string) {
  5640. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  5641. function replace(match, include) {
  5642. var replace = ShaderChunk[include];
  5643. if (replace === undefined) {
  5644. throw new Error('Can not resolve #include <' + include + '>');
  5645. }
  5646. return parseIncludes(replace);
  5647. }
  5648. return string.replace(pattern, replace);
  5649. }
  5650. function unrollLoops(string) {
  5651. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  5652. function replace(match, start, end, snippet) {
  5653. var unroll = '';
  5654. for (var i = parseInt(start) ; i < parseInt(end) ; i++) {
  5655. unroll += snippet.replace(/\[ i \]/g, '[ ' + i + ' ]');
  5656. }
  5657. return unroll;
  5658. }
  5659. return string.replace(pattern, replace);
  5660. }
  5661. function WebGLProgram(material, shader) {//, parameters) {
  5662. var parameters = getParameters(material);
  5663. //var shader = ShaderLib[parameters.shaderID];
  5664. //var extensions = material.extensions;
  5665. var defines = material.defines;
  5666. var vertexShader = shader.vertexShader;
  5667. var fragmentShader = shader.fragmentShader;
  5668. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  5669. if (parameters.shadowMapType === THREE.PCFShadowMap) {
  5670. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  5671. } else if (parameters.shadowMapType === THREE.PCFSoftShadowMap) {
  5672. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  5673. }
  5674. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  5675. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  5676. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  5677. if (parameters.envMap) {
  5678. switch (material.envMap.mapping) {
  5679. case CubeReflectionMapping:
  5680. case CubeRefractionMapping:
  5681. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  5682. break;
  5683. case CubeUVReflectionMapping:
  5684. case CubeUVRefractionMapping:
  5685. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  5686. break;
  5687. case EquirectangularReflectionMapping:
  5688. case EquirectangularRefractionMapping:
  5689. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  5690. break;
  5691. case SphericalReflectionMapping:
  5692. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  5693. break;
  5694. }
  5695. switch (material.envMap.mapping) {
  5696. case CubeRefractionMapping:
  5697. case EquirectangularRefractionMapping:
  5698. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  5699. break;
  5700. }
  5701. switch (material.combine) {
  5702. case MultiplyOperation:
  5703. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  5704. break;
  5705. case MixOperation:
  5706. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  5707. break;
  5708. case AddOperation:
  5709. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  5710. break;
  5711. }
  5712. }
  5713. var gammaFactorDefine = 1.0;// (renderer.gammaFactor > 0) ? renderer.gammaFactor : 1.0;
  5714. // var customExtensions = generateExtensions(extensions, parameters, renderer.extensions);
  5715. var customDefines = generateDefines(defines);
  5716. var prefixVertex, prefixFragment;
  5717. if (material.isRawShaderMaterial) {
  5718. prefixVertex = [
  5719. customDefines,
  5720. '\n'
  5721. ].filter(filterEmptyLine).join('\n');
  5722. prefixFragment = [
  5723. //customExtensions,
  5724. customDefines,
  5725. '\n'
  5726. ].filter(filterEmptyLine).join('\n');
  5727. } else {
  5728. prefixVertex = [
  5729. //'precision ' + parameters.precision + ' float;',
  5730. //'precision ' + parameters.precision + ' int;',
  5731. '#define SHADER_NAME ' + shader.name,
  5732. //customDefines,
  5733. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  5734. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  5735. '#define MAX_BONES ' + parameters.maxBones,
  5736. //(parameters.useFog && parameters.fog) ? '#define USE_FOG' : '',
  5737. //(parameters.useFog && parameters.fogExp) ? '#define FOG_EXP2' : '',
  5738. parameters.map ? '#define USE_MAP' : '',
  5739. parameters.envMap ? '#define USE_ENVMAP' : '',
  5740. parameters.envMap ? '#define ' + envMapModeDefine : '',
  5741. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  5742. parameters.aoMap ? '#define USE_AOMAP' : '',
  5743. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  5744. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  5745. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  5746. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  5747. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  5748. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  5749. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  5750. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  5751. parameters.vertexColors ? '#define USE_COLOR' : '',
  5752. parameters.flatShading ? '#define FLAT_SHADED' : '',
  5753. parameters.skinning ? '#define USE_SKINNING' : '',
  5754. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  5755. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  5756. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  5757. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  5758. parameters.flipSided ? '#define FLIP_SIDED' : '',
  5759. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  5760. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  5761. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  5762. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  5763. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  5764. //parameters.logarithmicDepthBuffer && renderer.extensions.get('EXT_frag_depth') ? '#define USE_LOGDEPTHBUF_EXT' : '',
  5765. //'uniform mat4 modelMatrix;',
  5766. //'uniform mat4 modelViewMatrix;',
  5767. //'uniform mat4 projectionMatrix;',
  5768. //'uniform mat4 viewMatrix;',
  5769. //'uniform mat3 normalMatrix;',
  5770. //'uniform vec3 cameraPosition;',
  5771. //'attribute vec3 position;',
  5772. //'attribute vec3 normal;',
  5773. //'attribute vec2 uv;',
  5774. '#ifdef USE_COLOR',
  5775. ' attribute vec3 color;',
  5776. '#endif',
  5777. '#ifdef USE_MORPHTARGETS',
  5778. ' attribute vec3 morphTarget0;',
  5779. ' attribute vec3 morphTarget1;',
  5780. ' attribute vec3 morphTarget2;',
  5781. ' attribute vec3 morphTarget3;',
  5782. ' #ifdef USE_MORPHNORMALS',
  5783. ' attribute vec3 morphNormal0;',
  5784. ' attribute vec3 morphNormal1;',
  5785. ' attribute vec3 morphNormal2;',
  5786. ' attribute vec3 morphNormal3;',
  5787. ' #else',
  5788. ' attribute vec3 morphTarget4;',
  5789. ' attribute vec3 morphTarget5;',
  5790. ' attribute vec3 morphTarget6;',
  5791. ' attribute vec3 morphTarget7;',
  5792. ' #endif',
  5793. '#endif',
  5794. '#ifdef USE_SKINNING',
  5795. ' attribute vec4 skinIndex;',
  5796. ' attribute vec4 skinWeight;',
  5797. '#endif',
  5798. '\n'
  5799. ].filter(filterEmptyLine).join('\n');
  5800. prefixFragment = [
  5801. //customExtensions,
  5802. //'precision ' + parameters.precision + ' float;',
  5803. //'precision ' + parameters.precision + ' int;',
  5804. '#define SHADER_NAME ' + shader.name,
  5805. customDefines,
  5806. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  5807. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  5808. (parameters.useFog && parameters.fog) ? '#define USE_FOG' : '',
  5809. (parameters.useFog && parameters.fogExp) ? '#define FOG_EXP2' : '',
  5810. parameters.map ? '#define USE_MAP' : '',
  5811. parameters.envMap ? '#define USE_ENVMAP' : '',
  5812. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  5813. parameters.envMap ? '#define ' + envMapModeDefine : '',
  5814. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  5815. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  5816. parameters.aoMap ? '#define USE_AOMAP' : '',
  5817. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  5818. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  5819. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  5820. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  5821. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  5822. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  5823. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  5824. parameters.vertexColors ? '#define USE_COLOR' : '',
  5825. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  5826. parameters.flatShading ? '#define FLAT_SHADED' : '',
  5827. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  5828. parameters.flipSided ? '#define FLIP_SIDED' : '',
  5829. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  5830. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  5831. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  5832. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  5833. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  5834. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  5835. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  5836. //parameters.logarithmicDepthBuffer && renderer.extensions.get('EXT_frag_depth') ? '#define USE_LOGDEPTHBUF_EXT' : '',
  5837. //parameters.envMap && renderer.extensions.get('EXT_shader_texture_lod') ? '#define TEXTURE_LOD_EXT' : '',
  5838. 'uniform mat4 viewMatrix;',
  5839. 'uniform vec3 cameraPosition;',
  5840. //(parameters.toneMapping !== THREE.NoToneMapping) ? "#define TONE_MAPPING" : '',
  5841. //(parameters.toneMapping !== THREE.NoToneMapping) ? ShaderChunk['tonemapping_pars_fragment'] : '', // this code is required here because it is used by the toneMapping() function defined below
  5842. //(parameters.toneMapping !== THREE.NoToneMapping) ? getToneMappingFunction("toneMapping", parameters.toneMapping) : '',
  5843. parameters.dithering ? '#define DITHERING' : '',
  5844. (parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding) ? ShaderChunk['encodings_pars_fragment'] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  5845. parameters.mapEncoding ? getTexelDecodingFunction('mapTexelToLinear', parameters.mapEncoding) : '',
  5846. parameters.envMapEncoding ? getTexelDecodingFunction('envMapTexelToLinear', parameters.envMapEncoding) : '',
  5847. parameters.emissiveMapEncoding ? getTexelDecodingFunction('emissiveMapTexelToLinear', parameters.emissiveMapEncoding) : '',
  5848. parameters.outputEncoding ? getTexelEncodingFunction("linearToOutputTexel", parameters.outputEncoding) : '',
  5849. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  5850. '\n'
  5851. ].filter(filterEmptyLine).join('\n');
  5852. }
  5853. vertexShader = parseIncludes(vertexShader);
  5854. vertexShader = replaceLightNums(vertexShader, parameters);
  5855. fragmentShader = parseIncludes(fragmentShader);
  5856. fragmentShader = replaceLightNums(fragmentShader, parameters);
  5857. if (!material.isShaderMaterial) {
  5858. vertexShader = unrollLoops(vertexShader);
  5859. fragmentShader = unrollLoops(fragmentShader);
  5860. }
  5861. var vertexGlsl = prefixVertex + vertexShader;
  5862. var fragmentGlsl = prefixFragment + fragmentShader;
  5863. this.id = programIdCount++;
  5864. this.usedTimes = 1;
  5865. this.vertexShader = vertexGlsl;
  5866. this.fragmentShader = fragmentGlsl;
  5867. return this;
  5868. }
  5869. return ShaderUtils;
  5870. });
  5871. define('Core/MeshVisualizer',[
  5872. 'Core/Mesh',
  5873. 'Core/RendererUtils',
  5874. 'Core/MeshMaterial',
  5875. 'Core/Shaders/ShaderChunk',
  5876. 'Core/Rotation',
  5877. 'Core/FramebufferTexture',
  5878. 'Core/LOD',
  5879. 'Core/ReferenceMesh',
  5880. 'ThirdParty/tiff-js/tiff',
  5881. 'Util/Path',
  5882. 'Core/GeometryUtils',
  5883. 'Core/MaterialUtils',
  5884. 'Core/MeshUtils',
  5885. 'Core/ShaderUtils'
  5886. ], function (
  5887. Mesh,
  5888. RendererUtils,
  5889. MeshMaterial,
  5890. ShaderChunk,
  5891. Rotation,
  5892. FramebufferTexture,
  5893. LOD,
  5894. ReferenceMesh,
  5895. TIFFParser,
  5896. Path,
  5897. GeometryUtils,
  5898. MaterialUtils,
  5899. MeshUtils,
  5900. ShaderUtils
  5901. ) {
  5902. var Matrix4 = Cesium.Matrix4;
  5903. var DrawCommand = Cesium.DrawCommand;
  5904. var defined = Cesium.defined;
  5905. var GeometryPipeline = Cesium.GeometryPipeline;
  5906. var BufferUsage = Cesium.BufferUsage;
  5907. var BlendingState = Cesium.BlendingState;
  5908. var VertexArray = Cesium.VertexArray;
  5909. var ShaderProgram = Cesium.ShaderProgram;
  5910. var DepthFunction = Cesium.DepthFunction;
  5911. var CullFace = Cesium.CullFace;
  5912. var RenderState = Cesium.RenderState;
  5913. var defaultValue = Cesium.defaultValue;
  5914. var Texture = Cesium.Texture;
  5915. var PixelFormat = Cesium.PixelFormat;
  5916. var BoxGeometry = Cesium.BoxGeometry;
  5917. var Cartesian3 = Cesium.Cartesian3;
  5918. var VertexFormat = Cesium.VertexFormat;
  5919. var CubeMap = Cesium.CubeMap;
  5920. var loadCubeMap = Cesium.loadCubeMap;
  5921. var Matrix3 = Cesium.Matrix3;
  5922. var CesiumMath = Cesium.Math;
  5923. var Color = Cesium.Color;
  5924. var scratchTranslation = new Cartesian3();
  5925. var scratchQuaternion = new Cesium.Quaternion();
  5926. var scratchScale = new Cartesian3();
  5927. var scratchTranslationQuaternionRotationScale = new Matrix4();
  5928. var computeModelMatrix = new Matrix4();
  5929. var scratchPosition = new Cartesian3();
  5930. var scratchTraverseArgs = {
  5931. cancelCurrent: false //停止遍历当前节点的所有子节点
  5932. };
  5933. Cesium.Cartesian3.prototype.set = function (x, y, z) {
  5934. this.x = x; this.y = y; this.z = z;
  5935. }
  5936. Cesium.Cartesian3.prototype.copy = function (src) {
  5937. this.x = src.x; this.y = src.y; this.z = src.z;
  5938. }
  5939. Cesium.Cartesian2.prototype.set = function (x, y) {
  5940. this.x = x; this.y = y;
  5941. }
  5942. Cesium.Cartesian2.prototype.copy = function (src) {
  5943. this.x = src.x; this.y = src.y;
  5944. }
  5945. Cesium.Quaternion.prototype.set = function (x, y, z, w) {
  5946. this.x = x; this.y = y; this.z = z; this.w = w;
  5947. }
  5948. Cesium.Quaternion.prototype.copy = function (src) {
  5949. this.x = src.x; this.y = src.y; this.z = src.z; this.w = src.w;
  5950. }
  5951. /**
  5952. *
  5953. *
  5954. *@param {Object}options
  5955. *@param {Cesium.Matrix4}[options.modelMatrix=Cesium.Matrix4.IDENTITY]
  5956. *@param {Cesium.Cartesian3}[options.up=Cesium.Cartesian3.UNIT_Z]
  5957. *@param {Cesium.Cartesian3}[options.position=Cesium.Cartesian3.ZERO]
  5958. *@param {Cesium.Cartesian3}[options.scale=new Cartesian3(1, 1, 1)]
  5959. *@param {Cesium.Rotation}[options.rotation]
  5960. *@param {Boolean}[options.show=true]
  5961. *@param {Boolean}[options.showReference=true]
  5962. *@param {Cesium.ArrowGeometry}[options.referenceAxisParameter]
  5963. *
  5964. *@property {Cesium.Matrix4}modelMatrix
  5965. *@property {Cesium.Cartesian3}up
  5966. *@property {Cesium.Cartesian3}position
  5967. *@property {Cesium.Cartesian3}scale
  5968. *@property {Cesium.Rotation}rotation
  5969. *@property {Boolean}show
  5970. *@property {Boolean}showReference
  5971. *@property {Boolean}modelMatrixNeedsUpdate
  5972. *@property {Cesium.Event}beforeUpdate
  5973. *
  5974. *@constructor
  5975. *@memberof Cesium
  5976. *@extends Cesium.Primitive
  5977. *
  5978. *@example
  5979. MeshVisualizer = Cesium.MeshVisualizer;
  5980. Mesh = Cesium.Mesh;
  5981. MeshMaterial = Cesium.MeshMaterial;
  5982. FramebufferTexture = Cesium.FramebufferTexture;
  5983. var center = Cesium.Cartesian3.fromDegrees(homePosition[0], homePosition[1], 50000);
  5984. var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(center);
  5985. var meshVisualizer = new MeshVisualizer({
  5986. modelMatrix: modelMatrix,
  5987. });
  5988. viewer.scene.primitives.add(meshVisualizer);
  5989. //示例1:Cesium.Geometry+Cesium.MeshMaterial组合
  5990. var box = Cesium.BoxGeometry.createGeometry(Cesium.BoxGeometry.fromDimensions({
  5991. dimensions: new Cesium.Cartesian3(100000, 50000, 50000),
  5992. vertexFormat: Cesium.VertexFormat.POSITION_ONLY
  5993. }));
  5994. var material = new MeshMaterial({
  5995. defaultColor: "rgba(255,0,0,1.0)",
  5996. wireframe: false,
  5997. side: MeshMaterial.Sides.DOUBLE
  5998. });
  5999. var boxMesh = new Mesh(box, material);
  6000. meshVisualizer.add(boxMesh);
  6001. //示例2:Cesium.CSG+Cesium.MeshMaterial组合,可以用Cesium.CSG做布尔运算并渲染运算结果
  6002. //首先使用Cesium创建球体
  6003. var sphere = new Cesium.SphereGeometry({
  6004. radius: 50000.0,
  6005. vertexFormat: Cesium.VertexFormat.POSITION_ONLY
  6006. });
  6007. sphere = Cesium.SphereGeometry.createGeometry(sphere);
  6008. var sphereMesh = new Mesh(sphere, material);
  6009. sphereMesh.position = new Cesium.Cartesian3(100000, 0, 0)
  6010. meshVisualizer.add(sphereMesh);
  6011. //将球体对象Cesium.SphereGeometry转成Cesium.CSG实例
  6012. sphere = CSG.toCSG(sphere);
  6013. //将盒子对象转成Cesium.CSG实例
  6014. box = CSG.toCSG(box);
  6015. //做布尔运算
  6016. var subResult = sphere.subtract(box);
  6017. //渲染运算结果
  6018. var subResultMesh = new Mesh(subResult, material);
  6019. subResultMesh.position = new Cesium.Cartesian3(700000, 0, 0)
  6020. meshVisualizer.add(subResultMesh);
  6021. //示例3:使用帧缓存作纹理,实际应用中如体绘制,风场流场绘制等等都可以运用此技术
  6022. function createGeometry() {
  6023. var p1 = new Cesium.Cartesian3(-50000, 50000, 100);
  6024. var p2 = new Cesium.Cartesian3(-50000, -50000, 100);
  6025. var p3 = new Cesium.Cartesian3(50000, -50000, 100);
  6026. var p4 = new Cesium.Cartesian3(50000, 50000, 100);
  6027. var positions = new Float64Array([
  6028. p1.x, p1.y, p1.z,
  6029. p2.x, p2.y, p2.z,
  6030. p3.x, p3.y, p3.z,
  6031. p4.x, p4.y, p4.z
  6032. ]);
  6033. var indices = new Uint16Array([
  6034. 0, 1, 3,
  6035. 1, 2, 3,
  6036. ]);
  6037. var sts = new Float32Array([
  6038. 1, 1,
  6039. 1, 0,
  6040. 0, 0,
  6041. 0, 1
  6042. ]);
  6043. var geometry = new Cesium.Geometry({
  6044. attributes: {
  6045. position: new Cesium.GeometryAttribute({
  6046. componentDatatype: Cesium.ComponentDatatype.DOUBLE,
  6047. componentsPerAttribute: 3,
  6048. values: positions
  6049. }),
  6050. st: new Cesium.GeometryAttribute({
  6051. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  6052. componentsPerAttribute: 2,
  6053. values: sts
  6054. })
  6055. },
  6056. indices: indices,
  6057. primitiveType: Cesium.PrimitiveType.TRIANGLES,
  6058. boundingSphere: Cesium.BoundingSphere.fromVertices(positions)
  6059. });
  6060. return geometry;
  6061. }
  6062. //将上文中的盒子渲染到缓存,作为纹理参与createGeometry()方法创建的几何体渲染过程
  6063. var framebufferTex = new FramebufferTexture(boxMesh);
  6064. var geometry = createGeometry();
  6065. var customMesh = new Mesh(geometry, new MeshMaterial({
  6066. uniforms: {
  6067. u_textureMap: framebufferTex//Cesium.buildModuleUrl('Widgets/Images/TerrainProviders/STK.png')
  6068. },
  6069. side: MeshMaterial.Sides.DOUBLE,
  6070. vertexShader : "\n\
  6071. \n\
  6072. varying vec3 v_position;\n\
  6073. varying vec2 v_st;\n\
  6074. \n\
  6075. void main(void) \n\
  6076. {\n\
  6077. vec4 pos = u_modelViewMatrix * vec4(position,1.0);\n\
  6078. v_position = pos.xyz;\n\
  6079. v_st=st;\n\
  6080. gl_Position = u_projectionMatrix * pos;\n\
  6081. }",
  6082. fragmentShader : "varying vec2 v_st;\
  6083. uniform sampler2D u_textureMap;\
  6084. void main()\
  6085. {\
  6086. gl_FragColor = texture2D(u_textureMap,v_st);\n\
  6087. \
  6088. }\
  6089. "
  6090. }));
  6091. customMesh.position = new Cesium.Cartesian3(100000, 0, 0);
  6092. meshVisualizer.add(customMesh);
  6093. */
  6094. function MeshVisualizer(options) {
  6095. this._modelMatrix = defaultValue(options.modelMatrix, Matrix4.IDENTITY);
  6096. this._actualModelMatrix = Matrix4.clone(this._modelMatrix);
  6097. this._ready = true;
  6098. this._modelMatrixNeedsUpdate = true;
  6099. this._isWireframe = false;
  6100. this._up = defaultValue(options.up, new Cartesian3(0, 0, 1));
  6101. this._position = defaultValue(options.position, new Cartesian3(0, 0, 0));
  6102. this._scale = defaultValue(options.scale, new Cartesian3(1, 1, 1));
  6103. this._rotation = defaultValue(options.rotation, { axis: new Cartesian3(0, 0, 1), angle: 0 });
  6104. this._rotation = new Rotation(this._rotation.axis, this._rotation.angle);
  6105. this._rotation.paramChanged.addEventListener(this.onModelMatrixNeedUpdate, this);
  6106. this._chidren = [];
  6107. this._debug = false;
  6108. this._show = defaultValue(options.show, true);
  6109. this._center = new Cartesian3();
  6110. Cesium.Matrix4.getTranslation(this._modelMatrix, this._center);
  6111. this._framebufferTextures = {};
  6112. this._uniformValueCache = {};
  6113. this._textureCache = {};
  6114. this._uniformMaps = {};
  6115. this.referenceMesh = new ReferenceMesh({
  6116. axisParameter: defaultValue(options.referenceAxisParameter, { length: 50000 * 2 }),
  6117. show: defaultValue(options.showReference, false)
  6118. });
  6119. this.add(this.referenceMesh);
  6120. this._pickIds = [];
  6121. this.beforeUpdate = new Cesium.Event();
  6122. this._scene = options.scene;
  6123. }
  6124. var world2localMatrix = new Cesium.Matrix4();
  6125. var surfacePointLocal = new Cesium.Cartesian3();
  6126. var rayDir = new Cesium.Cartesian3();
  6127. var pos = new Cesium.Cartesian3();
  6128. var rayOriginLocal = new Cesium.Cartesian3();
  6129. var scratchRay = new Cesium.Ray();
  6130. MeshVisualizer.prototype = {
  6131. /**
  6132. *@param {Cesium.Mesh}mesh
  6133. */
  6134. remove: function (mesh) {
  6135. for (var i = 0; i < this._chidren.length; i++) {
  6136. if (this._chidren[i] == mesh) {
  6137. this._chidren.splice(i, 1);
  6138. }
  6139. }
  6140. MeshVisualizer.traverse(mesh, function () {
  6141. if (mesh._drawCommand) {
  6142. mesh._drawCommand.destroy && mesh._drawCommand.destroy();
  6143. }
  6144. if (mesh._actualMesh && mesh._actualMesh._drawCommand) {
  6145. Cesium.destroyObject(mesh._actualMesh._drawCommand);
  6146. Cesium.destroyObject(mesh._actualMesh.geometry);
  6147. Cesium.destroyObject(mesh._actualMesh);
  6148. Cesium.destroyObject(mesh);
  6149. }
  6150. }, false);
  6151. },
  6152. /**
  6153. *
  6154. *拾取点用局部坐标系表达内部使用Cesium.Scene.pickPosition和MeshVisualizer.worldCoordinatesToLocal实现
  6155. *@param {Cesium.Cartesian2}windowPosition
  6156. *@param {Cesium.Ray}result
  6157. *@return {Cesium.Cartesian3}
  6158. */
  6159. pickPosition: function (windowPosition, result) {
  6160. if (!this._scene) {
  6161. return undefined;
  6162. }
  6163. this._scene.pickPosition(windowPosition, surfacePointLocal);
  6164. if (!surfacePointLocal) {
  6165. return undefined;
  6166. }
  6167. this.worldCoordinatesToLocal(surfacePointLocal, surfacePointLocal);
  6168. Cesium.Cartesian3.clone(surfacePointLocal, result);
  6169. return result;
  6170. },
  6171. /**
  6172. *
  6173. *创建一条射线用局部坐标系表达
  6174. *@param {Cesium.Cartesian2}windowPosition
  6175. *@param {Cesium.Ray}result
  6176. *@return {Cesium.Ray}
  6177. */
  6178. getPickRay: function (windowPosition, result) {
  6179. if (!this._scene) {
  6180. return undefined;
  6181. }
  6182. if (!result) {
  6183. result = Cesium.Ray();
  6184. }
  6185. this._scene.camera.getPickRay(windowPosition, scratchRay);//ray用于计算小球发射点位置,这里射线的起始点是世界坐标,不能像Threejs那样直接拿来计算,需要转成局部坐标
  6186. this._scene.pickPosition(windowPosition, surfacePointLocal);//射线和局部场景的交点
  6187. if (!surfacePointLocal) {
  6188. return undefined;
  6189. }
  6190. Cesium.Cartesian3.clone(scratchRay.direction, rayDir);
  6191. //世界坐标转局部坐标
  6192. this.worldCoordinatesToLocal(scratchRay.origin, rayOriginLocal);
  6193. this.worldCoordinatesToLocal(surfacePointLocal, surfacePointLocal);
  6194. Cesium.Cartesian3.add(rayOriginLocal, rayDir, pos);
  6195. //计算发射方向
  6196. Cesium.Cartesian3.subtract(surfacePointLocal, pos, rayDir);
  6197. Cesium.Cartesian3.clone(surfacePointLocal, result.origin);
  6198. Cesium.Cartesian3.clone(rayDir, result.direction);
  6199. return result;
  6200. },
  6201. /**
  6202. *世界坐标到局部坐标
  6203. *@param {Cesium.Cartesian3}worldCoordinates
  6204. *@param {Cesium.Cartesian3}result
  6205. *@return {Cesium.Cartesian3}
  6206. */
  6207. worldCoordinatesToLocal: function (worldCoordinates, result) {
  6208. if (!result) {
  6209. result = new Cartesian3();
  6210. }
  6211. Cesium.Matrix4.inverseTransformation(this._actualModelMatrix, world2localMatrix)
  6212. Cesium.Matrix4.multiplyByPoint(world2localMatrix, worldCoordinates, result);
  6213. return result;
  6214. },
  6215. /**
  6216. *局部坐标到世界坐标
  6217. *@param {Cesium.Cartesian3}localCoordinates
  6218. *@param {Cesium.Cartesian3}result
  6219. *@return {Cesium.Cartesian3}
  6220. */
  6221. localToWorldCoordinates: function (localCoordinates, result) {
  6222. if (!result) {
  6223. result = new Cartesian3();
  6224. }
  6225. Cesium.Matrix4.multiplyByPoint(this._actualModelMatrix, localCoordinates, result);
  6226. return result;
  6227. },
  6228. onModelMatrixNeedUpdate: function () {
  6229. this._modelMatrixNeedsUpdate = true;
  6230. },
  6231. /**
  6232. *
  6233. *@param {Number}x
  6234. *@param {Number}y
  6235. *@param {Number}z
  6236. */
  6237. setPosition: function (x, y, z) {
  6238. var changed = false;
  6239. if (arguments.length == 1) {
  6240. if (typeof x == 'number') {
  6241. if (x != this._position.x) changed = true;
  6242. this._position.x = x;
  6243. } else if (x instanceof Cesium.Cartesian3) {
  6244. if (x != this._position.x
  6245. || y != this._position.y
  6246. || z != this._position.z) {
  6247. changed = true;
  6248. }
  6249. this._position.x = x.x;
  6250. this._position.y = x.y;
  6251. this._position.z = x.z;
  6252. }
  6253. }
  6254. if (arguments.length == 2 && typeof y == 'number') {
  6255. if (y != this._position.y) changed = true;
  6256. this._position.y = y;
  6257. }
  6258. if (arguments.length == 3 && typeof z == 'number') {
  6259. if (z != this._position.z) changed = true;
  6260. this._position.z = z;
  6261. }
  6262. if (changed) {
  6263. this._modelMatrixNeedsUpdate = true;
  6264. }
  6265. },
  6266. /**
  6267. *
  6268. *@param {Number}x
  6269. *@param {Number}y
  6270. *@param {Number}z
  6271. */
  6272. setScale: function (x, y, z) {
  6273. var changed = false;
  6274. if (arguments.length == 1) {
  6275. if (typeof x == 'number') {
  6276. if (x != this._scale.x) changed = true;
  6277. this._scale.x = x;
  6278. } else if (x instanceof Cesium.Cartesian3) {
  6279. if (x != this._scale.x
  6280. || y != this._scale.y
  6281. || z != this._scale.z) {
  6282. changed = true;
  6283. }
  6284. this._scale.x = x.x;
  6285. this._scale.y = x.y;
  6286. this._scale.z = x.z;
  6287. }
  6288. }
  6289. if (arguments.length == 2 && typeof y == 'number') {
  6290. if (y != this._scale.y) changed = true;
  6291. this._scale.y = y;
  6292. }
  6293. if (arguments.length == 3 && typeof z == 'number') {
  6294. if (z != this._scale.z) changed = true;
  6295. this._scale.z = z;
  6296. }
  6297. if (changed) {
  6298. this._modelMatrixNeedsUpdate = true;
  6299. }
  6300. },
  6301. toWireframe: function (geometry) {
  6302. if (geometry.primitiveType !== Cesium.PrimitiveType.TRIANGLES
  6303. && geometry.primitiveType !== Cesium.PrimitiveType.TRIANGLE_FAN
  6304. && geometry.primitiveType !== Cesium.PrimitiveType.TRIANGLE_STRIP) {
  6305. return geometry;
  6306. }
  6307. if (!geometry.triangleIndices) {
  6308. geometry.triangleIndices = geometry.indices;
  6309. }
  6310. //if (geometry.lineIndices) {
  6311. // geometry.indices = geometry.lineIndices;
  6312. // return geometry;
  6313. //}
  6314. geometry = GeometryPipeline.toWireframe(geometry);
  6315. //geometry.lineIndices = geometry.indices;
  6316. return geometry;
  6317. },
  6318. restoreFromWireframe: function (geometry) {
  6319. if (geometry.triangleIndices) {
  6320. geometry.indices = geometry.triangleIndices;
  6321. }
  6322. geometry.primitiveType = Cesium.PrimitiveType.TRIANGLES;
  6323. return geometry;
  6324. },
  6325. /**
  6326. *
  6327. *@param {Cesium.Mesh} mesh
  6328. *@param {Cesium.FrameState} frameState
  6329. *@return {Cesium.DrawCommand}
  6330. *@private
  6331. */
  6332. createDrawCommand: function (mesh, frameState) {
  6333. var that = this;
  6334. var context = frameState.context;
  6335. var geometry = mesh.geometry;
  6336. var material = mesh.material;
  6337. var command = new Cesium.DrawCommand({
  6338. modelMatrix: Matrix4.clone(this.modelMatrix),
  6339. owner: mesh,
  6340. primitiveType: geometry.primitiveType,
  6341. cull: material.cullFrustum,
  6342. pass: material.translucent ? Cesium.Pass.TRANSLUCENT : Cesium.Pass.OPAQUE
  6343. //,boundingVolume: geometry.boundingSphere
  6344. });
  6345. var attributeLocations = GeometryPipeline.createAttributeLocations(geometry);
  6346. command.vertexArray = VertexArray.fromGeometry({
  6347. context: context,
  6348. geometry: geometry,
  6349. attributeLocations: attributeLocations,
  6350. bufferUsage: BufferUsage.STATIC_DRAW
  6351. });
  6352. command.vertexArray._attributeLocations = attributeLocations;
  6353. var pickObject = {
  6354. primitive: this,
  6355. id: mesh
  6356. };
  6357. var pickId = context.createPickId(pickObject);
  6358. that._pickIds.push(pickId);
  6359. var pickColor = pickId.color;
  6360. var shader = {
  6361. fragmentShader: this.getFragmentShaderSource(material),
  6362. vertexShader: this.getVertexShaderSource(geometry, material)
  6363. };
  6364. if (material.material3js) {
  6365. shader = ShaderUtils.processShader3js(material.material3js, shader);
  6366. }
  6367. command._sp = ShaderProgram.fromCache({
  6368. context: context,
  6369. fragmentShaderSource: shader.fragmentShader,//this.getFragmentShaderSource(material),
  6370. vertexShaderSource: shader.vertexShader,//this.getVertexShaderSource(geometry, material),
  6371. attributeLocations: attributeLocations
  6372. });
  6373. if (!Cesium.defined(mesh.material.allowPick)) {
  6374. mesh.material.allowPick = true;
  6375. }
  6376. if (mesh.material.allowPick) {
  6377. command._pickSp = ShaderProgram.fromCache({
  6378. context: context,
  6379. fragmentShaderSource: 'void main() {\n\tgl_FragColor = vec4(' + pickColor.red + ',' + pickColor.green + ',' + pickColor.blue + ',' + pickColor.alpha + ');\n}',
  6380. vertexShaderSource: shader.vertexShader,
  6381. attributeLocations: attributeLocations
  6382. });
  6383. }
  6384. command.shaderProgram = command._sp;
  6385. command.renderState = this.getRenderState(material);
  6386. command.uniformMap = this.getUniformMap(material, frameState);
  6387. return command;
  6388. },
  6389. /**
  6390. *
  6391. *
  6392. *@param {THREE.Material}material
  6393. *@return {Cesium.RenderState}frameState
  6394. *@private
  6395. */
  6396. getRenderState: function (material) {
  6397. var renderState = {
  6398. blending: material.blending ? BlendingState.ALPHA_BLEND : BlendingState.DISABLED,
  6399. depthTest: {
  6400. enabled: material.depthTest,
  6401. func: DepthFunction.LESS
  6402. },
  6403. cull: {
  6404. enabled: true,
  6405. face: CullFace.FRONT
  6406. },
  6407. depthRange: {
  6408. near: 0,
  6409. far: 1
  6410. },
  6411. colorMask: {
  6412. red: true,
  6413. green: true,
  6414. blue: true,
  6415. alpha: true
  6416. },
  6417. depthMask: material.depthMask
  6418. }
  6419. renderState.cull.enabled = true;
  6420. renderState.blending.color = {
  6421. red: 0.0,
  6422. green: 0.0,
  6423. blue: 0.0,
  6424. alpha: 0.0
  6425. };
  6426. switch (material.side) {
  6427. case MeshMaterial.Sides.FRONT:
  6428. renderState.cull.face = CullFace.BACK;
  6429. break;
  6430. case MeshMaterial.Sides.BACK:
  6431. renderState.cull.face = CullFace.FRONT;
  6432. break;
  6433. default:
  6434. renderState.cull.enabled = false;
  6435. break;
  6436. }
  6437. renderState = RenderState.fromCache(renderState);
  6438. return renderState;
  6439. },
  6440. /**
  6441. *
  6442. *
  6443. *@param {THREE.Material}material
  6444. *@param {Cesium.FrameState}frameState
  6445. *@private
  6446. */
  6447. getUniformMap: function (material, frameState) {
  6448. if (this._uniformMaps[material.uuid] && !material.needsUpdate) {
  6449. return this._uniformMaps[material.uuid];
  6450. }
  6451. var uniformMap = {};
  6452. this._uniformMaps[material.uuid] = uniformMap;
  6453. material.needsUpdate = false;
  6454. uniformMap.cameraPosition = function () {
  6455. return frameState.camera.position;
  6456. }
  6457. uniformMap.u_cameraPosition = function () {
  6458. return frameState.camera.position;
  6459. }
  6460. //base matrix
  6461. uniformMap.u_normalMatrix = function () {
  6462. return frameState.context.uniformState.normal;
  6463. }
  6464. uniformMap.u_projectionMatrix = function () {
  6465. return frameState.context.uniformState.projection;
  6466. }
  6467. uniformMap.u_modelViewMatrix = function () {
  6468. return frameState.context.uniformState.modelView;
  6469. }
  6470. //base matrix for threejs
  6471. uniformMap.normalMatrix = function () {
  6472. return frameState.context.uniformState.normal;
  6473. }
  6474. uniformMap.projectionMatrix = function () {
  6475. return frameState.context.uniformState.projection;
  6476. }
  6477. uniformMap.modelViewMatrix = function () {
  6478. return frameState.context.uniformState.modelView;
  6479. }
  6480. uniformMap.modelMatrix = function () {
  6481. return frameState.context.uniformState.model;
  6482. }
  6483. uniformMap.u_modelMatrix = function () {
  6484. return frameState.context.uniformState.model;
  6485. }
  6486. uniformMap.u_viewMatrix = function () {
  6487. return frameState.context.uniformState.view;
  6488. }
  6489. uniformMap.viewMatrix = function () {
  6490. return frameState.context.uniformState.view;
  6491. }
  6492. uniformMap.logDepthBufFC = function () {
  6493. return 2.0 / (Math.log(frameState.camera.frustum.far + 1.0) / Math.LN2)
  6494. }
  6495. if (material.uniformStateUsed && material.uniformStateUsed.length) {
  6496. material.uniformStateUsed.forEach(function (item) {
  6497. if (!uniformMap[item.glslVarName]) {
  6498. if (!frameState.context.uniformState[item.uniformStateName]) {
  6499. throw new Error(item.uniformStateName + "不是Cesium引擎的内置对象");
  6500. }
  6501. uniformMap[item.glslVarName] = function () {
  6502. return frameState.context.uniformState[item.uniformStateName];
  6503. }
  6504. }
  6505. });
  6506. }
  6507. var that = this;
  6508. function getCubeTextureCallback(name, item, mtl) {
  6509. var callback = function () {
  6510. if (!that._textureCache[item.uuid] || item.needsUpdate) {
  6511. if (!callback.allLoaded && !callback.isLoading) {
  6512. var promises = [];
  6513. for (var i = 0; i < item.value.length; i++) {
  6514. if (item.value[i] instanceof HTMLCanvasElement
  6515. || item.value[i] instanceof HTMLVideoElement
  6516. || item.value[i] instanceof HTMLImageElement
  6517. ) {
  6518. var deferred = Cesium.when.defer();
  6519. requestAnimationFrame(function () {
  6520. deferred.resolve(item.value[i]);
  6521. });
  6522. promises.push(deferred);
  6523. } else if (typeof item.value[i] === 'string') {
  6524. promises.push(Cesium.loadImage(item.value[i]));
  6525. } else {
  6526. throw Error(name + "" + i + "给定值“ " + item[i] + "” 不是有效的纹理图片");
  6527. }
  6528. }
  6529. callback.isLoading = true;
  6530. item.needsUpdate = false;
  6531. Cesium.when.all(promises, function (images) {
  6532. that._textureCache[item.uuid] = new Cesium.CubeMap({
  6533. context: frameState.context,
  6534. source: {
  6535. positiveX: images[0],
  6536. negativeX: images[1],
  6537. positiveY: images[2],
  6538. negativeY: images[3],
  6539. positiveZ: images[4],
  6540. negativeZ: images[5]
  6541. }
  6542. });
  6543. callback.allLoaded = true;
  6544. callback.isLoading = false;
  6545. });
  6546. }
  6547. }
  6548. if (callback.allLoaded) {
  6549. return that._textureCache[item.uuid];
  6550. }
  6551. else {
  6552. if (!that.defaultCubeMap) {
  6553. if (!that.defaultTextureImage) {
  6554. that.defaultTextureImage = document.createElement("canvas");
  6555. that.defaultTextureImage.width = 1;
  6556. that.defaultTextureImage.height = 1;
  6557. }
  6558. that.defaultCubeMap = new Cesium.CubeMap({
  6559. context: frameState.context,
  6560. source: {
  6561. positiveX: that.defaultTextureImage,
  6562. negativeX: that.defaultTextureImage,
  6563. positiveY: that.defaultTextureImage,
  6564. negativeY: that.defaultTextureImage,
  6565. positiveZ: that.defaultTextureImage,
  6566. negativeZ: that.defaultTextureImage
  6567. }
  6568. });
  6569. }
  6570. return that.defaultCubeMap;
  6571. }
  6572. }
  6573. if (callback.allLoaded) {
  6574. callback.allLoaded = false;
  6575. callback.isLoading = false;
  6576. }
  6577. return callback;
  6578. }
  6579. function createTexture(texture, context) {
  6580. var TextureMinificationFilter = Cesium.TextureMinificationFilter;
  6581. var TextureWrap = Cesium.TextureWrap;
  6582. var sampler = texture.sampler;
  6583. var mipmap =
  6584. (sampler.minificationFilter === TextureMinificationFilter.NEAREST_MIPMAP_NEAREST) ||
  6585. (sampler.minificationFilter === TextureMinificationFilter.NEAREST_MIPMAP_LINEAR) ||
  6586. (sampler.minificationFilter === TextureMinificationFilter.LINEAR_MIPMAP_NEAREST) ||
  6587. (sampler.minificationFilter === TextureMinificationFilter.LINEAR_MIPMAP_LINEAR);
  6588. var requiresNpot = mipmap ||
  6589. (sampler.wrapS === TextureWrap.REPEAT) ||
  6590. (sampler.wrapS === TextureWrap.MIRRORED_REPEAT) ||
  6591. (sampler.wrapT === TextureWrap.REPEAT) ||
  6592. (sampler.wrapT === TextureWrap.MIRRORED_REPEAT);
  6593. var source = texture.source;
  6594. var npot = !CesiumMath.isPowerOfTwo(source.width) || !CesiumMath.isPowerOfTwo(source.height);
  6595. if (requiresNpot && npot) {
  6596. // WebGL requires power-of-two texture dimensions for mipmapping and REPEAT/MIRRORED_REPEAT wrap modes.
  6597. var canvas = document.createElement('canvas');
  6598. canvas.width = CesiumMath.nextPowerOfTwo(source.width);
  6599. canvas.height = CesiumMath.nextPowerOfTwo(source.height);
  6600. var canvasContext = canvas.getContext('2d');
  6601. canvasContext.drawImage(source, 0, 0, source.width, source.height, 0, 0, canvas.width, canvas.height);
  6602. source = canvas;
  6603. }
  6604. var tx;
  6605. if (texture.target === WebGLConstants.TEXTURE_2D) {
  6606. tx = new Texture({
  6607. context: context,
  6608. source: source,
  6609. width: texture.width,
  6610. height: texture.height,
  6611. pixelFormat: texture.internalFormat,
  6612. pixelDatatype: texture.type,
  6613. sampler: sampler,
  6614. flipY: texture.flipY
  6615. });
  6616. }
  6617. // GLTF_SPEC: Support TEXTURE_CUBE_MAP. https://github.com/KhronosGroup/glTF/issues/40
  6618. if (mipmap) {
  6619. tx.generateMipmap();
  6620. }
  6621. return tx;
  6622. }
  6623. var WebGLConstants = Cesium.WebGLConstants;
  6624. function onTextureImageLoaded(image, item) {
  6625. var tex;
  6626. if (defined(image.internalFormat)) {
  6627. tex = new Texture({
  6628. context: frameState.context,
  6629. pixelFormat: image.internalFormat,
  6630. width: image.width,
  6631. height: image.height,
  6632. source: {
  6633. arrayBufferView: image.bufferView
  6634. },
  6635. flipY: item.flipY
  6636. });
  6637. } else {
  6638. var format = Cesium.WebGLConstants.RGB;
  6639. if (image instanceof HTMLCanvasElement
  6640. || image instanceof HTMLVideoElement
  6641. || (image.src && image.src.toLocaleLowerCase().indexOf(".png") >= 0)
  6642. ) {
  6643. format = Cesium.WebGLConstants.RGBA;
  6644. }
  6645. if (item.sampler) {
  6646. tex = createTexture({
  6647. context: frameState.context,
  6648. source: image,
  6649. target: WebGLConstants.TEXTURE_2D,
  6650. width: item.width,
  6651. height: item.height,
  6652. pixelFormat: format,
  6653. flipY: item.flipY,
  6654. sampler: new Cesium.Sampler(item.sampler)
  6655. }, frameState.context);
  6656. } else {
  6657. tex = new Texture({
  6658. context: frameState.context,
  6659. source: image,
  6660. target: WebGLConstants.TEXTURE_2D,
  6661. width: item.width,
  6662. height: item.height,
  6663. pixelFormat: format,
  6664. flipY: Cesium.defined(item.flipY) ? item.flipY : true
  6665. });
  6666. }
  6667. }
  6668. return tex;
  6669. }
  6670. function getTextureCallback(item) {
  6671. var callback = function () {
  6672. if (!that._textureCache[item.value] || item.needsUpdate) {
  6673. if (item.value instanceof HTMLImageElement
  6674. || item.value instanceof HTMLCanvasElement
  6675. || item.value instanceof HTMLVideoElement
  6676. ) {
  6677. var image = item.value;
  6678. that._textureCache[item.value] = onTextureImageLoaded(image, item);
  6679. item.needsUpdate = false;
  6680. return that._textureCache[item.value];
  6681. } else {
  6682. if (typeof item.value === "string" && !callback.isLoading) {
  6683. callback.isLoading = true;
  6684. item.needsUpdate = false;
  6685. var url = item.value.toLocaleLowerCase();
  6686. var extension = Path.GetExtension(url).slice(1);
  6687. if (extension == 'tif') {//处理tif纹理
  6688. Cesium.Resource.fetchArrayBuffer({ url: url }).then(function (imageArrayBuffer) {
  6689. var tiffParser = new TIFFParser();
  6690. var tiffCanvas = tiffParser.parseTIFF(imageArrayBuffer);
  6691. if (that._textureCache[item.value]) {
  6692. that._textureCache[item.value].destroy && that._textureCache[item.value].destroy();
  6693. }
  6694. that._textureCache[item.value] = onTextureImageLoaded(tiffCanvas, item);
  6695. callback.isLoading = false;
  6696. }).catch(function (err) {
  6697. console.log(err);
  6698. })
  6699. } else {
  6700. Cesium.Resource.fetchImage({ url: item.value }).then(function (image) {
  6701. if (that._textureCache[item.value]) {
  6702. that._textureCache[item.value].destroy && that._textureCache[item.value].destroy();
  6703. }
  6704. that._textureCache[item.value] = onTextureImageLoaded(image, item);
  6705. callback.isLoading = false;
  6706. }).catch(function (err) {
  6707. console.log(err);
  6708. })
  6709. }
  6710. }
  6711. if (!that.defaultTextureImage) {
  6712. that.defaultTextureImage = document.createElement("canvas");
  6713. that.defaultTextureImage.width = 1;
  6714. that.defaultTextureImage.height = 1;
  6715. }
  6716. if (!that.defaultTexture) {
  6717. that.defaultTexture = new Texture({
  6718. context: frameState.context,
  6719. source: that.defaultTextureImage
  6720. });
  6721. }
  6722. return that.defaultTexture;
  6723. }
  6724. } else {
  6725. return that._textureCache[item.value];
  6726. }
  6727. }
  6728. return callback;
  6729. }
  6730. if (material.uniforms) {
  6731. function setUniformCallbackFunc(name, item) {
  6732. if (item !== undefined && item !== null) {//item may be 0
  6733. var isImageUrl = typeof item.value === "string";
  6734. var isCssColorString = typeof item.value === "string";
  6735. if (typeof item.value === "string") {
  6736. var itemLowerCase = item.value.toLocaleLowerCase();
  6737. if (itemLowerCase.endsWith(".png")
  6738. || itemLowerCase.endsWith(".jpg")
  6739. || itemLowerCase.endsWith(".bmp")
  6740. || itemLowerCase.endsWith(".gif")
  6741. || itemLowerCase.endsWith(".tif")
  6742. || itemLowerCase.endsWith(".tiff")
  6743. || itemLowerCase.startsWith("data:")
  6744. ) {
  6745. isImageUrl = true;
  6746. isCssColorString = false;
  6747. } else {
  6748. try {
  6749. Cesium.Color.fromCssColorString(item.value);
  6750. isImageUrl = true;
  6751. isCssColorString = false;
  6752. } catch (e) {
  6753. isImageUrl = false;
  6754. isCssColorString = false;
  6755. }
  6756. }
  6757. }
  6758. if (item.value instanceof Cesium.Cartesian2
  6759. || item.value instanceof Cesium.Cartesian3
  6760. || item.value instanceof Cesium.Cartesian4
  6761. || item.value instanceof Cesium.Color
  6762. || item.value instanceof Cesium.Matrix4
  6763. || item.value instanceof Cesium.Matrix3
  6764. || item.value instanceof Cesium.Matrix2
  6765. || item.value instanceof Cesium.Texture
  6766. || typeof item.value === "number"
  6767. || isCssColorString
  6768. || item.value instanceof Cesium.Texture
  6769. || (item.value instanceof Array && (typeof item.value[0] === 'number'
  6770. || item.value[0] instanceof Cesium.Cartesian2
  6771. || item.value[0] instanceof Cesium.Cartesian3
  6772. || item.value[0] instanceof Cesium.Cartesian4))
  6773. ) {
  6774. if (!that._uniformValueCache) {
  6775. that._uniformValueCache = {};
  6776. }
  6777. that._uniformValueCache[item.uuid] = item;
  6778. if (isCssColorString) {
  6779. item.value = Cesium.Color.fromCssColorString(item.value);
  6780. }
  6781. uniformMap[name] = function () {
  6782. return that._uniformValueCache[item.uuid].value;
  6783. }
  6784. } else if (item.value instanceof Array && item.value.length == 6) {
  6785. uniformMap[name] = getCubeTextureCallback(name, item);
  6786. } else if (isImageUrl
  6787. || item.value instanceof HTMLImageElement
  6788. || item.value instanceof HTMLCanvasElement
  6789. || item.value instanceof HTMLVideoElement
  6790. ) {
  6791. uniformMap[name] = getTextureCallback(item, material);
  6792. } else if (item.value instanceof FramebufferTexture) {
  6793. if (!that._renderToTextureCommands) {
  6794. that._renderToTextureCommands = [];
  6795. }
  6796. if (!that._framebufferTextures[item.uuid]) {
  6797. that._framebufferTextures[item.uuid] = item;
  6798. }
  6799. uniformMap[name] = function () {
  6800. if (!that._framebufferTextures[item.uuid]
  6801. || !that._framebufferTextures[item.uuid].value.texture) {
  6802. return frameState.context.defaultTexture;
  6803. }
  6804. return that._framebufferTextures[item.uuid].value.texture;
  6805. }
  6806. }
  6807. }
  6808. }
  6809. var uniforms = material.uniforms;
  6810. for (var name in uniforms) {
  6811. if (uniforms.hasOwnProperty(name) && Cesium.defined(uniforms[name].value) && uniforms[name].value != null) {
  6812. if (Array.isArray(uniforms[name].value) && uniforms[name].value.length == 0) {
  6813. continue;
  6814. }
  6815. var item = uniforms[name];
  6816. if (item == undefined || item == null) {
  6817. continue;
  6818. }
  6819. setUniformCallbackFunc(name, item);
  6820. }
  6821. }
  6822. }
  6823. return this._uniformMaps[material.uuid];
  6824. },
  6825. /**
  6826. *
  6827. *@param {Cesium.Geometry} geometry
  6828. *@param {Cesium.Material} material
  6829. *@return {String}
  6830. *@private
  6831. */
  6832. getVertexShaderSource: function (geometry, material) {
  6833. function getAttributeDefineBlok(userDefine) {
  6834. var glsl = "";
  6835. var attrs = geometry.attributes;
  6836. for (var name in attrs) {
  6837. if (attrs.hasOwnProperty(name)) {
  6838. var attr = attrs[name]
  6839. if (attr) {
  6840. var type = null;
  6841. switch (attr.componentsPerAttribute) {
  6842. case 1:
  6843. type = "float";
  6844. break;
  6845. case 2:
  6846. type = "vec2";
  6847. break;
  6848. case 3:
  6849. type = "vec3";
  6850. break;
  6851. case 4:
  6852. type = "vec4";
  6853. break;
  6854. default:
  6855. }
  6856. if (type) {
  6857. if (userDefine.indexOf("attribute " + type + " " + name) >= 0) {
  6858. continue;
  6859. }
  6860. glsl += "attribute " + type + " " + name + ";\n";
  6861. }
  6862. }
  6863. }
  6864. }
  6865. return glsl;
  6866. }
  6867. var uniforms = "\n\
  6868. uniform mat4 modelViewMatrix;\n\
  6869. uniform mat4 viewMatrix;\n\
  6870. uniform mat4 modelMatrix;\n\
  6871. uniform mat4 projectionMatrix;\n\
  6872. uniform mat3 normalMatrix;\n\
  6873. uniform mat4 u_modelViewMatrix;\n\
  6874. uniform mat4 u_viewMatrix;\n\
  6875. uniform mat4 u_modelMatrix;\n\
  6876. uniform mat4 u_projectionMatrix;\n\
  6877. uniform mat3 u_normalMatrix;\n\
  6878. uniform vec3 cameraPosition;\n\
  6879. uniform vec3 u_cameraPosition;\n";
  6880. var innerUniforms = [
  6881. "uniform mat4 modelViewMatrix",
  6882. "uniform mat4 modelMatrix",
  6883. "uniform mat4 projectionMatrix",
  6884. "uniform mat3 normalMatrix",
  6885. "uniform mat4 u_modelViewMatrix",
  6886. "uniform mat4 u_modelMatrix",
  6887. "uniform mat4 u_projectionMatrix",
  6888. "uniform mat3 u_normalMatrix",
  6889. "uniform mat4 u_viewMatrix",
  6890. "uniform mat4 viewMatrix",
  6891. "uniform vec3 cameraPosition",
  6892. "uniform vec3 u_cameraPosition"
  6893. ];
  6894. if (material.vertexShader) {
  6895. uniforms = "";
  6896. innerUniforms.forEach(function (item) {
  6897. if (material.vertexShader.indexOf(item) < 0) {
  6898. uniforms += item + ";\n";
  6899. }
  6900. });
  6901. var vs = getAttributeDefineBlok(material.vertexShader) + uniforms +
  6902. material.vertexShader;
  6903. vs = ShaderChunk.parseIncludes(vs);
  6904. return vs;
  6905. }
  6906. else {
  6907. throw new Error("material.vertexShader 是必须参数");
  6908. }
  6909. },
  6910. /**
  6911. *
  6912. *@param {Cesium.Material} material
  6913. *@return {String}
  6914. *@private
  6915. */
  6916. getFragmentShaderSource: function (material) {
  6917. if (material.fragmentShader) {
  6918. var fs = ShaderChunk.parseIncludes(material.fragmentShader);
  6919. return fs;
  6920. } else {
  6921. throw new Error("material.fragmentShader 是必须参数");
  6922. }
  6923. }
  6924. }
  6925. MeshVisualizer.prototype._computeModelMatrix = function (mesh, frameState) {
  6926. if (mesh._actualMesh) {
  6927. mesh = mesh._actualMesh;
  6928. }
  6929. var that = this;
  6930. if (mesh instanceof LOD || mesh instanceof ReferenceMesh || typeof mesh.update === 'function') {
  6931. if (mesh.parent) {
  6932. if (mesh.parent == that) {
  6933. mesh.update(that._actualModelMatrix, frameState);
  6934. } else if (mesh.parent.modelMatrix) {
  6935. mesh.update(mesh.parent.modelMatrix, frameState);
  6936. } else {
  6937. mesh.update(that._actualModelMatrix, frameState);
  6938. }
  6939. } else {
  6940. mesh.update(that._actualModelMatrix, frameState);
  6941. }
  6942. } else {
  6943. var position = mesh.position;
  6944. if (mesh.parent instanceof LOD) {
  6945. Matrix4.clone(mesh.parent.modelMatrix, mesh.modelMatrix);
  6946. } else if (mesh._modelMatrixNeedsUpdate) {
  6947. var rotation = mesh.quaternion ? mesh.quaternion : mesh.rotation;
  6948. if (mesh.parent && mesh.parent.modelMatrix) {
  6949. var actualModelMatrix = mesh.parent.modelMatrix ? mesh.parent.modelMatrix : mesh._drawCommand.modelMatrix;
  6950. RendererUtils.computeModelMatrix(
  6951. actualModelMatrix,
  6952. mesh.position,
  6953. rotation,
  6954. mesh.scale,
  6955. mesh.modelMatrix
  6956. );
  6957. } else {
  6958. RendererUtils.computeModelMatrix(
  6959. that._actualModelMatrix,
  6960. mesh.position,
  6961. rotation,
  6962. mesh.scale,
  6963. mesh.modelMatrix
  6964. );
  6965. }
  6966. mesh._modelMatrixNeedsUpdate = false;
  6967. }
  6968. }
  6969. }
  6970. /**
  6971. *
  6972. *@param {Cesium.FrameState}frameState
  6973. */
  6974. MeshVisualizer.prototype.update = function (frameState) {
  6975. if (!this._scene) {
  6976. this._scene = frameState.camera._scene;
  6977. }
  6978. if (!this._ready || !this.show && this._chidren.length > 0) {//如果未准备好则不加入渲染队列
  6979. return;
  6980. }
  6981. this.beforeUpdate.raiseEvent(frameState);
  6982. var that = this;
  6983. var wireframeChanged = false;
  6984. var sysWireframe = frameState.camera._scene._globe._surface.tileProvider._debug.wireframe;
  6985. if (this.debug) {
  6986. sysWireframe = true;
  6987. }
  6988. if (sysWireframe != this._isWireframe) {
  6989. wireframeChanged = true;
  6990. }
  6991. if (this._modelMatrixNeedsUpdate) {
  6992. this._actualModelMatrix = RendererUtils.computeModelMatrix(
  6993. this._modelMatrix,
  6994. this._position,
  6995. this._rotation,
  6996. this._scale,
  6997. this._actualModelMatrix
  6998. );
  6999. if (this._up && this._up.y) {
  7000. this._actualModelMatrix = RendererUtils.yUp2Zup(this._actualModelMatrix, this._actualModelMatrix);
  7001. }
  7002. Cesium.Cartesian3.clone(this._scale, this._oldScale);
  7003. Cesium.Cartesian3.clone(this._position, this._oldPosition);
  7004. this._modelMatrixNeedsUpdate = false;
  7005. }
  7006. MeshVisualizer.traverse(this, function (mesh) {
  7007. if (MeshUtils.isMesh3js(mesh)) {
  7008. var needsUpdate = !mesh._actualMesh
  7009. || mesh.needsUpdate
  7010. || mesh.geometry.needsUpdate;
  7011. if (needsUpdate) {
  7012. mesh._actualMesh = MeshUtils.fromMesh3js(mesh);
  7013. mesh.modelMatrixNeedsUpdate = true;
  7014. }
  7015. if (!needsUpdate) {
  7016. for (var pn in mesh.geometry.attributes) {
  7017. if (mesh.geometry.attributes.hasOwnProperty(pn)) {
  7018. mesh._actualMesh.geometry.attributes[pn].needsUpdate = mesh.geometry.attributes[pn].needsUpdate;
  7019. }
  7020. }
  7021. var index = mesh.geometry.index;
  7022. if (index && index.needsUpdate) {
  7023. mesh._actualMesh.geometry.needsUpdate = true;
  7024. }
  7025. }
  7026. mesh._actualMesh.quaternion = Cesium.Quaternion.clone(mesh.quaternion);
  7027. mesh._actualMesh.position = mesh.position;
  7028. mesh._actualMesh.scale = mesh.scale;
  7029. mesh._actualMesh.modelMatrixNeedsUpdate = mesh.modelMatrixNeedsUpdate;
  7030. mesh = mesh._actualMesh;
  7031. MaterialUtils.updateMaterialFrom3js(mesh.material);
  7032. }
  7033. that._computeModelMatrix(mesh, frameState);
  7034. if (typeof mesh.update !== 'function') {
  7035. if (frameState.passes.pick && !mesh.material.allowPick) {
  7036. return;
  7037. }
  7038. if (!mesh._drawCommand
  7039. || mesh.needsUpdate
  7040. || mesh.geometry.needsUpdate
  7041. || wireframeChanged
  7042. ) {//重新构建绘图命令,比如geometry完全不同于之前一帧 或者顶点和索引数量都发生改变等时,执行这段
  7043. if (sysWireframe || mesh.material.wireframe) {
  7044. that.toWireframe(mesh.geometry);
  7045. } else {
  7046. that.restoreFromWireframe(mesh.geometry);
  7047. }
  7048. mesh._drawCommand = that.createDrawCommand(mesh, frameState);
  7049. mesh.needsUpdate = false;
  7050. mesh.geometry.needsUpdate = false;
  7051. } else {//在不需要重新构建绘图命令时,检查各个属性和索引是否需要更新,需要则将更新相应的缓冲区
  7052. //更新属性缓冲区
  7053. for (var name in mesh.geometry.attributes) {
  7054. if (mesh.geometry.attributes.hasOwnProperty(name)) {
  7055. if (mesh.geometry.attributes[name] && mesh.geometry.attributes[name].needsUpdate) {
  7056. var attrLocation = mesh._drawCommand.vertexArray._attributeLocations[name]
  7057. var vb = mesh._drawCommand.vertexArray._attributes[attrLocation].vertexBuffer;
  7058. vb.copyFromArrayView(mesh.geometry.attributes[name].values, 0);
  7059. }
  7060. }
  7061. }
  7062. //更新索引缓冲区
  7063. if (mesh.geometry.indexNeedsUpdate) {
  7064. var vb = mesh._drawCommand.vertexArray.indexBuffer;
  7065. vb.copyFromArrayView(mesh.geometry.indices, 0);
  7066. }
  7067. }
  7068. mesh._drawCommand.modelMatrix = mesh.modelMatrix;
  7069. if (!mesh._drawCommand.boundingVolume) {
  7070. if (!mesh.geometry.boundingSphere) {
  7071. mesh.geometry.boundingSphere = Cesium.BoundingSphere.fromVertices(mesh.geometry.attributes.position.values);
  7072. }
  7073. mesh._drawCommand.boundingVolume = Cesium.BoundingSphere.clone(mesh.geometry.boundingSphere);
  7074. }
  7075. Cesium.Matrix4.getTranslation(mesh.modelMatrix, mesh._drawCommand.boundingVolume.center);
  7076. mesh._drawCommand.uniformMap = that.getUniformMap(mesh.material, frameState);
  7077. if (frameState.passes.pick) {
  7078. mesh._drawCommand.shaderProgram = mesh._drawCommand._pickSp;
  7079. frameState.commandList.push(mesh._drawCommand);
  7080. } else {
  7081. mesh._drawCommand.renderState.depthTest.enabled = mesh.material.depthTest;
  7082. mesh._drawCommand.shaderProgram = mesh._drawCommand._sp;
  7083. frameState.commandList.push(mesh._drawCommand);
  7084. }
  7085. } else {
  7086. mesh.needsUpdate = false;
  7087. }
  7088. }, true);
  7089. //执行帧缓冲绘图命令
  7090. for (var i in that._framebufferTextures) {
  7091. if (that._framebufferTextures.hasOwnProperty(i)) {
  7092. var item = that._framebufferTextures[i].value;
  7093. that.updateFrameBufferTexture(frameState, item);
  7094. }
  7095. }
  7096. this._isWireframe = sysWireframe;
  7097. wireframeChanged = false;
  7098. this._modelMatrixNeedsUpdate = false;
  7099. this._geometryChanged = false;
  7100. }
  7101. /**
  7102. *单独渲染frameBufferTexture中的mesh最终更新frameBufferTexture中的texture
  7103. *@param {Cesium.FrameState}frameState
  7104. *@param {Cesium.FramebufferTexture}frameBufferTexture
  7105. */
  7106. MeshVisualizer.prototype.updateFrameBufferTexture = function (frameState, frameBufferTexture,viewport) {
  7107. var that = this;
  7108. var item = frameBufferTexture;
  7109. if (item instanceof FramebufferTexture) {
  7110. item.drawCommands = [];
  7111. MeshVisualizer.traverse(item.mesh, function (mesh) {
  7112. if (MeshUtils.isMesh3js(mesh)) {
  7113. var needsUpdate = !mesh._actualMesh
  7114. || mesh.needsUpdate
  7115. || mesh.geometry.needsUpdate;
  7116. if (needsUpdate) {
  7117. mesh._actualMesh = MeshUtils.fromMesh3js(mesh);
  7118. }
  7119. if (!needsUpdate) {
  7120. for (var pn in mesh.geometry.attributes) {
  7121. if (mesh.geometry.attributes.hasOwnProperty(pn)) {
  7122. mesh._actualMesh.geometry[pn].needsUpdate = mesh.geometry.attributes[pn].needsUpdate;
  7123. }
  7124. }
  7125. var index = mesh.geometry.getIndex();
  7126. if (index && index.needsUpdate) {
  7127. mesh._actualMesh.geometry.needsUpdate = true;
  7128. }
  7129. }
  7130. mesh._actualMesh.quaternion = Cesium.Quaternion.clone(mesh.quaternion);
  7131. mesh._actualMesh.position = mesh.position;
  7132. mesh._actualMesh.scale = mesh.scale;
  7133. mesh._actualMesh.modelMatrixNeedsUpdate = mesh.modelMatrixNeedsUpdate;
  7134. mesh = mesh._actualMesh;
  7135. MaterialUtils.updateMaterialFrom3js(mesh.material);
  7136. }
  7137. that._computeModelMatrix(mesh, frameState);
  7138. if (!mesh._textureCommand
  7139. || mesh.needsUpdate
  7140. || mesh.geometry.needsUpdate
  7141. ) {
  7142. if (mesh.material.wireframe) {
  7143. that.toWireframe(mesh.geometry);
  7144. } else {
  7145. that.restoreFromWireframe(mesh.geometry);
  7146. }
  7147. mesh._textureCommand = that.createDrawCommand(mesh, frameState);
  7148. //mesh._textureCommand.boundingVolume = mesh.geometry.boundingSphere;
  7149. mesh.needsUpdate = false;
  7150. mesh.material.needsUpdate = false;
  7151. } else {//在不需要重新构建绘图命令时,检查各个属性和索引是否需要更新,需要则将更新相应的缓冲区
  7152. //更新属性缓冲区
  7153. for (var name in mesh.geometry.attributes) {
  7154. if (mesh.geometry.attributes.hasOwnProperty(name)
  7155. && mesh.geometry.attributes[name]) {
  7156. if (mesh.geometry.attributes[name] && mesh.geometry.attributes[name].needsUpdate) {
  7157. var attrLocation = mesh._textureCommand.vertexArray._attributeLocations[name]
  7158. var vb = mesh._textureCommand.vertexArray._attributes[attrLocation].vertexBuffer;
  7159. vb.copyFromArrayView(mesh.geometry.attributes[name].values, 0);
  7160. }
  7161. }
  7162. }
  7163. //更新索引缓冲区
  7164. if (mesh.geometry.indexNeedsUpdate) {
  7165. var vb = mesh._textureCommand.vertexArray.indexBuffer;
  7166. vb.copyFromArrayView(mesh.geometry.indices, 0);
  7167. }
  7168. }
  7169. mesh._textureCommand.modelMatrix = mesh.modelMatrix;
  7170. var context = frameState.context;
  7171. var drawingBufferWidth = context.drawingBufferWidth;
  7172. var drawingBufferHeight = context.drawingBufferHeight;
  7173. if (!item.texture
  7174. || item.texture.width != drawingBufferWidth
  7175. || item.texture.height != drawingBufferHeight
  7176. ) {
  7177. var notFullScreen = item._notFullScreen || Cesium.defined(item.texture);
  7178. if (!notFullScreen) {
  7179. item.texture = new Texture({
  7180. context: context,
  7181. width: drawingBufferWidth,
  7182. height: drawingBufferHeight,
  7183. pixelFormat: PixelFormat.RGBA
  7184. });
  7185. }
  7186. item._notFullScreen = notFullScreen;
  7187. }
  7188. mesh._textureCommand.renderState.depthTest.enabled = mesh.depthTest;
  7189. if (viewport) {
  7190. mesh._textureCommand.renderState.viewport = viewport;
  7191. }
  7192. item.drawCommands.push(mesh._textureCommand);
  7193. }, true);
  7194. RendererUtils.renderToTexture(item.drawCommands, frameState, item.texture);
  7195. }
  7196. }
  7197. /**
  7198. *
  7199. *@param {Cesium.Mesh}mesh
  7200. */
  7201. MeshVisualizer.prototype.add = function (mesh) {
  7202. this._chidren.push(mesh);
  7203. }
  7204. /**
  7205. *
  7206. */
  7207. MeshVisualizer.prototype.destroy = function () {
  7208. this._ready = false;
  7209. MeshVisualizer.traverse(this, function (mesh) {
  7210. if (mesh._drawCommand) {
  7211. delete mesh._drawCommand;
  7212. }
  7213. }, false);
  7214. for (var i in this._uniformValueCache) {
  7215. if (this._uniformValueCache.hasOwnProperty(i)) {
  7216. delete this._uniformValueCache[i];
  7217. }
  7218. }
  7219. for (var i in this._textureCache) {
  7220. if (this._textureCache.hasOwnProperty(i)) {
  7221. delete this._textureCache[i];
  7222. }
  7223. }
  7224. for (var i in this._uniformMaps) {
  7225. if (this._uniformMaps.hasOwnProperty(i)) {
  7226. delete this._uniformMaps[i];
  7227. }
  7228. }
  7229. for (var i in this._framebufferTextures) {
  7230. if (this._framebufferTextures.hasOwnProperty(i)) {
  7231. delete this._framebufferTextures[i];
  7232. }
  7233. }
  7234. this._uniformValueCache = {};
  7235. this._textureCache = {};
  7236. this._uniformMaps = {};
  7237. this._framebufferTextures = {};
  7238. if (this._pickIds) {
  7239. for (i = 0; i < this._pickIds.length; ++i) {
  7240. this._pickIds[i].destroy && this._pickIds[i].destroy();
  7241. }
  7242. }
  7243. }
  7244. /**
  7245. *
  7246. *遍历节点
  7247. *@param {Cesium.MeshVisualizer|Cesium.Mesh}root
  7248. *@param {Cesium.MeshVisualizer~TraverseCallback}traverseFunc 访问每个节点时回调该函数进行相关操作回调函数包含一个参数traverseArgs其中封装了一个属性cancelCurrent可以通过改变此属性达到终止遍历当前节点的子节点
  7249. *@param {Boolean}visibleOnly visibleOnly为true时仅遍历可见的节点如果父级节点不可见则不再访问其子节点
  7250. */
  7251. MeshVisualizer.traverse = function (node, traverseFunc, visibleOnly, scratchTraverseArgs) {
  7252. if (!node) {
  7253. return;
  7254. }
  7255. if (!scratchTraverseArgs) {
  7256. scratchTraverseArgs = {
  7257. cancelCurrent: false,
  7258. cancelAll: false
  7259. };
  7260. }
  7261. scratchTraverseArgs.cancelCurrent = false;
  7262. if (visibleOnly && (!node.show && !node.visible)) {
  7263. return;
  7264. }
  7265. if ((node.geometry && node.material) || node instanceof LOD || node instanceof ReferenceMesh) {
  7266. traverseFunc(node, scratchTraverseArgs);
  7267. }
  7268. if (node.children) {
  7269. for (var i = 0; i < node.children.length; i++) {
  7270. if (scratchTraverseArgs.cancelCurrent) {
  7271. continue;
  7272. }
  7273. if (scratchTraverseArgs.cancelAll) {
  7274. break;
  7275. }
  7276. MeshVisualizer.traverse(node.children[i], traverseFunc, visibleOnly, scratchTraverseArgs);
  7277. }
  7278. }
  7279. },
  7280. /**
  7281. *
  7282. *@Cesium.MeshVisualizer~TraverseCallback
  7283. *@param {Cesium.Mesh|Cesium.LOD|Cesium.MeshVisualizer|Object}node
  7284. *@param {Object}traverseArgs
  7285. *@param {Boolean}traverseArgs.cancelCurrent 为true时终止遍历当前节点的子节点
  7286. *@param {Boolean}traverseArgs.cancelAll 为true时终止遍历退出遍历循环
  7287. */
  7288. Object.defineProperties(MeshVisualizer.prototype, {
  7289. scene: {
  7290. set: function (val) {
  7291. this._scene = val;
  7292. },
  7293. get: function () {
  7294. return this._scene;
  7295. }
  7296. },
  7297. frameState: {
  7298. get: function () {
  7299. if (!this._scene) {
  7300. return undefined;
  7301. }
  7302. return this._scene.frameState;
  7303. }
  7304. },
  7305. modelMatrixNeedsUpdate: {
  7306. get: function () {
  7307. return this._modelMatrixNeedsUpdate;
  7308. },
  7309. set: function (val) {
  7310. this._modelMatrixNeedsUpdate = val;
  7311. if (val) {
  7312. MeshVisualizer.traverse(this, function (child) {
  7313. child._modelMatrixNeedsUpdate = val;
  7314. }, false);
  7315. }
  7316. }
  7317. },
  7318. showReference: {
  7319. get: function () {
  7320. return this.referenceMesh.show;
  7321. },
  7322. set: function (val) {
  7323. this.referenceMesh.show = val;
  7324. }
  7325. },
  7326. children: {
  7327. get: function () {
  7328. return this._chidren;
  7329. },
  7330. set: function (val) {
  7331. this._chidren = val;
  7332. }
  7333. },
  7334. show: {
  7335. get: function () {
  7336. return this._show;
  7337. },
  7338. set: function (val) {
  7339. this._show = val;
  7340. }
  7341. },
  7342. debug: {
  7343. get: function () {
  7344. return this._debug;
  7345. },
  7346. set: function (val) {
  7347. this._debug = val;
  7348. }
  7349. },
  7350. ready: {
  7351. get: function () {
  7352. return this._ready;
  7353. }
  7354. },
  7355. modelMatrix: {
  7356. get: function () {
  7357. return this._modelMatrix;
  7358. },
  7359. set: function (val) {
  7360. this._modelMatrix = val;
  7361. this._modelMatrixNeedsUpdate = true;
  7362. }
  7363. },
  7364. rotation: {
  7365. get: function () {
  7366. return this._rotation;
  7367. },
  7368. set: function (val) {
  7369. if (val != this._rotation) {
  7370. this._rotation = val;
  7371. this._needUpdate = true;
  7372. }
  7373. this._rotation.paramChanged.removeEventListener(this._onNeedUpdateChanged);
  7374. this._rotation = val;
  7375. this._rotation.paramChanged.addEventListener(this._onNeedUpdateChanged);
  7376. }
  7377. },
  7378. position: {
  7379. get: function () {
  7380. return this._position;
  7381. },
  7382. set: function (val) {
  7383. if (val.x != this._position.x || val.y != this._position.y || val.z != this._position.z) {
  7384. this._position = val;
  7385. this._modelMatrixNeedsUpdate = true;
  7386. }
  7387. this._position = val;
  7388. }
  7389. },
  7390. scale: {
  7391. get: function () {
  7392. return this._scale;
  7393. },
  7394. set: function (val) {
  7395. if (val.x != this._scale.x || val.y != this._scale.y || val.z != this._scale.z) {
  7396. this._scale = val;
  7397. this._modelMatrixNeedsUpdate = true;
  7398. }
  7399. this._scale = val;
  7400. }
  7401. }
  7402. });
  7403. return MeshVisualizer;
  7404. });
  7405. define('Core/BasicMeshMaterial',[
  7406. 'Core/MeshMaterial',
  7407. 'Core/Shaders/ShaderChunk',
  7408. 'Core/Shaders/ShaderLib',
  7409. 'Util/Path'
  7410. ], function (
  7411. MeshMaterial,
  7412. ShaderChunk,
  7413. ShaderLib,
  7414. Path
  7415. ) {
  7416. var WebGLConstants = Cesium.WebGLConstants;
  7417. function BasicMeshMaterial(options) {
  7418. options = options ? options : {};
  7419. options.uniforms = options.uniforms ? options.uniforms : {
  7420. ambientColor: [0, 0, 0, 1.0], // Ka
  7421. emissionColor: [0, 0, 0, 1.0], // Ke
  7422. diffuseColor: [0, 0, 0, 1.0], // Kd
  7423. specularColor: [0, 0, 0, 1.0], // Ks
  7424. specularShininess: 0, // Ns
  7425. alpha: undefined, // d / Tr
  7426. ambientColorMap: undefined, // map_Ka
  7427. emissionColorMap: undefined, // map_Ke
  7428. diffuseColorMap: undefined, // map_Kd
  7429. specularColorMap: undefined, // map_Ks
  7430. specularShininessMap: undefined, // map_Ns
  7431. normalMap: undefined, // map_Bump
  7432. alphaMap: undefined // map_d
  7433. };
  7434. options.uniforms.ambientColor = Cesium.defaultValue(options.uniforms.ambientColor, [0, 0, 0, 1.0]);
  7435. options.uniforms.emissionColor = Cesium.defaultValue(options.uniforms.emissionColor, [0, 0, 0, 1.0]);
  7436. options.uniforms.diffuseColor = Cesium.defaultValue(options.uniforms.diffuseColor, [0, 0, 0, 1.0]);
  7437. options.uniforms.specularColor = Cesium.defaultValue(options.uniforms.specularColor, [0, 0, 0, 1.0]);
  7438. options.uniforms.alpha = Cesium.defaultValue(options.uniforms.alpha, 1);
  7439. options.uniforms.specularShininess = Cesium.defaultValue(options.uniforms.specularShininess, 0);
  7440. options.side = Cesium.defaultValue(options.side, MeshMaterial.Sides.FRONT)
  7441. MeshMaterial.apply(this, [options]);
  7442. this.blendEnable = false;
  7443. var withTexture = options.withTexture;
  7444. var withNormals = options.withNormals;
  7445. this.depthTest = true;
  7446. this.depthMask = true;
  7447. this.blending = true;
  7448. if (options.uniforms.diffuseColorMap) {//&& options.uniforms.diffuseColorMap.toLowerCase().indexOf(".png")) {
  7449. if (typeof options.uniforms.diffuseColorMap === 'string') {
  7450. var diffuseColorMap = options.uniforms.diffuseColorMap.toLowerCase();
  7451. var extension = Path.GetExtension(diffuseColorMap);
  7452. if (extension == ".tif" || extension == ".png") {
  7453. this.translucent = true;
  7454. } else if (diffuseColorMap.slice(0, "data:image/png".length) === "data:image/png") {
  7455. this.translucent = true;
  7456. } else if (diffuseColorMap.slice(0, "data:image/tif".length) === "data:image/tif") {
  7457. this.translucent = true;
  7458. }
  7459. } else if (diffuseColorMap instanceof HTMLCanvasElement
  7460. || diffuseColorMap instanceof HTMLVideoElement
  7461. ) {
  7462. this.translucent = true;
  7463. }
  7464. withTexture = true;
  7465. if (!Cesium.defined(this.uniforms.diffuseColorMap.flipY)) {
  7466. this.uniforms.diffuseColorMap.flipY = false;
  7467. }
  7468. if (!this.uniforms.diffuseColorMap.sampler) {
  7469. var sampler = {};
  7470. sampler.magnificationFilter = WebGLConstants.LINEAR;
  7471. sampler.minificationFilter = WebGLConstants.NEAREST_MIPMAP_LINEAR;
  7472. sampler.wrapS = WebGLConstants.REPEAT;
  7473. sampler.wrapT = WebGLConstants.REPEAT;
  7474. this.uniforms.diffuseColorMap.sampler = sampler;
  7475. }
  7476. } else {
  7477. withTexture = false;
  7478. }
  7479. var vertexShaderUri = null;// "texture_normals.vert";
  7480. var fragmentShaderUri = null; //"texture_normals.frag";
  7481. if (withTexture && withNormals) {
  7482. vertexShaderUri = ShaderChunk.texture_normals_vert;// "texture_normals.vert";
  7483. fragmentShaderUri = ShaderChunk.texture_normals_frag; //"texture_normals.frag";
  7484. } else if (withTexture && !withNormals) {
  7485. vertexShaderUri = ShaderChunk.texture_vert;//"texture.vert";
  7486. fragmentShaderUri = ShaderChunk.texture_frag;// "texture.frag";
  7487. } else if (!withTexture && withNormals) {
  7488. vertexShaderUri = ShaderChunk.normals_vert;// "normals.vert";
  7489. fragmentShaderUri = ShaderChunk.normals_frag;//"normals.frag";
  7490. }
  7491. else {
  7492. vertexShaderUri = ShaderChunk.none_vert;// "none.vert";
  7493. fragmentShaderUri = ShaderChunk.none_frag;// "none.frag";
  7494. }
  7495. this.vertexShader = vertexShaderUri;
  7496. this.fragmentShader = fragmentShaderUri;
  7497. }
  7498. BasicMeshMaterial.prototype = new MeshMaterial();
  7499. return BasicMeshMaterial;
  7500. });
  7501. define('Core/BasicGeometry',[], function () {
  7502. /**
  7503. *
  7504. *@param {Object}options
  7505. *@param {Array<Number>|Float32Array}options.positions
  7506. *@param {Array<Number>|Int32Array}options.indices
  7507. *@param {Array<Number>|Float32Array}[options.normals]
  7508. *@param {Array<Number>|Float32Array}[options.uvs]
  7509. *
  7510. *@memberof Cesium
  7511. *@constructor
  7512. */
  7513. function BasicGeometry(options) {
  7514. this.positions = options.positions;
  7515. this.normals = options.normals;
  7516. this.uvs = options.uvs;
  7517. this.indices = options.indices;
  7518. }
  7519. /**
  7520. *
  7521. *@param {Cesium.BasicGeometry}basicGeometry
  7522. *@return {Cesiumm.Geometry}
  7523. */
  7524. BasicGeometry.createGeometry = function (basicGeometry) {
  7525. if (!basicGeometry.positions) {
  7526. throw new Error("缺少positions参数");
  7527. }
  7528. if (!basicGeometry.indices) {
  7529. throw new Error("缺少indices参数");
  7530. }
  7531. var positions = basicGeometry.positions;
  7532. var normals = basicGeometry.normals;
  7533. var uvs = basicGeometry.uvs;
  7534. var indices = basicGeometry.indices instanceof Int32Array ? basicGeometry.indices : new Int32Array(basicGeometry.indices);
  7535. var attributes = {
  7536. position: new Cesium.GeometryAttribute({
  7537. componentDatatype: Cesium.ComponentDatatype.DOUBLE,
  7538. componentsPerAttribute: 3,
  7539. values: positions instanceof Float32Array ? positions : new Float32Array(basicGeometry.positions)
  7540. })
  7541. };
  7542. if (normals) {
  7543. attributes.normal = new Cesium.GeometryAttribute({
  7544. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  7545. componentsPerAttribute: 3,
  7546. values: normals instanceof Float32Array ? normals : new Float32Array(normals)
  7547. })
  7548. }
  7549. if (uvs) {
  7550. attributes.uv = new Cesium.GeometryAttribute({
  7551. componentDatatype: Cesium.ComponentDatatype.FLOAT,
  7552. componentsPerAttribute: 2,
  7553. values: uvs instanceof Float32Array ? uvs : new Float32Array(uvs)
  7554. })
  7555. }
  7556. var bs = Cesium.BoundingSphere.fromVertices(positions);
  7557. var geo = new Cesium.Geometry({
  7558. attributes: attributes,
  7559. indices: new Int32Array(indices),
  7560. primitiveType: Cesium.PrimitiveType.TRIANGLES,
  7561. boundingSphere: bs
  7562. });
  7563. return geo;
  7564. }
  7565. return BasicGeometry;
  7566. });
  7567. define('Core/PlaneBufferGeometry',[
  7568. 'Core/BasicGeometry'
  7569. ], function (
  7570. BasicGeometry
  7571. ) {
  7572. /**
  7573. *
  7574. *@param {Number}width
  7575. *@param {Number}height
  7576. *@param {Number}widthSegments
  7577. *@param {Number}heightSegments
  7578. *@constructor
  7579. *@memberof Cesium
  7580. */
  7581. function PlaneBufferGeometry(width, height, widthSegments, heightSegments) {
  7582. this.width = width;
  7583. this.height = height;
  7584. this.widthSegments = widthSegments;
  7585. this.heightSegments = heightSegments;
  7586. }
  7587. /**
  7588. *
  7589. *@param {}
  7590. */
  7591. PlaneBufferGeometry.createGeometry = function (planeBufferGeometry) {
  7592. var width = planeBufferGeometry.width,
  7593. height = planeBufferGeometry.height,
  7594. widthSegments = planeBufferGeometry.widthSegments,
  7595. heightSegments = planeBufferGeometry.heightSegments;
  7596. width = width || 1;
  7597. height = height || 1;
  7598. var width_half = width / 2;
  7599. var height_half = height / 2;
  7600. var gridX = Math.floor(widthSegments) || 1;
  7601. var gridY = Math.floor(heightSegments) || 1;
  7602. var gridX1 = gridX + 1;
  7603. var gridY1 = gridY + 1;
  7604. var segment_width = width / gridX;
  7605. var segment_height = height / gridY;
  7606. var ix, iy;
  7607. // buffers
  7608. var indices = [];
  7609. var vertices = [];
  7610. var normals = [];
  7611. var uvs = [];
  7612. // generate vertices, normals and uvs
  7613. for (iy = 0; iy < gridY1; iy++) {
  7614. var y = iy * segment_height - height_half;
  7615. for (ix = 0; ix < gridX1; ix++) {
  7616. var x = ix * segment_width - width_half;
  7617. vertices.push(x, -y, 0);
  7618. normals.push(0, 0, 1);
  7619. uvs.push(ix / gridX);
  7620. uvs.push(1 - (iy / gridY));
  7621. }
  7622. }
  7623. // indices
  7624. for (iy = 0; iy < gridY; iy++) {
  7625. for (ix = 0; ix < gridX; ix++) {
  7626. var a = ix + gridX1 * iy;
  7627. var b = ix + gridX1 * (iy + 1);
  7628. var c = (ix + 1) + gridX1 * (iy + 1);
  7629. var d = (ix + 1) + gridX1 * iy;
  7630. // faces
  7631. indices.push(a, b, d);
  7632. indices.push(b, c, d);
  7633. }
  7634. }
  7635. var geom= BasicGeometry.createGeometry({
  7636. positions: new Float32Array(vertices),
  7637. normals: new Float32Array(normals),
  7638. uvs: new Float32Array(uvs),
  7639. indices: new Int32Array(indices)
  7640. })
  7641. return geom;
  7642. }
  7643. return PlaneBufferGeometry;
  7644. });
  7645. define('Main',[
  7646. 'Core/RendererUtils',
  7647. 'Core/Mesh',
  7648. 'Core/MeshMaterial',
  7649. 'Core/Shaders/ShaderChunk',
  7650. 'Core/MeshVisualizer',
  7651. 'Core/FramebufferTexture',
  7652. 'Core/GeometryUtils',
  7653. 'Core/LOD',
  7654. 'Core/PlaneGeometry',
  7655. 'Core/Rotation',
  7656. 'Core/ReferenceMesh',
  7657. 'Core/BasicMeshMaterial',
  7658. 'Core/BasicGeometry',
  7659. 'Core/Shaders/ShaderLib',
  7660. 'Core/PlaneBufferGeometry',
  7661. 'Util/CSG',
  7662. 'Core/MeshPhongMaterial',
  7663. 'Core/MaterialUtils',
  7664. 'Core/ShaderUtils'
  7665. ], function (
  7666. RendererUtils,
  7667. Mesh,
  7668. MeshMaterial,
  7669. ShaderChunk,
  7670. MeshVisualizer,
  7671. FramebufferTexture,
  7672. GeometryUtils,
  7673. LOD,
  7674. PlaneGeometry,
  7675. Rotation,
  7676. ReferenceMesh,
  7677. BasicMeshMaterial,
  7678. BasicGeometry,
  7679. ShaderLib,
  7680. PlaneBufferGeometry,
  7681. CSG,
  7682. MeshPhongMaterial,
  7683. MaterialUtils,
  7684. ShaderUtils
  7685. ) {
  7686. if (typeof Cesium==='undefined') {
  7687. Cesium = {};
  7688. }
  7689. Cesium.RendererUtils = RendererUtils;
  7690. Cesium.Mesh = Mesh;
  7691. Cesium.MeshMaterial = MeshMaterial;
  7692. Cesium.ShaderChunk = ShaderChunk;
  7693. Cesium.ShaderLib = ShaderLib;
  7694. Cesium.MeshVisualizer = MeshVisualizer;
  7695. Cesium.FramebufferTexture = FramebufferTexture;
  7696. Cesium.GeometryUtils = GeometryUtils;
  7697. Cesium.LOD = LOD;
  7698. Cesium.PlaneGeometry = PlaneGeometry;
  7699. Cesium.Rotation = Rotation;
  7700. Cesium.ReferenceMesh = ReferenceMesh;
  7701. Cesium.BasicMeshMaterial = BasicMeshMaterial;
  7702. Cesium.BasicGeometry = BasicGeometry;
  7703. Cesium.PlaneBufferGeometry = PlaneBufferGeometry;
  7704. Cesium.CSG = CSG;
  7705. Cesium.MeshPhongMaterial = MeshPhongMaterial;
  7706. Cesium.MaterialUtils = MaterialUtils;
  7707. Cesium.ShaderUtils = ShaderUtils;
  7708. return Cesium;
  7709. });
  7710. require([
  7711. 'Main'
  7712. ], function (
  7713. Cesium) {
  7714. 'use strict';
  7715. /*global self*/
  7716. var scope = typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {};
  7717. scope.Cesium = Cesium;
  7718. if (scope.onLoad) {
  7719. scope.onLoad(Cesium)
  7720. }
  7721. }, undefined, true);
  7722. })();