Image.hx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. package hide.view;
  2. private class ImageViewerShader extends hxsl.Shader {
  3. static var SRC = {
  4. @param var compressedTex : Sampler2D;
  5. @param var uncompressedTex : Sampler2D;
  6. @param var textureCube : SamplerCube;
  7. @param var textureArray : Sampler2DArray;
  8. @param var layer : Float;
  9. @param var mipLod : Float;
  10. @param var exposure : Float;
  11. @param var comparisonFactor : Float;
  12. @const var channels : Int;
  13. @const var isCube : Bool;
  14. @const var isArray : Bool;
  15. var pixelColor : Vec4;
  16. var calculatedUV : Vec2;
  17. var transformedNormal : Vec3;
  18. function fragment() {
  19. if( isCube )
  20. pixelColor = textureCube.getLod(transformedNormal, mipLod);
  21. else if( isArray )
  22. pixelColor = textureArray.getLod(vec3(calculatedUV, layer), mipLod);
  23. else {
  24. if (calculatedUV.x > comparisonFactor)
  25. pixelColor = uncompressedTex.getLod(calculatedUV, mipLod);
  26. else
  27. pixelColor = compressedTex.getLod(calculatedUV, mipLod);
  28. }
  29. pixelColor.rgb *= pow(2, exposure);
  30. switch( channels ) {
  31. case 0, 15:
  32. // nothing
  33. case 1:
  34. pixelColor = vec4(pixelColor.rrr, 1.);
  35. case 2:
  36. pixelColor = vec4(pixelColor.ggg, 1.);
  37. case 4:
  38. pixelColor = vec4(pixelColor.bbb, 1.);
  39. case 8:
  40. pixelColor = vec4(pixelColor.aaa, 1.);
  41. default:
  42. if( channels & 1 == 0 ) pixelColor.r = 0;
  43. if( channels & 2 == 0 ) pixelColor.g = 0;
  44. if( channels & 4 == 0 ) pixelColor.b = 0;
  45. if( channels & 8 == 0 ) pixelColor.a = 1;
  46. }
  47. }
  48. }
  49. }
  50. enum ViewMode {
  51. Compressed;
  52. Uncompressed;
  53. Comparison;
  54. }
  55. class Image extends FileView {
  56. var bmp : h2d.Bitmap;
  57. var sliderBmp : h2d.Graphics;
  58. var scene : hide.comp.Scene;
  59. var shader : ImageViewerShader;
  60. var viewMode : ViewMode = Compressed;
  61. var interactive : h2d.Interactive;
  62. var tools : hide.comp.Toolbar;
  63. var cam : Dynamic;
  64. override function onDisplay() {
  65. cleanUp();
  66. element.html('
  67. <div class="flex vertical">
  68. <div class="toolbar"></div>
  69. <div class="scene-partition" style="display: flex; flex-direction: row; flex: 1; overflow: hidden;">
  70. <div class="heaps-scene"></div>
  71. <div class="image-properties">
  72. <div class="title">Image compression</div>
  73. <div class="compression-infos">
  74. <p class="comp-tex-weight">Compressed texture weight : missing info </p>
  75. <p class="uncomp-tex-weight">Uncompressed texture weight : missing info</p>
  76. </div>
  77. <div class="preview-btns">
  78. <input type="button" class="reset-preview" value="Reset preview" title="Reset preview compression."/>
  79. <input type="button" class="save-compression" value="Save" title="Save current compression options into a props.json file."/>
  80. </div>
  81. <input type="button" class="reset-compression" value="Reset compression" title="Remove the current compression\'s rules applied to this texture, from props.json file."/>
  82. </div>
  83. </div>
  84. <div class="identifiers">
  85. <label>Compressed</label>
  86. <label>Uncompressed</label>
  87. </div>
  88. </div>
  89. ');
  90. scene = new hide.comp.Scene(config, null, element.find(".heaps-scene"));
  91. function addField(parent: Element, label:String, title:String, selectClass:String, options:Array<String>) {
  92. var field = new Element('<div class="field">
  93. <label>${label}</label>
  94. <select class="${selectClass}" title="${title}">
  95. </select>
  96. </div>');
  97. var select = field.find(".select-format");
  98. for (opt in options) {
  99. select.append(new Element('<option value="${opt}">${opt}</option>'));
  100. }
  101. parent.append(field);
  102. }
  103. var compressionInfo = element.find(".compression-infos");
  104. var nativeFormat = new Element('<div class="field">
  105. <label>Native format :</label>
  106. <label class="native-format">Unknown</label>
  107. </div>');
  108. compressionInfo.append(nativeFormat);
  109. addField(compressionInfo, "Format :", "Compression format used to compress texture", "select-format", ["none", "BC1", "BC2", "BC3", "BC7", "RGBA", "R16F", "RG16F", "RGBA16F", "R32F", "RG32F", "RGBA32F", "R16U", "RG16U", "RGBA16U"] );
  110. var alphaField = new Element('<div class="field alpha">
  111. <label>Alpha :</label>
  112. <input type="checkbox" class="use-alpha" title="Does the BC1 format use alpha"></input>
  113. <input type="number" class="alpha-threshold" placeholder="Alpha threshold" title="Alpha threshold value"></input>
  114. </div>');
  115. compressionInfo.append(alphaField);
  116. var mipsField = new Element('<div class="field">
  117. <label>Mip maps :</label>
  118. <input type="checkbox" class="mips-checkbox" title="Generate mip maps for the texture"></input>
  119. </div>');
  120. compressionInfo.append(mipsField);
  121. var sizeField = new Element('<div class="field">
  122. <label>Size :</label>
  123. <input type="number" class="size"></input>
  124. <label class="max-size">/ 128 px</label>
  125. </div>');
  126. compressionInfo.append(sizeField);
  127. var format = compressionInfo.find(".select-format");
  128. var mips = compressionInfo.find(".mips-checkbox");
  129. var size = compressionInfo.find(".size");
  130. var useAlpha = compressionInfo.find(".use-alpha");
  131. var alpha = compressionInfo.find(".alpha-threshold");
  132. format.on("change", function(_) {
  133. createPreviewTexture(format, useAlpha, alpha, mips, size);
  134. // Alpha treshold make sense for BC1 format
  135. if (format.val() != "BC1")
  136. alpha.parent().css({"display":"none"});
  137. else
  138. alpha.parent().css({"display":"flex"});
  139. if (format.val() == "none")
  140. mips.parent().css({"display":"none"});
  141. else
  142. mips.parent().css({"display":"flex"});
  143. });
  144. useAlpha.on("change", function(_) {
  145. if (useAlpha.is(':checked')) {
  146. alpha.removeAttr("disabled");
  147. if (alpha.val() == null || alpha.val() == "")
  148. alpha.val(128);
  149. }
  150. else {
  151. alpha.prop("disabled", true);
  152. }
  153. createPreviewTexture(format, useAlpha, alpha, mips, size);
  154. });
  155. alpha.on("change", function(_) {
  156. createPreviewTexture(format, useAlpha, alpha, mips, size);
  157. });
  158. size.on("change", function(_) {
  159. createPreviewTexture(format, useAlpha, alpha, mips, size);
  160. });
  161. mips.on("change", function(_) {
  162. createPreviewTexture(format, useAlpha, alpha, mips, size);
  163. });
  164. var fs:hxd.fs.LocalFileSystem = Std.downcast(hxd.res.Loader.currentInstance.fs, hxd.fs.LocalFileSystem);
  165. @:privateAccess var textureConvertRule = fs.convert.getConvertRule(state.path);
  166. var convertRuleEmpty = textureConvertRule == null || textureConvertRule.cmd == null || textureConvertRule.cmd.params == null;
  167. this.saveDisplayKey = state.path;
  168. this.viewMode = getDisplayState("ViewMode");
  169. if (this.viewMode == null)
  170. this.viewMode = Compressed;
  171. var identifiers = element.find(".identifiers");
  172. identifiers.css(this.viewMode.match(ViewMode.Comparison) ? {"visibility":"inherit"} : {"visibility":"hidden"});
  173. var dirPos = state.path.lastIndexOf("/");
  174. var dirPath = dirPos < 0 ? state.path : state.path.substr(0, dirPos + 1);
  175. var name = dirPos < 0 ? state.path : state.path.substr(dirPos + 1);
  176. var propsFilePath = ide.getPath(dirPath + "props.json");
  177. var resetPreview = element.find(".reset-preview");
  178. resetPreview.on("click", function(_) {
  179. var texMaxSize = getTextureMaxSize();
  180. format.val(convertRuleEmpty ? "none" : textureConvertRule.cmd.params.format);
  181. alpha.val(convertRuleEmpty || Reflect.field(textureConvertRule.cmd.params, "alpha") == null ? null : textureConvertRule.cmd.params.alpha);
  182. size.val(convertRuleEmpty || Reflect.field(textureConvertRule.cmd.params, "size") == null ? texMaxSize : textureConvertRule.cmd.params.size);
  183. if (!convertRuleEmpty && Reflect.field(textureConvertRule.cmd.params, "alpha") != null) {
  184. useAlpha.prop("checked", true);
  185. alpha.removeAttr("disabled");
  186. alpha.val(128);
  187. }
  188. else {
  189. useAlpha.prop("checked", false);
  190. alpha.prop("disabled", true);
  191. alpha.val(null);
  192. }
  193. if (!convertRuleEmpty && textureConvertRule.cmd.params.mips)
  194. mips.prop("checked", true);
  195. else
  196. mips.removeProp("checked");
  197. // Alpha treshold make sense for BC1 format
  198. if (format.val() != "BC1")
  199. alpha.parent().css({"display":"none"});
  200. else
  201. alpha.parent().css({"display":"flex"});
  202. if (format.val() == "none")
  203. mips.parent().css({"display":"none"});
  204. else
  205. mips.parent().css({"display":"flex"});
  206. createPreviewTexture(format, useAlpha, alpha, mips, size);
  207. });
  208. var saveCompression = element.find(".save-compression");
  209. saveCompression.on("click", function(_) {
  210. var texMaxSize = getTextureMaxSize();
  211. var bytes = new haxe.io.BytesOutput();
  212. var convertRule = { };
  213. if (format.val() == "none") {
  214. convertRule = { convert : "none", priority: 10000000 };
  215. }
  216. else {
  217. convertRule = { convert : "dds", format : format.val(), mips : mips.is(':checked'), priority: 10000000 };
  218. if (size.val() != texMaxSize)
  219. Reflect.setField(convertRule, "size", size.val());
  220. if (useAlpha.is(':checked'))
  221. Reflect.setField(convertRule, "alpha", alpha.val());
  222. }
  223. if (sys.FileSystem.exists(propsFilePath)) {
  224. var propsJson = haxe.Json.parse(sys.io.File.getContent(propsFilePath));
  225. if (Reflect.hasField(propsJson, "fs.convert")) {
  226. var fsConvertObj = Reflect.getProperty(propsJson, "fs.convert");
  227. Reflect.setField(fsConvertObj, state.path, convertRule);
  228. }
  229. else {
  230. var fsConvertObj = {} ;
  231. Reflect.setField(fsConvertObj, state.path, convertRule);
  232. Reflect.setProperty(propsJson, "fs.convert", fsConvertObj);
  233. }
  234. var data = haxe.Json.stringify(propsJson, "\t");
  235. bytes.writeString(data);
  236. hxd.File.saveBytes(propsFilePath, bytes.getBytes());
  237. } else {
  238. var fsConvertObj = { };
  239. var pathObj = { };
  240. Reflect.setProperty(pathObj, state.path, convertRule);
  241. Reflect.setProperty(fsConvertObj, "fs.convert", pathObj);
  242. var data = haxe.Json.stringify(fsConvertObj, "\t");
  243. bytes.writeString(data);
  244. hxd.File.saveBytes(propsFilePath, bytes.getBytes());
  245. }
  246. @:privateAccess fs.convert.configs.clear();
  247. @:privateAccess fs.convert.loadConfig(state.path);
  248. var localEntry = @:privateAccess new hxd.fs.LocalFileSystem.LocalEntry(fs, name, state.path, Ide.inst.getPath(state.path));
  249. fs.convert.run(localEntry);
  250. });
  251. var resetCompression = element.find(".reset-compression");
  252. resetCompression.on("click", function(_) {
  253. if (sys.FileSystem.exists(propsFilePath)) {
  254. var rulesObj = haxe.Json.parse(sys.io.File.getContent(propsFilePath));
  255. var fsConvertObj = Reflect.getProperty(rulesObj, "fs.convert");
  256. if (fsConvertObj != null && Reflect.getProperty(fsConvertObj, state.path) != null) {
  257. if(!ide.confirm('Do you really want to remove ${state.path} from ${propsFilePath} ?'))
  258. return;
  259. Reflect.deleteField(fsConvertObj, state.path);
  260. if (Reflect.fields(fsConvertObj).length == 0)
  261. Reflect.deleteField(rulesObj, "fs.convert");
  262. if (Reflect.fields(rulesObj).length == 0) {
  263. sys.FileSystem.deleteFile(propsFilePath);
  264. updateImageCompressionInfos();
  265. replaceImage(ide.getPath(state.path));
  266. return;
  267. }
  268. }
  269. var bytes = new haxe.io.BytesOutput();
  270. var data = haxe.Json.stringify(rulesObj, "\t");
  271. bytes.writeString(data);
  272. hxd.File.saveBytes(propsFilePath, bytes.getBytes());
  273. }
  274. updateImageCompressionInfos();
  275. replaceImage(ide.getPath(state.path));
  276. });
  277. shader = new ImageViewerShader();
  278. tools = new hide.comp.Toolbar(null,element.find(".toolbar"));
  279. tools.addSeparator();
  280. var tgCompressed = tools.addToggle("show-compressed", "file-zip-o", "Show compressed texture", "", function (e) {
  281. tools.element.find(".show-uncompressed").removeAttr("checked");
  282. tools.element.find(".show-comparison").removeAttr("checked");
  283. if (bmp != null) {
  284. this.saveDisplayState("ViewMode", Compressed);
  285. this.viewMode = Compressed;
  286. var identifiers = element.find(".identifiers");
  287. identifiers.css(this.viewMode.match(ViewMode.Comparison) ? {"visibility":"inherit"} : {"visibility":"hidden"});
  288. applyShaderConfiguration();
  289. }
  290. }, this.viewMode.match(Compressed), null, false, false);
  291. tgCompressed.element.addClass("show-compressed");
  292. var tgUncompressed = tools.addToggle("show-uncompressed","file-image-o", "Show uncompressed texture", "", function (e) {
  293. tools.element.find(".show-compressed").removeAttr("checked");
  294. tools.element.find(".show-comparison").removeAttr("checked");
  295. if (bmp != null) {
  296. this.saveDisplayState("ViewMode", Uncompressed);
  297. this.viewMode = Uncompressed;
  298. var identifiers = element.find(".identifiers");
  299. identifiers.css(this.viewMode.match(ViewMode.Comparison) ? {"visibility":"inherit"} : {"visibility":"hidden"});
  300. applyShaderConfiguration();
  301. }
  302. }, this.viewMode.match(Uncompressed), null, false, false);
  303. tgUncompressed.element.addClass("show-uncompressed");
  304. var tgComparison = tools.addToggle("show-comparison","arrows-h", "Show comparison between compressed and uncompressed texture", "", function (e) {
  305. tools.element.find(".show-uncompressed").removeAttr("checked");
  306. tools.element.find(".show-compressed").removeAttr("checked");
  307. if (bmp != null) {
  308. this.saveDisplayState("ViewMode", Comparison);
  309. this.viewMode = Comparison;
  310. var identifiers = element.find(".identifiers");
  311. identifiers.css(this.viewMode.match(ViewMode.Comparison) ? {"visibility":"inherit"} : {"visibility":"hidden"});
  312. applyShaderConfiguration();
  313. }
  314. }, this.viewMode.match(Comparison), null, false, false);
  315. tgComparison.element.addClass("show-comparison");
  316. tools.addSeparator();
  317. // We don't want to load old texture from cache because convert rule might
  318. // have been changed
  319. @:privateAccess fs.fileCache.remove(state.path);
  320. scene.onReady = function() {
  321. scene.loadTexture(state.path, state.path, function(compressedTexture) {
  322. scene.loadTexture(state.path, state.path, function(uncompressedTexture) {
  323. onTexturesLoaded(compressedTexture, uncompressedTexture);
  324. }, false, true);
  325. }, false);
  326. };
  327. }
  328. override function onActivate() {
  329. if (tools != null)
  330. tools.refreshToggles();
  331. }
  332. override function onRebuild() {
  333. if ( scene != null ) {
  334. scene.dispose();
  335. scene = null;
  336. }
  337. super.onRebuild();
  338. }
  339. override function onResize() {
  340. if( bmp == null ) return;
  341. var scale = Math.min(1,Math.min((contentWidth - 20) / bmp.tile.width, (contentHeight - 20) / bmp.tile.height));
  342. var cam2d = Std.downcast(cam, hide.view.l3d.CameraController2D);
  343. if (cam2d != null) {
  344. @:privateAccess cam2d.curPos.set(bmp.tile.width / 2, bmp.tile.width / 2, (1 / bmp.tile.width) * 500);
  345. }
  346. else {
  347. bmp.setScale(scale * js.Browser.window.devicePixelRatio);
  348. bmp.x = -Std.int(bmp.tile.width * bmp.scaleX) >> 1;
  349. bmp.y = -Std.int(bmp.tile.height * bmp.scaleY) >> 1;
  350. }
  351. updateSliderVisual();
  352. }
  353. public function onTexturesLoaded(compressedTexture: Null<h3d.mat.Texture>, uncompressedTexture: Null<h3d.mat.Texture>) {
  354. uncompressedTexture.filter = Nearest;
  355. scene.element.on("wheel", function(_) {
  356. updateSliderVisual();
  357. });
  358. for( i in 0...4 ) {
  359. var name = "RGBA".charAt(i);
  360. tools.addToggle("Channel"+name, "", "Channel "+name, name, function(b) {
  361. shader.channels &= ~(1 << i);
  362. if( b ) shader.channels |= 1 << i;
  363. });
  364. }
  365. if( !compressedTexture.flags.has(Cube) ) {
  366. bmp = new h2d.Bitmap(h2d.Tile.fromTexture(compressedTexture), scene.s2d);
  367. bmp.addShader(shader);
  368. if( compressedTexture.layerCount > 1 ) {
  369. shader.isArray = true;
  370. shader.textureArray = cast(compressedTexture, h3d.mat.TextureArray);
  371. tools.addRange("Layer", function(f) shader.layer = f, 0, 0, compressedTexture.layerCount-1, 1);
  372. } else
  373. shader.compressedTex = compressedTexture;
  374. shader.uncompressedTex = uncompressedTexture;
  375. shader.comparisonFactor = 0.5;
  376. this.cam = new hide.view.l3d.CameraController2D(scene.s2d);
  377. } else {
  378. var r = new h3d.scene.fwd.Renderer();
  379. var ls = new h3d.scene.fwd.LightSystem();
  380. ls.ambientLight.set(1,1,1);
  381. scene.s3d.lightSystem = ls;
  382. scene.s3d.renderer = r;
  383. var sp = new h3d.prim.Sphere(1,64,64);
  384. sp.addNormals();
  385. sp.addUVs();
  386. shader.textureCube = compressedTexture;
  387. shader.isCube = true;
  388. var sp = new h3d.scene.Mesh(sp, scene.s3d);
  389. sp.material.texture = compressedTexture;
  390. sp.material.mainPass.addShader(shader);
  391. sp.material.shadows = false;
  392. this.cam = new h3d.scene.CameraController(5,scene.s3d);
  393. }
  394. if( compressedTexture.flags.has(MipMapped) ) {
  395. compressedTexture.mipMap = Linear;
  396. tools.addRange("MipMap", function(f) shader.mipLod = f, 0, 0, compressedTexture.mipLevels - 1, "mipmap");
  397. }
  398. if( hxd.Pixels.isFloatFormat(compressedTexture.format) ) {
  399. tools.addRange("Exposure", function(f) shader.exposure = f, 0, -10, 10);
  400. }
  401. var compTexMemSize = element.find(".comp-tex-weight");
  402. compTexMemSize.text('Compressed texture weight : ${@:privateAccess floatToStringPrecision(compressedTexture.mem.memSize(compressedTexture) / (1024 * 1024)) } mb');
  403. updateImageCompressionInfos();
  404. applyShaderConfiguration();
  405. onResize();
  406. }
  407. public function applyShaderConfiguration() {
  408. switch (this.viewMode) {
  409. case Compressed:
  410. {
  411. shader.comparisonFactor = 1;
  412. if (interactive != null)
  413. interactive.remove();
  414. if (sliderBmp != null)
  415. sliderBmp.alpha = 0;
  416. }
  417. case Uncompressed:
  418. {
  419. shader.comparisonFactor = 0;
  420. if (interactive != null)
  421. interactive.remove();
  422. if (sliderBmp != null)
  423. sliderBmp.alpha = 0;
  424. }
  425. case Comparison:
  426. {
  427. if (sliderBmp == null)
  428. drawSlider();
  429. else
  430. sliderBmp.alpha = 1;
  431. bmp.addChild(sliderBmp);
  432. var bounds = new h2d.col.Bounds();
  433. sliderBmp.getSize(bounds);
  434. if (interactive != null)
  435. interactive.remove();
  436. interactive = new h2d.Interactive(bmp.tile.width,bmp.tile.height,bmp);
  437. interactive.propagateEvents = true;
  438. interactive.x = bmp.tile.dx;
  439. interactive.y = bmp.tile.dy;
  440. sliderBmp.x = bmp.tile.width / 2.0 - bounds.width / 2.0;
  441. shader.comparisonFactor = 0.5;
  442. var clicked = false;
  443. function updateSlider(e: hxd.Event) {
  444. if (!clicked)
  445. return;
  446. sliderBmp.x = e.relX - (bounds.width * sliderBmp.scaleX) / 2.0;
  447. shader.comparisonFactor = e.relX / interactive.width;
  448. }
  449. interactive.onPush = function (e) {
  450. clicked = true;
  451. updateSlider(e);
  452. }
  453. interactive.onRelease = function (e) {
  454. clicked = false;
  455. }
  456. interactive.onMove = function (e) {
  457. updateSlider(e);
  458. };
  459. }
  460. default:
  461. trace("Not implemented yet");
  462. }
  463. }
  464. public function cleanUp() {
  465. if (scene != null)
  466. scene.dispose();
  467. sliderBmp = null;
  468. if (bmp != null && !bmp.tile.isDisposed())
  469. bmp.tile.dispose();
  470. bmp = null;
  471. interactive = null;
  472. shader = null;
  473. }
  474. public function updateImageCompressionInfos() {
  475. var compressionInfo = element.find(".compression-infos");
  476. // Compression infos fields
  477. var format = compressionInfo.find(".select-format");
  478. var mips = compressionInfo.find(".mips-checkbox");
  479. var size = compressionInfo.find(".size");
  480. var useAlpha = compressionInfo.find(".use-alpha");
  481. var alpha = compressionInfo.find(".alpha-threshold");
  482. var maxSize = compressionInfo.find(".max-size");
  483. var nativeFormat = compressionInfo.find(".native-format");
  484. var dirPos = state.path.lastIndexOf("/");
  485. var name = dirPos < 0 ? state.path : state.path.substr(dirPos + 1);
  486. // We want to clear file system because we don't want to load texture from older texture's convert rules
  487. var fs:hxd.fs.LocalFileSystem = Std.downcast(hxd.res.Loader.currentInstance.fs, hxd.fs.LocalFileSystem);
  488. @:privateAccess fs.convert.configs.clear();
  489. @:privateAccess fs.convert.loadConfig(state.path);
  490. var localEntry = @:privateAccess new hxd.fs.LocalFileSystem.LocalEntry(fs, name, state.path, Ide.inst.getPath(state.path));
  491. try {
  492. fs.convert.run(localEntry);
  493. }
  494. catch (e) onError();
  495. @:privateAccess var texConvRule = fs.convert.getConvertRule(state.path);
  496. var convertRuleEmpty = texConvRule == null || texConvRule.cmd == null || texConvRule.cmd.params == null;
  497. format.val(convertRuleEmpty ? "none" : texConvRule.cmd.params.format);
  498. if (!convertRuleEmpty) {
  499. if (Reflect.field(texConvRule.cmd.params, "alpha") != null) {
  500. useAlpha.prop("checked", true);
  501. alpha.removeAttr("disabled");
  502. alpha.val(128);
  503. }
  504. else {
  505. useAlpha.removeProp("checked");
  506. alpha.prop("disabled", true);
  507. alpha.val(null);
  508. }
  509. }
  510. alpha.val(convertRuleEmpty || Reflect.field(texConvRule.cmd.params, "alpha") == null ? null : texConvRule.cmd.params.alpha);
  511. // Alpha treshold make sense for BC1 format
  512. if (format.val() != "BC1")
  513. alpha.parent().css({"display":"none"});
  514. else
  515. alpha.parent().css({"display":"flex"});
  516. if (format.val() == "none")
  517. mips.parent().css({"display":"none"});
  518. else
  519. mips.parent().css({"display":"flex"});
  520. var strMaxSize = getTextureMaxSize();
  521. size.val(convertRuleEmpty || Reflect.field(texConvRule.cmd.params, "size") == null ? strMaxSize : texConvRule.cmd.params.size);
  522. if (!convertRuleEmpty && texConvRule.cmd.params.mips)
  523. mips.prop("checked", true);
  524. else
  525. mips.removeProp("checked");
  526. var texMaxSize = getTextureMaxSize();
  527. maxSize.text('/${texMaxSize} px');
  528. if(size.val() == null || size.val() == "")
  529. size.val(texMaxSize);
  530. var uncompTWeight = element.find(".uncomp-tex-weight");
  531. uncompTWeight.text('Uncompressed texture weight : ${getTextureMemSize(state.path)} mb');
  532. nativeFormat.text(getTextureNativeFormat(state.path).getName());
  533. }
  534. public function replaceImage(path : String) {
  535. var bytes = sys.io.File.getBytes(path);
  536. var res = hxd.res.Any.fromBytes(path, bytes);
  537. var t = res.toTexture();
  538. if (bmp != null) {
  539. if (!bmp.tile.isDisposed())
  540. bmp.tile.dispose();
  541. bmp.remove();
  542. bmp = null;
  543. }
  544. if( !t.flags.has(Cube) ) {
  545. bmp = new h2d.Bitmap(h2d.Tile.fromTexture(t), scene.s2d);
  546. drawSlider();
  547. bmp.addShader(shader);
  548. if( t.layerCount > 1 ) {
  549. shader.isArray = true;
  550. shader.textureArray = cast(t, h3d.mat.TextureArray);
  551. tools.addRange("Layer", function(f) shader.layer = f, 0, 0, t.layerCount-1, 1);
  552. } else
  553. shader.compressedTex = t;
  554. } else {
  555. var r = new h3d.scene.fwd.Renderer();
  556. var ls = new h3d.scene.fwd.LightSystem();
  557. ls.ambientLight.set(1,1,1);
  558. scene.s3d.lightSystem = ls;
  559. scene.s3d.renderer = r;
  560. var sp = new h3d.prim.Sphere(1,64,64);
  561. sp.addNormals();
  562. sp.addUVs();
  563. shader.textureCube = t;
  564. shader.isCube = true;
  565. var sp = new h3d.scene.Mesh(sp, scene.s3d);
  566. sp.material.texture = t;
  567. sp.material.mainPass.addShader(shader);
  568. sp.material.shadows = false;
  569. }
  570. tools.element.find(".hide-range").remove();
  571. if( t.flags.has(MipMapped) ) {
  572. t.mipMap = Linear;
  573. tools.addRange("MipMap", function(f) shader.mipLod = f, 0, 0, t.mipLevels - 1, "mipmap");
  574. }
  575. if( hxd.Pixels.isFloatFormat(t.format) ) {
  576. tools.addRange("Exposure", function(f) shader.exposure = f, 0, -10, 10);
  577. }
  578. var compTexMemSize = element.find(".comp-tex-weight");
  579. compTexMemSize.text('Compressed texture weight : ${@:privateAccess floatToStringPrecision(t.mem.memSize(t) / (1024 * 1024)) } mb');
  580. applyShaderConfiguration();
  581. onResize();
  582. }
  583. public function createPreviewTexture(format: Element, useAlpha: Element, alpha: Element, mips: Element, size: Element) {
  584. var dirPos = state.path.lastIndexOf("/");
  585. var name = dirPos < 0 ? state.path : state.path.substr(dirPos + 1);
  586. var tmpPath = StringTools.replace(Sys.getEnv("TEMP"), "\\","/") + "/tempTexture.dds";
  587. if (format.val().toString() != "none") {
  588. var comp = new hxd.fs.Convert.CompressIMG("png,tga,jpg,jpeg,dds,envd,envs","dds");
  589. comp.srcPath = Ide.inst.getPath(state.path);
  590. comp.dstPath = Ide.inst.getPath(tmpPath);
  591. comp.originalFilename = name;
  592. if (useAlpha.is(':checked'))
  593. comp.params = { alpha:Std.parseInt(alpha.val()), format:format.val().toString(), mips:mips.is(':checked'), size:Std.parseInt(size.val()) };
  594. else
  595. comp.params = { format:format.val().toString(), mips:mips.is(':checked'), size:Std.parseInt(size.val()) };
  596. try {
  597. comp.convert();
  598. }
  599. catch(e) onError();
  600. }
  601. else {
  602. tmpPath = state.path;
  603. }
  604. replaceImage(Ide.inst.getPath(tmpPath));
  605. }
  606. public function getTextureMaxSize(): Int {
  607. var path = ide.getPath(state.path);
  608. var bytes = sys.io.File.getBytes(path);
  609. var res = hxd.res.Any.fromBytes(path, bytes);
  610. var t = res.toTexture();
  611. return t.width;
  612. }
  613. public function getTextureMemSize(path: String) {
  614. // Return texture mem size in MB
  615. var p = ide.getPath(path);
  616. var bytes = sys.io.File.getBytes(p);
  617. var res = hxd.res.Any.fromBytes(p, bytes);
  618. var t = res.toTexture();
  619. return @:privateAccess floatToStringPrecision(t.mem.memSize(t) / (1024 * 1024));
  620. }
  621. public function getTextureNativeFormat(path: String) {
  622. var p = ide.getPath(path);
  623. var bytes = sys.io.File.getBytes(p);
  624. var res = hxd.res.Any.fromBytes(p, bytes);
  625. var t = res.toTexture();
  626. return t.format;
  627. }
  628. public function floatToStringPrecision(number:Float, ?precision=2) {
  629. number *= Math.pow(10, precision);
  630. return Math.round(number) / Math.pow(10, precision);
  631. }
  632. public function updateSliderVisual() {
  633. var cam2d = Std.downcast(cam, hide.view.l3d.CameraController2D);
  634. if (cam2d != null && sliderBmp != null) {
  635. var oldWidth = sliderBmp.getSize().width;
  636. @:privateAccess sliderBmp.scaleX = (1 / (cam2d.curPos.z)) * 2;
  637. var offset = sliderBmp.getSize().width - oldWidth;
  638. sliderBmp.x -= offset;
  639. }
  640. // todo : handle slider zoom for cam 3d
  641. }
  642. public function drawSlider() {
  643. if (sliderBmp == null)
  644. sliderBmp = new h2d.Graphics(scene.s2d);
  645. sliderBmp.clear();
  646. sliderBmp.beginFill(0xFFFFFF, 1);
  647. sliderBmp.drawRect(0,0,2, shader.compressedTex.height);
  648. sliderBmp.endFill();
  649. updateSliderVisual();
  650. }
  651. public function onError() {
  652. Ide.inst.quickError('Can\'t load texture with this compression parameters, original texture is loaded instead!');
  653. }
  654. static var _ = Extension.registerExtension(Image,hide.Ide.IMG_EXTS.concat(["envd","envs"]),{ icon : "picture-o", name: "Image" });
  655. }