12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732 |
- IPE.app = {};
- IPE.helper = {};
- IPE.interceptors = {};
- String.prototype.endsWith = function(suffix) {
- return this.indexOf(suffix, this.length - suffix.length) !== -1;
- };
- Array.prototype.last = function() {
- return this[this.length-1];
- }
- IPE.app = {
- init : function(config) {
- var headerHeight = $('header').height();
- if($(window).height() < 500) {
- $("body").animate({ scrollTop: headerHeight }, "slow");
- }
- $.each(IPE.interceptors, function(index, interceptor) {
- interceptor.init();
- });
- Globals.init();
- IPE.app.initializeHelper();
- IPE.app.bindEvents();
- IPE.app.initData();
- tempRenderer = new THREE.WebGLRenderer();
- maximumTextureSize = tempRenderer.context.getParameter(tempRenderer.context.MAX_TEXTURE_SIZE);
- // we have to take an power of 2 less
- maximumTextureSize /= 2;
- if(config.defaultSize > maximumTextureSize) {
- config.defaultSize = maximumTextureSize;
- }
- // Getting info file
- $.ajax({
- url: infoUrl + config.defaultSize,
- success: function (data) {
- textureInfo = data;
- originalSizeArray[0] = textureInfo.originalSize.sizex;
- originalSizeArray[1] = textureInfo.originalSize.sizey;
- originalSizeArray[2] = textureInfo.originalSize.sizez;
- imgInfo = data.info;
- currentVolumeDimension.xmin = 0;
- currentVolumeDimension.xmax = textureInfo.originalSize.sizex;
- currentVolumeDimension.ymin = 0;
- currentVolumeDimension.ymax = textureInfo.originalSize.sizey;
- currentVolumeDimension.zmin = imgInfo.imgMin;
- currentVolumeDimension.zmax = imgInfo.imgMax;
- // downloading first image and starting
- helper.downloadImage(spriteUrl + textureInfo.sprites[0][0].$oid, 0, 0, true);
- $(document).trigger('basicsReady');
- },
- dataType: 'json'
- });
- container = document.getElementById( 'container' );
- $container = $(container);
- containerHeader = document.getElementById( 'container-header' );
- $containerHeader = $(containerHeader);
- containerOverview = document.getElementById('container-overview');
- $containerOverview = $(containerOverview);
- statsHelper = new StatsHelper($containerHeader.children('#container-stats'));
- // until now, it has to be initialized here, needs a new internal structure
- zoomHelper = new ZoomHelper();
- $(window).on('scroll', function(e) {
- if($(this).scrollTop() >= headerHeight) {
- $container.css('position', 'relative');
- $container.css('top', $(this).scrollTop() - headerHeight);
- } else {
- $container.css('top', 0);
- }
- });
- },
- initializeHelper: function() {
- helper = new Helper();
- geometryHelper = new GeometryHelper();
- stepHelper = new StepHelper();
- overviewHelper = new OverviewHelper();
- transferHelper = new TransferHelper();
- opacityPlotter = new OpacityPlotter();
- },
- initData: function() {
- volumeId = $('#volumeId').val();
- $resSpan = $('span#currentRes');
- volumeUrl = IPE.util.buildUrl('volumes/' + volumeId + '/');
- infoUrl = volumeUrl + 'texture-info/';
- spriteUrl = volumeUrl + 'sprite/';
- waitDiv = $('div#wait');
- helper.initializeShaders(IPE.util.buildUrl('static/shaders/three-shader.vert'), function(script) {
- vertexShader = script
- });
- helper.initializeShaders(IPE.util.buildUrl('static/shaders/three-shader-simple.frag'), function(script) {
- fragmentSimleShader = script
- });
- helper.initializeShaders(IPE.util.buildUrl('static/shaders/three-shader.frag'), function(script) {
- fragmentShader = script
- });
- },
- bindEvents : function() {
- $(document).on('firstImageOnLoad',function (e, firstImageParams){
- initTextures(imgInfo, firstImageParams, true);
- initFrameControls();
- stepHelper.initStepControls();
- initSliders();
- });
- $(document).on('imageOnLoad', function(e, imageParams) {
- initTextures(imgInfo, imageParams, false);
- if(useDownloadedTextureImmediately) {
- updateTexture();
- useDownloadedTextureImmediately = false;
- updateFrameControls();
- }
- });
- $(document).on('firstFrameSpritesCompleted', function() {
- init();
- addResolutionLinks();
- overviewHelper.initOverview(containerOverview);
- animate();
- });
- showPopup = false;
- $('#save-canvas').click(function(e, params) {
- if(params != undefined && params.source != undefined && params.source == 'animate-function') {
- window.open(params.imageUrl);
- return false;
- } else {
- saveImage = true;
- return false;
- }
- });
- $(window).on('resize', function() {
- var rendererSizeHolder = calculateWidthHeight();
- width = rendererSizeHolder.width.px;
- height = rendererSizeHolder.height.px;
- cameraRTT.aspect = width / height;
- cameraRTT.updateProjectionMatrix();
- camera.aspect = width / height;
- camera.updateProjectionMatrix();
- renderer.setSize( width, height );
- renderer.domElement.style.width = rendererSizeHolder.width.percent + '%';
- renderer.domElement.style.height = rendererSizeHolder.height.percent + '%';
- });
- $resolutionLinks.on('click', 'a', function(e) {
- e.preventDefault();
- e.stopPropagation();
- var $this = $(this);
- if($this.attr('href') == undefined) {
- return false;
- }
- requestedSize = $this.attr('data');
- $('.res-link').each(function(index, value) {
- var $value = $(value);
- $value.attr('href', '#');
- });
- $this.removeAttr('href');
- $.ajax({
- // todo test after remove of sync flag
- url: infoUrl + requestedSize,
- success: function (data) {
- framesDownloaded = 0;
- textures = {};
- currentTexture = 0;
- textureInfo = data;
- imgInfo = data.info;
- imgMin = imgInfo.imgMin;
- imgMax = imgInfo.imgMax;
- useDownloadedTextureImmediately = true;
- helper.downloadImage(spriteUrl + textureInfo.sprites[0][0].$oid, 0, 0, false);
- $resSpan.text(requestedSize);
- if($('input#hide-content-small-devices').is(':visible')) {
- $('input#hide-content-small-devices').trigger('click');
- }
- },
- dataType: 'json'
- });
- return false;
- });
- $('div.controls').on('click', function() {
- var $this = $(this),
- bottomControlsContainer = $('div#bottom-controls-container'),
- bottomControls = $('div#bottom-controls'),
- filledById = '',
- thisControlHolder = null;
- filledById = hideBottomControlsContainer();
- if(filledById === $this.attr('id')) {
- return;
- }
- thisControlHolder = $this.children('.control-holder')[0];
- thisControlHolder = $(thisControlHolder);
- bottomControls.append(thisControlHolder.children());
- bottomControls.attr('filledBy', $this.attr('id'));
- bottomControlsContainer.removeClass('hidden');
- // inform, that it is showed
- $this.trigger('controlsShowed');
- });
- $('input#hide-bottom-controls-container').on('click', function() {
- hideBottomControlsContainer();
- });
- $('div#menu-buttons-small-devices input').on('click', function() {
- var $this = $(this),
- target = $this.attr('data'),
- $target = $('#' + target),
- $overlay = $('div#overlay-small-devices'),
- $content = $('div#content-small-devices');
- $overlay.attr('source', target);
- $content.append($target.children());
- $overlay.show();
- });
- $('input#hide-content-small-devices').on('click', function() {
- var $overlay = $('div#overlay-small-devices'),
- $content = $('div#content-small-devices'),
- source = $overlay.attr('source'),
- $source = $('#' + source);
- $overlay.hide();
- $overlay.attr('source', '');
- $source.append($content.children());
- });
- var buttonAdvCons = $('input#show-adv-con');
- buttonAdvCons.on('click', function() {
- var advCons = $('div#advanced-controls');
- if(advCons.hasClass('hidden')) {
- advCons.removeClass('hidden');
- buttonAdvCons.val('hide adv cons');
- } else {
- advCons.addClass('hidden');
- buttonAdvCons.val('show adv cons');
- }
- });
- $(document).on('initFinished', function() {
- $canvas.addClass('context-menu');
- $.contextMenu({
- selector: 'canvas.context-menu',
- callback: function(key, options) {
- if(key === 'save') {
- saveImage = true;
- }
- },
- items: {
- "save": {name: "Open image in new tab"}
- }
- });
- });
- $('input#adjust-isodata-thresholding-bottom-controls-container').on('click', function() {
- console.log(textureInfo.info.thresholdIndex_isodata);
- GenericSlider.setPosSlider(
- slider = $( "#gray-slider" ),
- sliderInputs = $('input.gray'),
- minGray,
- textureInfo.info.thresholdIndex_isodata
- );
- $(document).trigger('opacityBordersChanged', { minGray: minGray, maxGray: textureInfo.info.thresholdIndex_isodata});
- });
- $('input#adjust-otsu-thresholding-bottom-controls-container').on('click', function() {
- console.log(textureInfo.info.thresholdIndex_otsu);
- GenericSlider.setPosSlider(
- slider = $( "#gray-slider" ),
- sliderInputs = $('input.gray'),
- minGray,
- textureInfo.info.thresholdIndex_otsu
- );
- $(document).trigger('opacityBordersChanged', { minGray: minGray, maxGray: textureInfo.info.thresholdIndex_otsu});
- });
- $('input#adjust-yen-thresholding-bottom-controls-container').on('click', function() {
- console.log(textureInfo.info.thresholdIndex_yen);
- GenericSlider.setPosSlider(
- slider = $( "#gray-slider" ),
- sliderInputs = $('input.gray'),
- minGray,
- textureInfo.info.thresholdIndex_yen
- );
- $(document).trigger('opacityBordersChanged', { minGray: minGray, maxGray: textureInfo.info.thresholdIndex_yen});
- });
- }
- }
- function initTextures(imgInfo, imageParams, whileInit) {
- // set initial array to index
- if(textures[imageParams.textureIndex] == undefined
- || textures[imageParams.textureIndex] == null) {
- textures[imageParams.textureIndex] = [];
- }
- // using texture
- texture = initTexture(imageParams.texture);
- textures[imageParams.textureIndex].push(texture);
- // fetch new sprites of same time frame
- if(imageParams.spriteIndex < imgInfo.numberOfSprites - 1) {
- nextSpriteIndex = imageParams.spriteIndex + 1;
- nextSpriteId = textureInfo.sprites[imageParams.textureIndex][nextSpriteIndex].$oid
- helper.downloadImage(spriteUrl + nextSpriteId, imageParams.textureIndex, nextSpriteIndex, whileInit);
- return;
- }
- // inform the rest, that the first frame is loaded completely
- if(whileInit && imageParams.textureIndex == 0) {
- $(document).trigger('firstFrameSpritesCompleted');
- }
- // todo some logic
- if(!imgInfo.multipleFrames) {
- currentTexture = 0;
- return;
- } else {
- var numberOfFrames = Object.keys(textureInfo.sprites).length,
- nextIndex = null,
- nextFrameName = null,
- nextFramePath = null;
- framesDownloaded++;
- if(framesDownloaded == 1) {
- currentTexture = 0;
- }
- currentMaxFrame = imgInfo.frameFrom + framesDownloaded - 1;
- if(framesDownloaded > 1) {
- // updating frame control maximums
- updateFrameControlsMaxFrame();
- }
- if(numberOfFrames == framesDownloaded) {
- return;
- } else {
- nextIndex = framesDownloaded;
- nextFrameName = textureInfo.sprites[nextIndex][0].$oid;
- var framePath = spriteUrl + nextFrameName;
- helper.downloadImage(framePath, nextIndex, false);
- }
- }
- }
- function initTexture(texture) {
- texture.magFilter = THREE.LinearFilter;
- texture.minFilter = THREE.LinearFilter;
- texture.needsUpdate = true;
- return texture;
- }
- function getCurrentTexture() {
- return textures[currentTexture];
- }
- function useFrameControls() {
- return (imgInfo.multipleFrames && (imgInfo.frameTo - imgInfo.frameFrom) != 0);
- }
- function initFrameControls() {
- if(!useFrameControls()) {
- return;
- }
- $('#frame-controls').removeClass('hidden');
- var $frameSlider = $('#frame-slider'),
- $playButton = $('#frame-play'),
- $pauseButton = $('#frame-pause'),
- $currentFrameInput = $('#currentFrame'),
- playId = $playButton.attr('id'),
- pauseId = $pauseButton.attr('id'),
- minFrame = imgInfo.frameFrom;
- $currentFrameInput.val(minFrame);
- var play = function() {
- if(Object.keys(textures).length == 1) {
- console.warn('only one texture loaded, can not play yet');
- return;
- }
- $playButton.addClass('hidden');
- $pauseButton.removeClass('hidden');
- playFrames = true;
- $frameSlider.slider({disabled: true});
- $currentFrameInput.prop('disabled', true);
- }
- var pause = function() {
- $playButton.removeClass('hidden');
- $pauseButton.addClass('hidden');
- playFrames = false;
- $frameSlider.slider({disabled: false});
- $currentFrameInput.prop('disabled', false);
- }
- $('.frame-button').click(function() {
- var $this = $(this),
- thisId = $this.attr('id');
- if(thisId == playId) {
- play();
- } else if(thisId == pauseId) {
- pause();
- }
- });
- $(document).on('zoomActionFinished', function(e, params) {
- zoomedIn = params.zoomAction == 'zoomIn';
- if(zoomedIn) {
- pause();
- currentTexture = minFrame + params.textureNumber;
- updateFrameControls();
- $frameSlider.slider({disabled: true});
- $currentFrameInput.prop('disabled', true);
- $playButton.prop('disabled', true);
- $pauseButton.prop('disabled', true);
- } else {
- $frameSlider.slider({disabled: false});
- $currentFrameInput.prop('disabled', false);
- $playButton.prop('disabled', false);
- $pauseButton.prop('disabled', false);
- }
- });
- $frameSlider.slider(
- {
- min: minFrame,
- max: currentMaxFrame,
- slide: function( event, ui ) {
- currentTexture = ui.value - minFrame;
- updateTexture();
- $currentFrameInput.val(ui.value);
- }
- }
- );
- $currentFrameInput.change(function() {
- var value = parseInt($(this).val());
- if(value >= imgInfo.frameFrom && currentMaxFrame >= value) {
- currentTexture = value - minFrame;
- updateTexture();
- $frameSlider.slider('value', value);
- } else {
- $(this).val($frameSlider.slider('value'));
- }
- });
- }
- function updateFrameControlsMaxFrame() {
- if(!useFrameControls()) {
- return;
- }
- var $frameSlider = $('#frame-slider');
- $frameSlider.slider('option', 'max', currentMaxFrame);
- }
- function updateFrameControls() {
- if(!useFrameControls()) {
- return;
- }
- var $frameSlider = $('#frame-slider'),
- $currentFrameInput = $('#currentFrame'),
- minFrame = imgInfo.frameFrom,
- value = currentTexture + minFrame;
- $frameSlider.slider('value', value);
- $currentFrameInput.val(value);
- }
- function init() {
- rendererSizeHolder = calculateWidthHeight();
- width = rendererSizeHolder.width.px;
- height = rendererSizeHolder.height.px;
- //width = window.innerWidth;
- //height = window.innerHeight;
- camera = new THREE.PerspectiveCamera( 45, width / height, .1, 1000 );
- camera.position.z = 2;
- cameraRTT = new THREE.PerspectiveCamera( 45, width / height, .1, 1000 );
- cameraRTT.position.z = 2;
- scene = new THREE.Scene();
- sceneRTT = new THREE.Scene();
- rtTexture = new THREE.WebGLRenderTarget( width, height, { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat } );
- var geometry = geometryHelper.createBoxGeometry(originalDimension, currentVolumeDimension);
- var attributes = {
- frontColor: {type: 'c', value: [] }
- }
- material = new THREE.ShaderMaterial({
- attributes: attributes,
- vertexShader: vertexShader,
- fragmentShader: fragmentSimleShader,
- side: THREE.FrontSide
- });
- var spriteMaps = getCurrentTexture();
- var transferImageData = transferHelper.getCurrentTransferFunction();
- var transferTexture = new THREE.Texture(transferImageData);
- transferTexture.needsUpdate = true;
- var uniforms = {
- tBackground: {type: 't', value: rtTexture},
- tvSlices: {type: 'tv', value: spriteMaps},
- tTransfer: { type: 't', value: transferTexture},
- steps: {type: 'f', value: 100},
- numberOfSlices: {type: 'f', value: imgInfo.numberOfSlices },
- numberOfSprites: {type: 'f', value: imgInfo.numberOfSprites },
- slicesPerSprite: {type: 'f', value: imgInfo.slicesPerSprite },
- slicesOverX: {type: 'f', value: imgInfo.slicesOverX },
- slicesOverY: {type: 'f', value: imgInfo.slicesOverY },
- };
- materialScreen = new THREE.ShaderMaterial({
- attributes: attributes,
- uniforms: uniforms,
- vertexShader: vertexShader,
- fragmentShader: fragmentShader,
- side: THREE.BackSide,
- transparent: true
- });
- backgroundBox = new THREE.Mesh(geometry, material);
- sceneRTT.add(backgroundBox);
- frontBox = new THREE.Mesh(geometry, materialScreen);//
- scene.add(frontBox);
- objectsToIntersect.push(frontBox);
- translateBoxes(-0.5, -0.5, -0.5 * currentVolumeDimension.getZStretchFactor());
- rotateBoxesX(Math.PI / -2);
- //rotateBoxesY(Math.PI);
- //rotateBoxesZ(Math.PI);
- renderer = new THREE.WebGLRenderer();
- renderer.setSize(width, height);
- renderer.domElement.style.width = rendererSizeHolder.width.percent + '%';
- renderer.domElement.style.height = rendererSizeHolder.height.percent + '%';
- renderer.setClearColor(0xffffff, 1);
- container.appendChild(renderer.domElement);
- $canvas = $('canvas', $container);
- controls1 = new THREE.OrbitControls( camera, renderer.domElement );
- controls1.damping = 0.2;
- controls2 = new THREE.OrbitControls( cameraRTT, renderer.domElement );
- controls2.damping = 0.2;
- rendererContext = renderer.context;
- raycaster = new THREE.Raycaster();
- $(document).trigger('initFinished');
- }
- function rotateBoxesX(radian) {
- rotationMatrix = new THREE.Matrix4().makeRotationX(radian);
- rotateBoxes(rotationMatrix);
- }
- function rotateBoxesY(radian) {
- rotationMatrix = new THREE.Matrix4().makeRotationY(radian);
- rotateBoxes(rotationMatrix);
- }
- function rotateBoxesZ(radian) {
- rotationMatrix = new THREE.Matrix4().makeRotationZ(radian);
- rotateBoxes(rotationMatrix);
- }
- function rotateBoxes(matrix) {
- backgroundBox.applyMatrix(rotationMatrix);
- frontBox.applyMatrix(rotationMatrix);
- }
- function translateBoxes(x, y, z) {
- translationMatrix = new THREE.Matrix4().makeTranslation(x, y, z);
- backgroundBox.applyMatrix(translationMatrix);
- frontBox.applyMatrix(translationMatrix);
- }
- function initSliders() {
- initLayerSliders();
- // init gray value slider
- GenericSlider.initSlider(
- slider = $( "#gray-slider" ),
- sliderInputs = $('input.gray'),
- minGray,
- maxGray,
- minGray,
- maxGray,
- function(values) {
- $(document).trigger(
- 'opacityBordersChanged',
- {
- minGray: values[0],
- maxGray : values[1]
- }
- );
- }
- );
- $('#gray-slider-container').on('controlsShowed', function() {
- var values = $("#gray-slider").slider('values');
- $(document).trigger('opacityBordersChanged', { minGray: values[0], maxGray: values[1] });
- });
- GenericSlider.initSimpleSlider(
- slider = $('#background-slider'),
- sliderInput = $('#background-input'),
- startVal = 255,
- 0,
- 255,
- function(value) {
- var colorFloat = calculateGrayFloat(value);
- renderer.setClearColor(
- new THREE.Color(colorFloat, colorFloat, colorFloat),
- 1
- );
- }
- );
- }
- function initLayerSliders() {
- // init xlayer slider
- GenericSlider.initSlider(
- $( "#xlayer-slider" ),
- sliderInputs = $('input.xlayer'),
- currentVolumeDimension.xmin,
- currentVolumeDimension.xmax,
- currentVolumeDimension.xmin,
- currentVolumeDimension.xmax,
- function(values) {
- dimMin = currentVolumeDimension.xmin;
- dimMax = currentVolumeDimension.xmax;
- currentDimension.xmin = calculateLayerFloat(values[0], dimMin, dimMax);
- currentDimension.xmax = calculateLayerFloat(values[1], dimMin, dimMax);
- updateCubeLayers(currentDimension);
- },
- function() {
- values = Array(2);
- values[0] = calculateLayerInt(currentDimension.xmin, currentVolumeDimension.xmin, currentVolumeDimension.xmax );
- values[1] = calculateLayerInt(currentDimension.xmax, currentVolumeDimension.xmin, currentVolumeDimension.xmax );
- return values;
- }
- );
- // init ylayer slider
- GenericSlider.initSlider(
- $( "#ylayer-slider" ),
- sliderInputs = $('input.ylayer'),
- currentVolumeDimension.ymin,
- currentVolumeDimension.ymax,
- currentVolumeDimension.ymin,
- currentVolumeDimension.ymax,
- function(values) {
- dimMin = currentVolumeDimension.ymin;
- dimMax = currentVolumeDimension.ymax;
- currentDimension.ymin = calculateLayerFloat(values[0], dimMin, dimMax);
- currentDimension.ymax = calculateLayerFloat(values[1], dimMin, dimMax);
- updateCubeLayers(currentDimension);
- },
- function() {
- values = Array(2);
- values[0] = calculateLayerInt(currentDimension.ymin, currentVolumeDimension.ymin, currentVolumeDimension.ymax );
- values[1] = calculateLayerInt(currentDimension.ymax, currentVolumeDimension.ymin, currentVolumeDimension.ymax );
- return values;
- }
- );
- // init zlayer slider
- GenericSlider.initSlider(
- $( "#zlayer-slider" ),
- sliderInputs = $('input.zlayer'),
- currentVolumeDimension.zmin,
- currentVolumeDimension.zmax,
- currentVolumeDimension.zmin,
- currentVolumeDimension.zmax,
- function(values) {
- dimMin = currentVolumeDimension.zmin;
- dimMax = currentVolumeDimension.zmax;
- currentDimension.zmin = calculateLayerFloat(values[0], dimMin, dimMax),
- currentDimension.zmax = calculateLayerFloat(values[1], dimMin, dimMax);
- updateCubeLayers(currentDimension);
- },
- function() {
- values = Array(2);
- values[0] = calculateLayerInt(currentDimension.zmin, currentVolumeDimension.zmin, currentVolumeDimension.zmax );
- values[1] = calculateLayerInt(currentDimension.zmax, currentVolumeDimension.zmin, currentVolumeDimension.zmax );
- return values;
- }
- );
- }
- function repositionLayerSliders() {
- initLayerSliders();
- $.each($('.slider.layer'), function(index, value) {
- $(value).trigger('reposition');
- });
- updateCubeLayers(currentDimension);
- }
- var prevTime = Date.now();
- var fps = 0;
- var frames = 0;
- function animate() {
- requestAnimationFrame( animate );
- $container.trigger('animation');
- var numberOfTextures = Object.keys(textures).length;
- var now = Date.now();
- frames++;
- if(now > prevTime + 1000) {
- fps = (frames * 1000) / (now - prevTime);
- if(adjustSteps) {
- if(fps < 10) {
- stepHelper.decreaseSteps();
- } else if(fps > 15) {
- stepHelper.increaseSteps();
- }
- }
- prevTime = now;
- frames = 0;
- }
- if(playFrames && numberOfTextures > 1) {
- var timeStamp = (new Date()).getTime();
- if(timeStamp - textureTimestamp > 400) {
- currentTexture++;
- if(currentTexture >= numberOfTextures) {
- currentTexture = 0;
- }
- updateTexture();
- textureTimestamp = timeStamp;
- updateFrameControls();
- }
- }
- if(nextCubeDeletionTimeStamp == null && intersectCubesTimeStamps.length != 0) {
- nextCubeDeletionTimeStamp = intersectCubesTimeStamps.shift();
- }
- if((Date.now() - nextCubeDeletionTimeStamp) > 1500) {
- cubeToDelete = intersectCubes.shift();
- scene.remove(cubeToDelete);
- nextCubeDeletionTimeStamp = null;
- }
- if(transferHelper.transferFunctionChanged()) {
- var transfer = new THREE.Texture(transferHelper.getCurrentTransferFunction());
- transfer.needsUpdate = true;
- materialScreen.uniforms.tTransfer.value = transfer;
- }
- cameraPoint = camera.position.clone();
- overviewHelper.updateCameraPosition(cameraPoint);
- statsHelper.update();
- controls1.update();
- controls2.update();
- render();
- if(saveImage) {
- $('#save-canvas').trigger('click', { source: 'animate-function', imageUrl: renderer.domElement.toDataURL() });
- saveImage = false;
- }
- }
- function updateTexture(textures) {
- if(textures == undefined || textures == null) {
- textures = getCurrentTexture();
- }
- $.each(textures, function(index, texture) {
- value.needsUpdate = true;
- });
- materialScreen.uniforms.tvSlices.value = textures;
- }
- function render() {
- renderer.clear();
- renderer.context.clearDepth(-50.0);
- renderer.context.depthFunc(renderer.context.GEQUAL);
- renderer.render(sceneRTT, cameraRTT, rtTexture, true);
- renderer.context.clearDepth(50.0);
- renderer.context.depthFunc(renderer.context.LEQUAL);
- renderer.render(scene, camera);
- overviewHelper.render();
- }
- function updateCubeLayers(geometryDimension) {
- var geometry = geometryHelper.createBoxGeometry(geometryDimension, currentVolumeDimension);
- var colorArray = geometry.attributes.frontColor.array,
- positionArray = geometry.attributes.position.array;
- frontBox.geometry.attributes.frontColor.array = colorArray;
- frontBox.geometry.attributes.frontColor.needsUpdate = true;
- frontBox.geometry.attributes.position.array = positionArray;
- frontBox.geometry.attributes.position.needsUpdate = true;
- }
- // invert function of calculateLayerFloat
- function calculateLayerInt(position, dimMin, dimMax) {
- if(position <= 0.005) {
- return dimMin;
- }
- if(position >= 0.995) {
- return dimMax;
- }
- value = Math.round(position * (dimMax - dimMin) + dimMin);
- return value;
- }
- // calculate the float value for a layer input integer
- // 150 of [0, 299] will be 0.5
- function calculateLayerFloat(value, dimMin, dimMax) {
- var floatVal = (value - dimMin) / (dimMax - dimMin);
- if (floatVal == 0) {
- return 0.005;
- }
- if (floatVal == 1) {
- return 0.995;
- }
- return floatVal;
- }
- function calculateGrayFloat(value) {
- return value / 255.0;
- }
- function distance (v1, v2) {
- dx = v1.x - v2.x;
- dy = v1.y - v2.y;
- dz = v1.z - v2.z;
- return Math.sqrt(dx*dx+dy*dy+dz*dz);
- }
- function calculateWidthHeight() {
- downScaleFactor = 0.66;
- valueholder = {
- height: {},
- width: {}
- }
- containerHeight = $container.height();
- volumeInfoHeight = $('#volume-information').height();
- headerHeight = $('header').height();
- valueholder.height.px = (containerHeight - volumeInfoHeight) * downScaleFactor;
- volumeInfoHeightPercent = Math.floor(volumeInfoHeight / containerHeight * 100);
- valueholder.height.percent = 100 - volumeInfoHeightPercent;
- valueholder.width.px = $container.width() * downScaleFactor;
- valueholder.width.percent = 100;
- return valueholder;
- }
- function hideBottomControlsContainer() {
- var bottomControlsContainer = $('div#bottom-controls-container'),
- bottomControls = $('div#bottom-controls'),
- filledById = bottomControls.attr('filledBy'),
- filledBy = $('#' + filledById);
- // writing data back to original, because append MOVES the children
- if(filledBy.length == 1) {
- filledBy = $(filledBy[0]);
- filledByControlHolder = filledBy.children('.control-holder')[0];
- $(filledByControlHolder).append(bottomControls.children());
- }
- bottomControls.attr('filledBy', '');
- bottomControlsContainer.addClass('hidden');
- return filledById;
- }
- function addResolutionLinks() {
- $resSpan.text(config.defaultSize);
- textureSizes = config.textureSizes;
- textureSizes.forEach(function(size) {
- if(size > maximumTextureSize) {
- return;
- }
- href = size == config.defaultSize ? '' : 'href="#"';
- $resolutionLinks.append('<a '+href+' class="res-link" data="'+size+'">'+size+'</a> ');
- });
- }
- ;var volumeId;
- var stats, container, $container, containerHeader, $containerHeader, $canvas, cameraRTT, camera, sceneRTT, scene, renderer, controls, controls2;
- var maximumTextureSize;
- var containerOverview, $containerOverview;
- var $resSpan;
- var $resolutionLinks;
- var raycaster;
- var width, height;
- var steps, adjustSteps;
- var rtTexture, material;
- var backgroundBox, frontBox;
- var objectsToIntersect = [];
- var minGray = 5, maxGray = 255;
- var originalDimension,
- zoomedDimension,
- currentDimension,
- originalVolumeDimension,
- zoomedVolumeDimension,
- currentVolumeDimension,
- volumeUrl,
- infoUrl,
- spriteUrl,
- imgInfo = null,
- textureInfo = null,
- originalSizeArray = Array(3),
- zoomedInfo,
- rotationMatrix;
- var textures = {},
- currentTexture = 0,
- useDownloadedTextureImmediately = false,
- textureTimestamp = (new Date()).getTime(),
- playFrames = false,
- currentMaxFrame = 0;
- var framesDownloaded = 0,
- cachedImages = {};
- var vertexShader = null,
- fragmentSimleShader = null,
- fragmentShader = null;
- var intersectCubes = [],
- intersectCubesTimeStamps = []
- nextCubeDeletionTimeStamp = null,
- zoomedIn = false;
- var helper,
- geometryHelper,
- stepHelper,
- overviewHelper,
- transferHelper,
- zoomHelper,
- opacityPlotter,
- statsHelper;
- var waitDiv;
- var saveImage = false;
- // prefetch first image to cache it
- var progressContainer,
- imageProgress,
- progressSpan;
- var Globals = (function() {
- return {
- init: function() {
- originalDimension = new GeometryDimension();
- zoomedDimension = new GeometryDimension();
- currentDimension = originalDimension;
- originalVolumeDimension = new VolumeDimension();
- zoomedVolumeDimension = new VolumeDimension();
- currentVolumeDimension = originalVolumeDimension;
- $resolutionLinks = $('#resolution-links');
- }
- }
- }());
- ;var GeometryHelper = function() {
- return {
- createBoxGeometry: function(dimension, volumeDimension) {
- var vertexPos = [
- //front face first
- [dimension.xmin, dimension.ymin, dimension.zmax],
- [dimension.xmax, dimension.ymin, dimension.zmax],
- [dimension.xmax, dimension.ymax, dimension.zmax],
- //front face second
- [dimension.xmin, dimension.ymin, dimension.zmax],
- [dimension.xmax, dimension.ymax, dimension.zmax],
- [dimension.xmin, dimension.ymax, dimension.zmax],
- // back face first
- [dimension.xmin, dimension.ymin, dimension.zmin],
- [dimension.xmin, dimension.ymax, dimension.zmin],
- [dimension.xmax, dimension.ymax, dimension.zmin],
- // back face second
- [dimension.xmin, dimension.ymin, dimension.zmin],
- [dimension.xmax, dimension.ymax, dimension.zmin],
- [dimension.xmax, dimension.ymin, dimension.zmin],
- // top face first
- [dimension.xmin, dimension.ymax, dimension.zmin],
- [dimension.xmin, dimension.ymax, dimension.zmax],
- [dimension.xmax, dimension.ymax, dimension.zmax],
- // top face second
- [dimension.xmin, dimension.ymax, dimension.zmin],
- [dimension.xmax, dimension.ymax, dimension.zmax],
- [dimension.xmax, dimension.ymax, dimension.zmin],
- // bottom face first
- [dimension.xmin, dimension.ymin, dimension.zmin],
- [dimension.xmax, dimension.ymin, dimension.zmin],
- [dimension.xmax, dimension.ymin, dimension.zmax],
- // bottom face second
- [dimension.xmin, dimension.ymin, dimension.zmin],
- [dimension.xmax, dimension.ymin, dimension.zmax],
- [dimension.xmin, dimension.ymin, dimension.zmax],
- // right face first
- [dimension.xmax, dimension.ymin, dimension.zmin],
- [dimension.xmax, dimension.ymax, dimension.zmin],
- [dimension.xmax, dimension.ymax, dimension.zmax],
- // right face second
- [dimension.xmax, dimension.ymin, dimension.zmin],
- [dimension.xmax, dimension.ymax, dimension.zmax],
- [dimension.xmax, dimension.ymin, dimension.zmax],
- // left face first
- [dimension.xmin, dimension.ymin, dimension.zmin],
- [dimension.xmin, dimension.ymin, dimension.zmax],
- [dimension.xmin, dimension.ymax, dimension.zmax],
- // left face second
- [dimension.xmin, dimension.ymin, dimension.zmin],
- [dimension.xmin, dimension.ymax, dimension.zmax],
- [dimension.xmin, dimension.ymax, dimension.zmin]
- ];
- var positions = [];
- var colors = [];
- for(var i = 0; i < vertexPos.length; i++) {
- var backCounter = vertexPos.length - 1 - i,
- x = vertexPos[backCounter][0],
- y = vertexPos[backCounter][1],
- z = vertexPos[backCounter][2];
- positions.push(x);
- positions.push(y);
- positions.push(z * volumeDimension.getZStretchFactor());
- colors.push(x);
- colors.push(y);
- colors.push(z);
- colors.push(1.0);
- }
- var geometry = new THREE.BufferGeometry();
- var bufferPositions = new Float32Array(positions);
- geometry.addAttribute( 'position', new THREE.BufferAttribute( bufferPositions, 3 ) );
- geometry.addAttribute( 'frontColor', new THREE.BufferAttribute(new Float32Array(colors), 4));
- geometry.computeBoundingSphere();
- return geometry;
- }
- }
- }
- var GeometryDimension = function() {
- this.xmin = 0.005;
- this.xmax = 0.995;
- this.ymin = 0.005;
- this.ymax = 0.995;
- this.zmin = 0.005;
- this.zmax = 0.995;
- }
- var VolumeDimension = function() {
- this.xmin;
- this.xmax;
- this.ymin;
- this.ymax;
- this.zmin;
- this.zmax;
- return {
- getZStretchFactor: function() {
- return (this.zmax - this.zmin + 1) / (this.xmax - this.xmin);
- }
- }
- }
- ;var Helper = function() {
- var messagePopup = $('#popup'),
- popupVisible = messagePopup.hasClass('hidden'),
- progressContainer = $('#progress-container'),
- imageProgress = $('#image-progress'),
- progressSpan = $('#texturePath');
- return {
- initializeShaders: function(url, callback) {
- $.ajax({
- url: url,
- error: function() {
- console.error('failed to load shader file from: ' + url);
- },
- success: callback
- });
- },
- downloadImage: function (texturePath, textureIndex, spriteIndex, whileInit) {
- me = this;
- onProgressHolder = me.showProgress(texturePath);
- if(!texturePath.endsWith('/')) {
- texturePath += '/';
- }
- var xmlHttp = new XMLHttpRequest();
- xmlHttp.open('GET', texturePath, true);
- xmlHttp.onprogress = onProgressHolder.onProgressFunction;
- xmlHttp.onload = function(e) {
- var blob = new Blob([xmlHttp.response], {
- type: this.getResponseHeader('content-type')
- });
- var blobSrc = window.URL.createObjectURL(blob);
- var image = new Image();
- var texture = new THREE.Texture(image);
- image.onload = function() {
- me.hideProgress();
- texture.needsUpdate = true;
- var params = {
- textureIndex: textureIndex,
- spriteIndex: spriteIndex,
- texture: texture
- };
- if(textureIndex == 0 && whileInit) {
- $(document).trigger('firstImageOnLoad', params);
- } else {
- $(document).trigger('imageOnLoad', params);
- }
- }
- image.src = blobSrc;
- };
- xmlHttp.responseType = 'blob';
- xmlHttp.send();
- },
- showProgress: function(texturePath) {
- progressContainer.removeClass('hidden');
- progressSpan.text(texturePath);
- return {
- onProgressFunction: function(e) {
- if (e.lengthComputable) {
- value = Math.floor(e.loaded / e.total * 100);
- imageProgress.val(value);
- }
- }
- }
- },
- hideProgress: function() {
- imageProgress.val(0);
- progressSpan.text('');
- progressContainer.addClass('hidden');
- },
- displayMessage: function(message, fadeOutAutomatically, callback, timeout) {
- var me = this;
- messagePopup.html(message);
- messagePopup.show();
- if(fadeOutAutomatically) {
- this.fadeoutMessage(callback, timeout);
- }
- },
- fadeoutMessage: function(callback, timeout) {
- if(timeout == undefined) {
- timeout = 0;
- }
- setTimeout(function() {
- messagePopup.fadeOut(400, function() {
- $(this).html('');
- if(callback) {
- callback();
- }
- });
- }, timeout);
- }
- };
- }
- ;var OpacityPlotter = function() {
- // we have 255 colors
- var coordinateLength = 255;
- // set with respect on plotter height
- var height = 40;
- // array for holding the x coordinates
- var coordinates = Array(coordinateLength);
- // array for holding the y coordinates values elementOf [0, height]
- var linePosition = Array(coordinateLength);
- // array holding the resulting opacities, that will be generated
- // of line position, values elementof [0, 255]
- var opacities = Array(coordinateLength);
- for(counter = 0; counter < coordinateLength; counter++) {
- coordinates[counter] = counter;
- linePosition[counter] = 0;
- opacities[counter] = 255;
- }
- var stage = new Kinetic.Stage({
- container : 'opacity-plot',
- width : coordinateLength,
- height: height
- });
- var layer = new Kinetic.Layer();
- var rect = new Kinetic.Rect({
- x: 0,
- y: 0,
- width: stage.getWidth(),
- height: stage.getHeight(),
- fill: '#cccccc'
- });
- layer.add(rect);
- var spline = new Kinetic.Line({
- points: getResultingPoints(),
- stroke: 'red',
- strokeWidth: 3,
- lineCap: 'round'
- });
- layer.add(spline);
- stage.add(layer);
- stage.on("mousedown", function() {
- processEvent();
- });
- stage.on("mousemove", function(e) {
- if(e.evt.which == 1) {
- processEvent();
- }
- });
- $('#transfer-function-definition').on('controlsShowed', function() {
- populateOpacities();
- });
- $('input#opacity-visible').on('click', function() {
- setToFixedValue(255);
- });
- $('input#opacity-invisible').on('click', function() {
- setToFixedValue(0);
- });
- function setToFixedValue(value) {
- var opacityValue = value;
- var yValue = height - ((value / 255) * height)
- for(counter = 0; counter < opacities.length; counter++) {
- opacities[counter] = opacityValue ;
- linePosition[counter] = yValue;
- }
- populateOpacities();
- spline.setPoints(getResultingPoints());
- layer.draw();
- }
- function populateOpacities() {
- $(document).trigger('opacityChanged', { opacities: opacities.slice() });
- }
- function processEvent() {
- var mousePosition = stage.getPointerPosition();
- calculateOpacities(mousePosition);
- spline.setPoints(getResultingPoints());
- layer.draw();
- }
- function calculateOpacities(mousePosition) {
- // Set area of click to this value
- var xMin = (mousePosition.x - 2 >= 0) ? mousePosition.x - 2 : 0;
- var xMax = (mousePosition.x + 2 <= 255) ? mousePosition.x + 2 : 255;
- var opacityValue = (height - mousePosition.y) / height;
- opacityValue *= 255;
- for(counter = xMin; counter <= xMax; counter++) {
- linePosition[counter] = mousePosition.y;
- opacities[counter] = opacityValue;
- }
- populateOpacities();
- }
- function getResultingPoints() {
- return combineArrays(coordinates, linePosition);
- }
- function combineArrays(array1, array2) {
- return $.map(array1, function(v, i) { return [v, array2[i]]; });
- }
- }
- ;var StatsHelper = function(parentElement) {
- if(IPE.environment != 'dev') {
- // fill parentElement with emptyness
- parentElement.append(' ');
- // we don't want to do display anything
- // in production
- return {
- update: function() {}
- };
- }
- var stats = new Stats();
- var parentElement = parentElement;
- parentElement.append(stats.domElement);
- return {
- update: function() {
- stats.update();
- }
- }
- };
- ;var StepHelper = function() {
- // default is the step 100
- currentStepIndex = 2;
- // steps just defined
- availableSteps = [10, 20, 50, 80, 100, 150, 200];
- return {
- decreaseSteps: function() {
- var currentStepIndex = this.determineCurrentStepIndex();
- if(currentStepIndex > 0) {
- this.updateStepValue(availableSteps[currentStepIndex - 1], true);
- }
- },
- increaseSteps: function() {
- var currentStepIndex = this.determineCurrentStepIndex();
- if(currentStepIndex > -1 && currentStepIndex < availableSteps.length - 1) {
- this.updateStepValue(availableSteps[currentStepIndex + 1], true);
- }
- },
- determineCurrentStepIndex: function() {
- var minDeviation = null,
- minDeviationIndex;
- // first we have to find an appropiate predefined stepValue for input stepvalue
- for(var index = 0; index < availableSteps.length; index++) {
- deviation = Math.abs(steps - availableSteps[index]);
- if(minDeviation == null || deviation < minDeviation) {
- minDeviation = deviation;
- minDeviationIndex = index;
- }
- }
- if(minDeviation !== null) {
- return minDeviationIndex;
- } else {
- return -1;
- }
- },
- updateStepValue: function(stepValue, updateInputField) {
- steps = stepValue;
- materialScreen.uniforms.steps.value = steps;
- if(updateInputField) {
- $('#steps').val(stepValue);
- }
- },
- initStepControls: function() {
- var me = this,
- stepsInput = $('#steps'),
- stepsAdjustInput = $('#steps-adjust');
- steps = stepsInput.val();
- stepsInput.change(function() {
- steps = stepsInput.val();
- me.updateStepValue(steps, false);
- });
- adjustSteps = stepsAdjustInput.is(':checked');
- stepsAdjustInput.change(function() {
- adjustSteps = $(this).is(':checked');
- if(adjustSteps) {
- stepsInput.prop('disabled', true);
- } else {
- stepsInput.prop('disabled', false);
- }
- });
- }
- };
- };
- ;var TransferHelper = function() {
- var me = this,
- changed = false,
- canvas = document.getElementById('transfer-function'),
- $canvas = $(canvas),
- context = canvas.getContext('2d'),
- hiddenCanvas = document.getElementById('hidden-transfer'),
- hiddenContext = hiddenCanvas.getContext('2d'),
- transferSpanHolder = $('#transfer-span-holder'),
- transfer = $('#transfer'),
- disabled = true,
- handles = $('span.transfer'),
- $standardTf = $('img#standard-tf').get(0),
- offsetLeft = {
- blue: 0,
- turquois: 0.25,
- green: 0.5,
- orange: 0.75,
- red: 1
- },
- colorCodes = {
- blue: '#0000FF',
- turquois: '#00FFFF',
- green: '#00FF00',
- orange: '#FFFF00',
- red: '#FF0000'
- },
- opacities = Array(255);
- //black values are disabled defaultly
- opacities[0] = 0;
- for(counter = 0; counter < opacities.length; counter++) {
- opacities[counter] = 255;
- if (counter <= minGray) {
- opacities[counter] = 0;
- }
- }
- $('input#toggle-transfer').on('click', function() {
- if(disabled) {
- enableTransferFunction();
- } else {
- disableTransferFunction();
- }
- });
- var getOffsetLeft = function() {
- return transfer.offset().left - transfer.parent().offset().left;
- }
- var removePxOffString = function(str) {
- return parseInt(str.replace('px', ''));
- }
- var updateGradient = function() {
- // Create gradient
- var grd = context.createLinearGradient(0,0,255,0);
- $.each(handles, function(index, value) {
- var $value = $(value),
- colorName = $value.attr('color'),
- colorOffsetLeft = offsetLeft[colorName],
- colorCode = colorCodes[colorName];
- grd.addColorStop(colorOffsetLeft, colorCode);
- });
- // Fill with gradient
- context.fillStyle = grd;
- context.fillRect(0,0,255, 10);
- applyOpacities();
- changed = true;
- };
- var applyOpacities = function() {
- var imageData = context.getImageData(0, 0, 255, 1),
- data = imageData.data;
- for(counter = 0; counter < opacities.length; counter++) {
- data[(counter * 4) + 3] = opacities[counter];
- }
- hiddenContext.putImageData(imageData, 0, 0, 0, 0, 255, 1);
- }
- var updateHandlePosition = function(element) {
- var colorLeft = removePxOffString($(element).css('left')) - getOffsetLeft(),
- colorOffsetLeft = colorLeft / $canvas.width(),
- colorName = $(element).attr('color');
- if(colorOffsetLeft > 1.0) {
- colorOffsetLeft = 1.0;
- }
- if(colorOffsetLeft < 0.0) {
- colorOffsetLeft = 0.0;
- }
- offsetLeft[colorName] = colorOffsetLeft;
- updateGradient();
- };
- var enableTransferFunction = function() {
- $.each(handles, function(index, value) {
- var $value = $(value),
- colorName = $value.attr('color'),
- colorOffsetLeft = offsetLeft[colorName],
- colorLeft = getOffsetLeft() + ($canvas.width() * colorOffsetLeft),
- colorCode = colorCodes[colorName];
- $value.css({left: colorLeft, 'background-color': colorCode });
- $(value).draggable({
- containment: '#transfer-span-holder',
- scroll: false,
- axis: 'x',
- cursor: "crosshair",
- stop: function() {
- updateHandlePosition(this);
- },
- drag: function() {
- updateHandlePosition(this);
- }
- });
- });
- showHandles();
- updateGradient();
- disabled = false;
- };
- var disableTransferFunction = function() {
- context.drawImage($standardTf, 0, 0, 255, 10);
- applyOpacities();
- hideHandles();
- disabled = true;
- changed = true;
- };
- var showHandles = function() {
- $.each(handles, function(index, value) {
- $(value).removeClass('hidden');
- });
- };
- var hideHandles = function() {
- $.each(handles, function(index, value) {
- $(value).addClass('hidden');
- });
- };
- disableTransferFunction();
- $(document).on('opacityChanged', function(e, params) {
- if(params != undefined && params.opacities != undefined) {
- opacities = params.opacities;
- applyOpacities();
- changed = true;
- }
- });
- $(document).on('opacityBordersChanged', function(e, params) {
- var minGray = 0,
- maxGray = 255;
- if(params != undefined && params.minGray != undefined && params.maxGray != undefined) {
- minGray = params.minGray;
- maxGray = params.maxGray;
- for(counter = 0; counter < 255; counter++) {
- var opacity = 255;
- if(counter < minGray || counter > maxGray) {
- opacity = 1;
- }
- opacities[counter] = opacity;
- }
- applyOpacities();
- changed = true;
- }
- });
- return {
- transferFunctionChanged : function() {
- return changed;
- },
- getCurrentTransferFunction : function() {
- changed = false;
- return hiddenContext.getImageData(0, 0, 255, 1);
- }
- };
- }
- ;var OverviewHelper = function() {
- var sceneOveriew, rendererOverview, cameraOverview, innerCubeOverview;
- var originalZStretchFactor;
- //private method
- var addInnerCubeOverView = function(x, y, z) {
- var innerCubeGeometry = new THREE.BoxGeometry( x, y, z );
- var innerCubeMaterial = new THREE.MeshBasicMaterial( {color: 0xaaaaaa} );
- innerCubeOverview = new THREE.Mesh( innerCubeGeometry, innerCubeMaterial );
- sceneOverview.add( innerCubeOverview );
- }
- var addInnerFullCube = function() {
- addInnerCubeOverView(1, 1 * originalZStretchFactor, 1);
- };
- var initiateEventListener = function(containerOverviewElement) {
- // change overview box
- $(document).on('zoomActionFinished', function(e, params) {
- zoomedIn = params.zoomAction == 'zoomIn' || zoomedInfo != null;
- sceneOverview.remove(innerCubeOverview);
- if(zoomedIn) {
- xWidth = zoomedInfo.dimension.xywidth / textureInfo.originalSize.sizex;
- yWidth = zoomedInfo.dimension.xywidth / textureInfo.originalSize.sizey;
- zWidth = zoomedInfo.numberOfSlices / textureInfo.originalSize.sizez;
- xOffset = zoomedInfo.dimension.xmin / textureInfo.originalSize.sizex;
- yOffset = zoomedInfo.dimension.ymin / textureInfo.originalSize.sizey;
- zOffset = zoomedInfo.dimension.zmin / (textureInfo.originalSize.sizez * originalZStretchFactor);
- addInnerCubeOverView(xWidth, yWidth, zWidth);
- // main cube was rotated around x axis, so have to swap y and z coordinates
- // for the overview
- innerCubeOverview.position.x = -0.5 + xOffset + xWidth / 2;
- innerCubeOverview.position.y = (-0.5 + zOffset + zWidth / 2);
- innerCubeOverview.position.z = (-0.5 + yOffset + yWidth / 2) * -1;
- } else {
- addInnerFullCube();
- }
- });
- var headerHeight = $('header').height();
- $(window).on('scroll', function(e) {
- $containerOverviewElement = $(containerOverviewElement)
- if($(this).scrollTop() >= headerHeight) {
- $containerOverviewElement.css('position', 'relative');
- $containerOverviewElement.css('top', $(this).scrollTop() - headerHeight);
- } else {
- $containerOverviewElement.css('top', 0);
- }
- });
- }
- var addTextsToScene = function() {
- var shapeParameters = {font: 'helvetiker', size: 0.2, height: 0.05},
- shape = new THREE.TextGeometry("0", shapeParameters),
- wrapper = new THREE.MeshBasicMaterial({color: 0x000000}),
- words = new THREE.Mesh(shape, wrapper);
- words.position.x = -0.6;
- words.position.y = -0.6;
- words.position.z = 0.52;
- sceneOverview.add(words);
- }
- var addCubeEdges = function() {
- // fix for cube
- var numberOfEdges = 12;
- var xColorEdge = new THREE.Color(1,0,0);
- var yColorEdge = new THREE.Color(0,1,0);
- var zColorEdge = new THREE.Color(0,0,1);
- var geometry = new THREE.BufferGeometry();
- var material = new THREE.LineBasicMaterial({ vertexColors: THREE.VertexColors });
- var colors = new Float32Array( numberOfEdges * 2 * 3 );
- var zMin = -0.5 * originalZStretchFactor;
- var zMax = 0.5 * originalZStretchFactor;
- var positions = new Float32Array([
- // edges in x direction
- // front face
- -0.5, zMin, -0.5, 0.5, zMin, -0.5,
- -0.5, zMax, -0.5, 0.5, zMax, -0.5,
- // back face
- -0.5, zMin, 0.5, 0.5, zMin, 0.5,
- -0.5, zMax, 0.5, 0.5, zMax, 0.5,
- // edges in y direction
- // front face
- -0.5, zMin, -0.5, -0.5, zMax, -0.5,
- 0.5, zMin, -0.5, 0.5, zMax, -0.5,
- // back face
- -0.5, zMin, 0.5, -0.5, zMax, 0.5,
- 0.5, zMin, 0.5, 0.5, zMax, 0.5,
- // edges in z direction
- // left side
- -0.5, zMin, -0.5, -0.5, zMin, 0.5,
- -0.5, zMax, -0.5, -0.5, zMax, 0.5,
- // right side
- 0.5, zMin, -0.5, 0.5, zMin, 0.5,
- 0.5, zMax, -0.5, 0.5, zMax, 0.5
- ]);
- for(edgeCounter = 0; edgeCounter < 12 * 2; edgeCounter++) {
- var colorToUse = null
- if(edgeCounter <= 7) {
- colorToUse = xColorEdge;
- } else if(edgeCounter <= 15) {
- colorToUse = zColorEdge;
- } else {
- colorToUse = yColorEdge;
- }
- colors[edgeCounter * 3 + 0] = colorToUse.r;
- colors[edgeCounter * 3 + 1] = colorToUse.g;
- colors[edgeCounter * 3 + 2] = colorToUse.b;
- }
- geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
- geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
- var lines = new THREE.Line( geometry, material, THREE.LinePieces );
- sceneOverview.add( lines );
- }
- return {
- initOverview: function(containerOverviewElement) {
- originalZStretchFactor = currentVolumeDimension.getZStretchFactor();
- sceneOverview = new THREE.Scene();
- cameraOverview = new THREE.PerspectiveCamera( 45, 150 / 150, .1, 1000 );
- cameraOverview.position.z = 2;
- var cubeGeometry = new THREE.BoxGeometry( 1, 1, 1 );
- var cubeMaterial = new THREE.MeshBasicMaterial( {color: 0x000000} );
- var cubeOverview = new THREE.Mesh( cubeGeometry, cubeMaterial );
- var edgesHelper = new THREE.EdgesHelper(cubeOverview, 0x000000);
- edgesHelper.material.linewidth = 2;
- //sceneOverview.add( edgesHelper );
- addInnerFullCube();
- addCubeEdges();
- addTextsToScene();
- rendererOverview = new THREE.WebGLRenderer();
- rendererOverview.setSize(200, 200);
- rendererOverview.setClearColor(0xffffff, 1);
- containerOverviewElement.appendChild(rendererOverview.domElement);
- initiateEventListener(containerOverviewElement);
- },
- updateCameraPosition: function(position) {
- cameraPoint.normalize().multiplyScalar(4);
- cameraPoint = sceneOverview.position.clone().add(cameraPoint);
- cameraOverview.position.x = cameraPoint.x;
- cameraOverview.position.y = cameraPoint.y;
- cameraOverview.position.z = cameraPoint.z;
- cameraOverview.lookAt(sceneOverview.position);
- },
- render: function() {
- rendererOverview.render(sceneOverview, cameraOverview);
- }
- }
- }
- ;var VolumeFace = function(orientation, direction) {
- this.orientation = orientation;
- this.direction = direction;
- }
- VolumeFace.prototype = {
- constructor: VolumeFace,
- orientation: 0,
- direction: 0,
- getAxisOfNaviation: function() {
- var axis = {
- plane: {
- ver: null,
- hor: null
- },
- slider: null
- };
- if(this.orientation == VolumeFaceOrientation.XY) {
- axis.plane.ver = new Orientation(Axis.Y);
- axis.plane.hor = new Orientation(Axis.X);
- axis.slider = new Orientation(Axis.Z);
- } else if(this.orientation == VolumeFaceOrientation.YZ) {
- axis.plane.ver = new Orientation(Axis.Z);
- axis.plane.hor = new Orientation(Axis.Y);
- axis.slider = new Orientation(Axis.X);
- } else if(this.orientation == VolumeFaceOrientation.XZ) {
- axis.plane.ver = new Orientation(Axis.Z);
- axis.plane.hor = new Orientation(Axis.X);
- axis.slider = new Orientation(Axis.Y);
- }
- return axis;
- },
- getIdentifier: function() {
- return this.orientation + '-' + this.direction;
- }
- };
- var VolumeFaceOrientation = {
- XY: 0,
- XZ: 1,
- YZ: 2
- }
- var VolumeFaceDirection = {
- FRONT: 0,
- BACK: 1
- }
- function determineVolumeFace(cubeFaceNormal) {
- var orientation, direction;
- if(cubeFaceNormal.x != 0) {
- orientation = VolumeFaceOrientation.YZ;
- direction = determineFaceOrientation(cubeFaceNormal.x);
- } else if(cubeFaceNormal.y != 0) {
- orientation = VolumeFaceOrientation.XZ;
- direction = determineFaceOrientation(cubeFaceNormal.y);
- } else if(cubeFaceNormal.z != 0) {
- orientation = VolumeFaceOrientation.XY;
- direction = determineFaceOrientation(cubeFaceNormal.z);
- }
- return new VolumeFace(orientation, direction);
- }
- function determineFaceOrientation(normalComp) {
- return normalComp > 0 ? VolumeFaceDirection.FRONT : VolumeFaceDirection.BACK;
- }
- function isFrontFace(orientation, direction) {
- return orientation == VolumeFaceOrientation.XY
- && direction == VolumeFaceDirection.FRONT;
- }
- function isBackFace(orientation, direction) {
- return orientation == VolumeFaceOrientation.XY
- && direction == VolumeFaceDirection.BACK;
- }
- function isLeftFace(orientation, direction) {
- return orientation == VolumeFaceOrientation.YZ
- && direction == VolumeFaceDirection.FRONT;
- }
- function isRightFace(orientation, direction) {
- return orientation == VolumeFaceOrientation.YZ
- && direction == VolumeFaceDirection.BACK;
- }
- function isTopFace(orientation, direction) {
- return orientation == VolumeFaceOrientation.XZ
- && direction == VolumeFaceDirection.FRONT;
- }
- function isBottomFace(orientation, direction) {
- return orientation == VolumeFaceOrientation.XZ
- && direction == VolumeFaceDirection.BACK;
- }
- ;var ZoomHelper = function() {
- var navigationPlaneHorLabel = $('#navigation-plane-hor-label'),
- navigationPlaneVerLabel = $('#navigation-plane-ver-label'),
- navigationSliderLabel = $('#navigation-slider-label'),
- zoomStatus = $('#zoom-status'),
- zoomInButton = $('input#zoomin'),
- zoomOutButton = $('input#zoomout'),
- navigationPlane = $('div#navigation-plane'),
- navigationPlaneParent = navigationPlane.parent(),
- navigationSlider = $('div#navigation-slider'),
- navigationSliderParent = navigationSlider.parent(),
- displayTimestamp = null,
- planeOrientation = {
- ver: new Orientation(Axis.Y, OffsetTo.LEFT),
- hor: new Orientation(Axis.X, OffsetTo.TOP),
- direction: VolumeFaceDirection.BACK,
- orientation: VolumeFaceOrientation.XY
- },
- sliderOrientation = {axis: new Orientation(Axis.Z, OffsetTo.TOP) },
- zoomedIn,
- zoomedInfoArray = {
- dimension: Array(3),
- offset: Array(3)
- },
- oldZoomedInfos = [];
- var lastExecutionTime = Date.now();
- // adjust navigation related navigations
- $container.on('animation', function() {
- determineAxisLabels();
- determinePlanePosition();
- determineSliderPosition();
- });
- // one has to press ctrl AND alt while clicking
- $container.on('click', 'canvas', function(event){
- event.stopPropagation();
- event.preventDefault();
- // keyboard shortcut activated or button zoom in pressed before?
- if((event.ctrlKey == false || event.altKey == false)
- && !zoomInActivated) {
- return;
- }
- var mouseX = ( (event.clientX - $canvas.offset().left) / ($canvas.width()) ) * 2 - 1,
- mouseY = - ( (event.clientY - $canvas.offset().top) / ($canvas.height()) ) * 2 + 1;
- var vector = new THREE.Vector3( mouseX, mouseY, camera.near);
- vector = vector.unproject( camera );
- var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
- var intersects = raycaster.intersectObjects( [frontBox] );
- if(intersects.length > 0) {
- if(!handleZoomStatus(true)) {
- return false;
- }
- var intersect = intersects[0],
- point = intersect.point;
- var geometry = new THREE.BoxGeometry( 0.1, 0.1, 0.1 );
- var material = new THREE.MeshBasicMaterial( {
- color: new THREE.Color( 0xaaaaaa ),
- opacity: 0.3
- });
- mesh = new THREE.Mesh( geometry, material );
- mesh.position.x = point.x;
- mesh.position.y = point.y;
- mesh.position.z = point.z;
- scene.add(mesh);
- intersectCubes[intersectCubes.length] = mesh;
- intersectCubesTimeStamps[intersectCubesTimeStamps.length] = Date.now();
- var realPoint = point.clone();
- getSubvolume(point, false, 'zoomIn', false);
- }
- });
- function getSubvolume(realPoint, alreadyTranslated, zoomAction, sameDepth, fromDraggable) {
- var requestedRes = typeof(window.requestedSize)=="undefined" ? config.defaultSize : requestedSize;
- if(alreadyTranslated == undefined || !alreadyTranslated) {
- realPoint = realPoint.applyMatrix4((new THREE.Matrix4).makeRotationX(Math.PI / -2));
- // retranslate the point into original position beginning from 0,0,0
- realPoint.add(new THREE.Vector3(0.5, 0.5, 0.5));
- }
- volumePointArray = realPoint.toArray();
- var processingUrl = IPE.util.buildUrl('volumes/' + volumeId + '/processing/sub/');
- $.each(volumePointArray, function(index, value) {
- dimWidth = null;
- // have to decide, whether we in zoomed in or zoomed out status
- if(zoomedInfo == undefined || zoomedInfo == null || fromDraggable) {
- if(index == 0) {
- dimWidth = textureInfo.originalSize.sizex;
- } else if(index == 1) {
- dimWidth = textureInfo.originalSize.sizey;
- } else {
- dimWidth = textureInfo.originalSize.sizez;
- }
- } else {
- if(index < 2) {
- dimWidth = zoomedInfo.dimension.xywidth;
- } else {
- dimWidth = zoomedInfo.numberOfSlices;
- }
- }
- value *= dimWidth;
- // due to interpolation algorithm, we had to rotate the whole cube, that it matches
- // the display of imagej
- // so we have to map the current pointer values to the real volume values
- // but only for the y and z direction --> the x direction is all right
- if(index > 0) {
- value = dimWidth - value;
- }
- if(!fromDraggable && zoomedInfo) {
- if(index == 0) {
- value = value + zoomedInfo.dimension.xmin;
- } else if(index == 1) {
- value = value + zoomedInfo.dimension.ymin;
- } else {
- value = value + zoomedInfo.dimension.zmin;
- }
- }
- value = Math.floor(value);
- volumePointArray[index] = value;
- processingUrl += value + '/';
- });
- frameNumber = imgInfo.frameFrom + currentTexture;
- processingUrl += frameNumber + '/';
- depth = 1;
- if(zoomAction == 'zoomIn') {
- if(zoomedInfo != null){
- if(sameDepth) {
- depth = zoomedInfo.depth;
- } else {
- depth = zoomedInfo.depth + 1;
- }
- }
- } else if(zoomAction == 'zoomOut') {
- if(zoomedInfo.depth > 1) {
- depth = zoomedInfo.depth - 1;
- }
- }
- while(oldZoomedInfos.length > 0
- && oldZoomedInfos.last().zoomedInfo.depth >= depth)
- {
- oldZoomedInfos.pop();
- }
- processingUrl += depth + '/';
- processingUrl += requestedRes + '/';
- $.ajax({
- url: processingUrl,
- success: function(data) {
- var available = false;
- var availableTestCounter = 0;
- zoomedInfo = data;
- oldZoomedInfos.push({
- point: realPoint,
- translated: true,
- zoomedInfo: zoomedInfo
- });
- // this function is called recursive by the settimeout statement
- availableTest = function() {
- $.ajax({
- url: IPE.util.buildUrl('volumes/' + volumeId + '/processing/sprite/' + zoomedInfo.spriteId + '/available/'),
- success: function(data) {
- available = data.available;
- },
- dataType: 'json',
- async: false
- });
- if(available) {
- // subvolume available: fetch it
- fetchSubVolume(zoomAction);
- } else if(availableTestCounter < 80) {
- // abort condition not reached --> try again
- setTimeout(availableTest, 500);
- availableTestCounter++;
- } else {
- oldZoomedInfos.pop();
- // abort condition reached --> error handling
- $(document).trigger('zoomActionFinished', { zoomAction: zoomAction, error: true });
- }
- };
- setTimeout(availableTest, 500);
- },
- dataType: 'json',
- async: true,
- error: function(data) {
- helper.displayMessage('Sorry, an error occured during processing zoom', true, null, 2500);
- }
- });
- };
- var fetchSubVolume = function(zoomAction) {
- imageSrc = IPE.util.buildUrl('volumes/' + volumeId + '/processing/sprite/' + zoomedInfo.spriteId + '/show/');
- var image = new Image();
- var texture = initTexture(new THREE.Texture(image));
- image.onload = function() {
- materialScreen.uniforms.numberOfSlices.value = zoomedInfo.numberOfSlices;
- materialScreen.uniforms.numberOfSlices.needsupdate = true;
- materialScreen.uniforms.slicesOverX.value = zoomedInfo.slicesOverX;
- materialScreen.uniforms.slicesOverX.needsUpdate = true;
- materialScreen.uniforms.slicesOverY.value = zoomedInfo.slicesOverY;
- materialScreen.uniforms.slicesOverY.needsUpdate = true;
- materialScreen.uniforms.numberOfSprites.value = 1;
- materialScreen.uniforms.numberOfSprites.needsUpdate = true;
- materialScreen.uniforms.slicesPerSprite.value = zoomedInfo.numberOfSlices;
- materialScreen.uniforms.slicesPerSprite.needsUpdate = true;
- updateTexture([texture]);
- zoomedVolumeDimension.xmin = zoomedInfo.dimension.xmin;
- zoomedVolumeDimension.xmax = zoomedInfo.dimension.xmin + zoomedInfo.dimension.xywidth - 1;
- zoomedVolumeDimension.ymin = zoomedInfo.dimension.ymin;
- zoomedVolumeDimension.ymax = zoomedInfo.dimension.ymin + zoomedInfo.dimension.xywidth - 1;
- zoomedVolumeDimension.zmin = zoomedInfo.dimension.zmin;
- zoomedVolumeDimension.zmax = zoomedInfo.dimension.zmin + zoomedInfo.numberOfSlices - 1;
- originalVolumeDimension = currentVolumeDimension;
- originalDimension = currentDimension;
- currentVolumeDimension = zoomedVolumeDimension;
- repositionLayerSliders();
- $(document).trigger('zoomActionFinished', {
- zoomAction: zoomAction, textureNumber: frameNumber
- });
- }
- image.src = imageSrc;
- };
- $container.on('contextmenu', function(event){
- if(event.ctrlKey == false) {
- return;
- }
- if(event.altKey == false) {
- return;
- }
- if(!handleZoomStatus(false)) {
- return false;
- }
- return zoomOut();
- });
- function zoomOut() {
- currentZoomPoint = oldZoomedInfos.pop().point;
- if(oldZoomedInfos.length > 0) {
- // using the current point to get a new subvolume
- getSubvolume(currentZoomPoint, true, 'zoomOut', true);
- return false;
- }
- else
- {
- zoomedInfo = null;
- materialScreen.uniforms.numberOfSlices.value = textureInfo.info.numberOfSlices;
- materialScreen.uniforms.numberOfSlices.needsupdate = true;
- materialScreen.uniforms.slicesOverX.value = textureInfo.info.slicesOverX;
- materialScreen.uniforms.slicesOverX.needsUpdate = true;
- materialScreen.uniforms.slicesOverY.value = textureInfo.info.slicesOverY;
- materialScreen.uniforms.slicesOverY.needsUpdate = true;
- materialScreen.uniforms.numberOfSprites.value = imgInfo.numberOfSprites;
- materialScreen.uniforms.numberOfSprites.needsUpdate = true;
- materialScreen.uniforms.slicesPerSprite.value = imgInfo.slicesPerSprite;
- materialScreen.uniforms.slicesPerSprite.needsUpdate = true;
- updateTexture();
- currentVolumeDimension = originalVolumeDimension;
- currentDimension = originalDimension;
- repositionLayerSliders();
- }
- $(document).trigger('zoomActionFinished', {
- zoomAction: 'zoomOut'
- });
- return false;
- }
- function zoomInAllowed() {
- return !zoomedIn || zoomedInfo.dimension.xywidth > 300;
- }
- /**
- * return: procceed or not
- */
- function handleZoomStatus(zoomIn) {
- zoomInButton.removeClass('red');
- zoomInActivated = false;
- if(zoomIn && !zoomInAllowed()) {
- return false;
- } else if(!zoomIn && !zoomedIn) {
- return false;
- }
- waitDiv.removeClass('hidden');
- displayMessage = zoomIn ? 'Generating zoomed subvolume, please wait a moment' : 'Zooming out';
- helper.displayMessage(displayMessage);
- displayTimestamp = Date.now();
- return true;
- }
- // general function to disable stuff like messages etc.
- $(document).on('zoomActionFinished', function(e, params) {
- zoomedIn = zoomedInfo != null;
- timeout = 2000 - (Date.now() - displayTimestamp);
- if(timeout < 0) {
- timeout = 0;
- }
- helper.fadeoutMessage(null, timeout);
- zoomedStatusText = '';
- if(zoomedIn) {
- zoomStatus.addClass('green-background');
- zoomedStatusText = 'zoomed in';
- $.each($('.res-link'), function(index, value) {
- $(value).addClass('disabled');
- });
- if(zoomedInfo.dimension.xywidth <= 300) {
- zoomInButton.prop('disabled', true);
- }
- } else {
- zoomStatus.removeClass('green-background');
- zoomedStatusText = 'zoomed out';
- if(params.error) {
- errorMessage = 'Error during subvolume generation - zoomed out again';
- helper.displayMessage(errorMessage, true, null, 5000);
- }
- $.each($('.res-link'), function(index, value) {
- $(value).removeClass('disabled');
- });
- zoomInButton.prop('disabled', false);
- }
- zoomStatus.html(zoomedStatusText);
- waitDiv.addClass('hidden');
- });
- // draggable related stuff
- // TODO for multilevel zooming
- $(document).on('zoomActionFinished', function(e, params) {
- zoomedIn = zoomedInfo != null;
- if(zoomedIn) {
- zoomedInfoArray.offset[Axis.X] = zoomedVolumeDimension.xmin;
- zoomedInfoArray.offset[Axis.Y] = zoomedVolumeDimension.ymin;
- zoomedInfoArray.offset[Axis.Z] = zoomedVolumeDimension.zmin;
- zoomedInfoArray.dimension[Axis.X] = zoomedInfo.dimension.xywidth;
- zoomedInfoArray.dimension[Axis.Y] = zoomedInfo.dimension.xywidth;
- zoomedInfoArray.dimension[Axis.Z] = zoomedInfo.numberOfSlices;
- } else {
- navigationPlane.hide();
- navigationPlaneParent.removeClass('white');
- navigationSlider.hide();
- navigationSliderParent.removeClass('white');
- }
- navigationPlane.removeClass('no-pos-set');
- navigationSlider.removeClass('no-pos-set');
- });
- navigationPlane.draggable({
- containment: '#navigation-plane-container',
- scroll: false,
- stop: function() {
- zoomedDraggableChanged();
- }
- });
- navigationSlider.draggable({
- containment: '#navigation-slider-container',
- scroll: false,
- stop: function() {
- zoomedDraggableChanged();
- }
- });
- function zoomedDraggableChanged() {
- waitDiv.removeClass('hidden');
- var planeWidthHalf = navigationPlane.width() / 2,
- planeHeightHalf = navigationPlane.height() / 2,
- planeOffsetLeft = navigationPlane.offset().left - navigationPlaneParent.offset().left - 1,
- planeOffsetTop = navigationPlane.offset().top - navigationPlaneParent.offset().top - 1,
- sliderHeightHalf = navigationSlider.height() / 2,
- sliderOffsetTop = navigationSlider.offset().top - navigationSliderParent.offset().top - 1,
- orientation = planeOrientation.orientation,
- direction = planeOrientation.direction;
- // set correct border values due to messure errors
- if(planeOffsetLeft < 0) {
- planeOffsetLeft = 0;
- } else if(planeOffsetLeft > navigationPlaneParent.width() - navigationPlane.width()) {
- planeOffsetLeft = navigationPlaneParent.width() - navigationPlane.width();
- }
- if(planeOffsetTop < 0) {
- planeOffsetTop = 0;
- } else if(planeOffsetTop > navigationPlaneParent.height() - navigationPlane.height()) {
- planeOffsetTop = navigationPlaneParent.height() - navigationPlane.height();
- }
- if(sliderOffsetTop < 0) {
- sliderOffsetTop = 0;
- } else if(sliderOffsetTop > navigationSliderParent.height() - navigationSlider.height()) {
- sliderOffsetTop = navigationSliderParent.height() - navigationSlider.height();
- }
- planeOffsetLeft = planeOffsetLeft + planeWidthHalf;
- planeOffsetTop = planeOffsetTop + planeHeightHalf;
- sliderOffsetTop = sliderOffsetTop + sliderHeightHalf;
- horAxis = planeOrientation.hor.axis;
- verAxis = planeOrientation.ver.axis;
- pointAsArray = Array(3);
- pointAsArray[horAxis] = planeOffsetLeft / navigationPlaneParent.width();
- pointAsArray[verAxis] = planeOffsetTop / navigationPlaneParent.height();
- /*if(planeOrientation.direction == VolumeFaceDirection.BACK) {
- pointAsArray[horAxis] = 1.0 - pointAsArray[horAxis];
- } else if(planeOrientation.orientation == VolumeFaceOrientation.XZ) {
- pointAsArray[horAxis] = 1.0 - pointAsArray[horAxis];
- }*/
- if((planeOrientation.orientation == VolumeFaceOrientation.XY
- && planeOrientation.direction == VolumeFaceDirection.BACK)
- || (planeOrientation.orientation == VolumeFaceOrientation.YZ
- && planeOrientation.direction == VolumeFaceDirection.BACK)
- || (planeOrientation.orientation == VolumeFaceOrientation.XZ
- && planeOrientation.direction == VolumeFaceDirection.BACK)) {
- pointAsArray[horAxis] = 1.0 - pointAsArray[horAxis];
- }
- pointAsArray[sliderOrientation.axis] = sliderOffsetTop / navigationSliderParent.height();
- /*if((sliderOrientation.axis == Axis.Z
- && planeOrientation.direction == VolumeFaceDirection.FRONT)
- || (sliderOrientation.axis == Axis.Y
- && planeOrientation.direction == VolumeFaceDirection.FRONT)
- || (sliderOrientation.axis == Axis.X
- && planeOrientation.direction == VolumeFaceDirection.BACK)) {
- pointAsArray[sliderOrientation.axis] = 1.0 - pointAsArray[sliderOrientation.axis];
- }*/
- if((sliderOrientation.axis == Axis.X
- && planeOrientation.direction == VolumeFaceDirection.FRONT)
- || (sliderOrientation.axis == Axis.Y
- && planeOrientation.direction == VolumeFaceDirection.BACK)
- || (sliderOrientation.axis == Axis.Z
- && planeOrientation.direction == VolumeFaceDirection.BACK)) {
- pointAsArray[sliderOrientation.axis] = 1.0 - pointAsArray[sliderOrientation.axis];
- }
- point = new THREE.Vector3(pointAsArray[0], pointAsArray[1], pointAsArray[2]);
- getSubvolume(point, true, 'zoomIn', true, true);
- };
- var zoomInActivated = false;
- zoomInButton.on('click', function() {
- zoomInActivated = !zoomInActivated;
- if(zoomInActivated) {
- $(this).addClass('red');
- } else {
- $(this).removeClass('red');
- }
- });
- zoomOutButton.on('click', function() {
- zoomInButton.removeClass('red');
- if(!handleZoomStatus(false)) {
- return false;
- }
- return zoomOut();
- });
- function determineAxisLabels() {
- if(Date.now() - lastExecutionTime > 100) {
- var lookAtVector = new THREE.Vector3(0,0, -1);
- lookAtVector.applyQuaternion(camera.quaternion);
- xIterator = -0.4;
- yIterator = -0.4;
- facesIntersect = {};
- interSectStartingPoint = new THREE.Vector3(xIterator, yIterator, camera.near);
- for(xIterator = -0.4; xIterator <= 0.4; xIterator += 0.2) {
- for(yIterator = -0.4; yIterator <= 0.4; yIterator += 0.2) {
- interSectStartingPoint.x = xIterator;
- interSectStartingPoint.y = yIterator;
- vector = interSectStartingPoint.unproject( camera );
- var raycaster = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );
- var intersects = raycaster.intersectObjects( [frontBox] );
- if(intersects.length > 0) {
- var intersect = intersects[0],
- point = intersect.point,
- face = intersect.face,
- faceObject = determineVolumeFace(face.normal),
- faceIdent = faceObject.getIdentifier();
- alreadyAdded = Object.keys(facesIntersect).indexOf(faceIdent) >= 0;
- if(alreadyAdded) {
- facesIntersect[faceIdent].count++;
- } else {
- facesIntersect[faceIdent] = { faceObject: faceObject, count: 1};
- }
- }
- }
- }
- frontFace = { count: 0 };
- for(faceIdent in facesIntersect) {
- if(facesIntersect[faceIdent].count > frontFace.count) {
- frontFace = facesIntersect[faceIdent];
- }
- }
- if(frontFace.faceObject != undefined) {
- volumeFace = frontFace.faceObject;
- axisOfNaviation = volumeFace.getAxisOfNaviation();
- planeOrientation = axisOfNaviation.plane;
- planeOrientation.hor.offsetTo = OffsetTo.LEFT;
- planeOrientation.ver.offsetTo = OffsetTo.TOP;
- planeOrientation.direction = volumeFace.direction;
- planeOrientation.orientation = volumeFace.orientation;
- sliderOrientation = axisOfNaviation.slider;
- sliderOrientation.offsetTo = OffsetTo.TOP;
- navigationPlaneHorLabel.html(planeOrientation.hor.getLabel());
- navigationPlaneVerLabel.html(planeOrientation.ver.getLabel());
- navigationSliderLabel.html(sliderOrientation.getLabel());
- }
- lastExecutionTime = Date.now();
- }
- }
- function determinePlanePosition() {
- if(!zoomedIn) {
- return;
- }
- if(navigationPlane.hasClass('ui-draggable-dragging')
- || navigationPlane.hasClass('no-pos-set')) {
- navigationPlane.addClass('no-pos-set');
- return;
- }
- horAxis = planeOrientation.hor.axis;
- verAxis = planeOrientation.ver.axis;
- planeRelativeX = navigationPlaneParent.width() / originalSizeArray[horAxis];
- planeRelativeY = navigationPlaneParent.height() / originalSizeArray[verAxis];
- planeWidth = planeRelativeX * zoomedInfoArray.dimension[horAxis];
- planeHeight = planeRelativeY * zoomedInfoArray.dimension[verAxis];
- planeWidth = Math.ceil(planeWidth);
- planeHeight = Math.ceil(planeHeight);
- planeOffsetLeft = zoomedInfoArray.offset[horAxis] * planeRelativeX;
- if((planeOrientation.direction == VolumeFaceDirection.BACK
- && planeOrientation.orientation == VolumeFaceOrientation.XZ)
- || (planeOrientation.direction == VolumeFaceDirection.FRONT
- && planeOrientation.orientation == VolumeFaceOrientation.YZ)) {
- planeOffsetLeft = navigationPlaneParent.width() - (planeOffsetLeft + navigationPlane.width());
- }
- planeOffsetTop = zoomedInfoArray.offset[verAxis] * planeRelativeY;
- if(planeOrientation.orientation == VolumeFaceOrientation.XZ
- || planeOrientation.orientation == VolumeFaceOrientation.YZ){
- planeOffsetTop = navigationPlaneParent.height() - (planeOffsetTop + navigationPlane.height());
- }
- navigationPlane.css({
- 'top': planeOffsetTop + 'px',
- 'left' : planeOffsetLeft + 'px',
- 'width': planeWidth + 'px',
- 'height': planeHeight + 'px'
- });
- navigationPlane.show();
- navigationPlaneParent.addClass('white');
- }
- function determineSliderPosition() {
- if(!zoomedIn) {
- return;
- }
- if(navigationSlider.hasClass('ui-draggable-dragging')
- || navigationSlider.hasClass('no-pos-set')) {
- navigationSlider.addClass('no-pos-set');
- return;
- }
- sliderRelative = navigationSliderParent.height() / originalSizeArray[sliderOrientation.axis];
- sliderOffsetTop = zoomedInfoArray.offset[sliderOrientation.axis] * sliderRelative;
- sliderHeight = Math.ceil(sliderRelative * zoomedInfoArray.dimension[sliderOrientation.axis]);
- if(planeOrientation.direction == VolumeFaceDirection.FRONT) {
- sliderOffsetTop = navigationSliderParent.height() - (navigationSlider.height() + sliderOffsetTop);
- }
- navigationSlider.css({
- 'top': sliderOffsetTop + 'px',
- 'height': sliderHeight + 'px'
- });
- navigationSlider.show();
- navigationSliderParent.addClass('white');
- }
- };
- function radToDeg(rad) {
- return rad * 180 / Math.PI;
- }
- ;var Orientation = function(axis, offsetTo) {
- this._axis = axis;
- this._offsetTo = null;
- }
- Orientation.prototype = {
- constructor: Orientation,
- getLabel: function() {
- switch(this._axis) {
- case(Axis.X):
- return 'x-axis';
- case(Axis.Y):
- return 'y-axis';
- case(Axis.Z):
- return 'z-axis';
- }
- },
- get axis() {
- return this._axis;
- },
- get offsetTo() {
- return this._offsetTo;
- },
- set offsetTo(value) {
- this._offsetTo = value;
- }
- }
- var Axis = {
- X: 0,
- Y: 1,
- Z: 2
- }
- var OffsetTo = {
- TOP: 0,
- LEFT: 1,
- BOTTOM: 2,
- RIGHT: 3
- }
- ;IPE.interceptors.SendInterceptor = (function() {
- return {
- init: function() {
- $(document).ajaxSend(function (e, xhr, settings) {
- if(settings.url.indexOf('/static/') === -1) {
- if(!settings.url.endsWith('/')) {
- settings.url += '/';
- }
- }
- });
- }
- };
- }())
- ;var NavigationPlane = function(element, horizontalLabel, verticalLabel) {
- this._element = element;
- this._parent = element.parent();
- this._horizontalLabel = horizontalLabel;
- this._verticalLabel = verticalLabel;
- this._zoomedInfoArray = null;
- this._volumeFace = null;
- }
- NavigationPlane.prototype = {
- constructor: NavigationPlane,
- set zoomedInfoArray(value) {
- this._zoomedInfoArray = value;
- },
- set volumeFace(value) {
- this._volumeFace = value;
- },
- }
- ;
|