let slideShowInterval = null let grabHotspot = null let deleteHotspot = null let currentSet = 'default' /** * Disables hiding of various child items * once model has loaded */ modelLoaded = function(e) { $('.awaiting-model').css('display', 'flex').removeClass('awaiting-model') if (typeof enableMenu != 'undefined') {enableMenu()} } /** * Reads the json string in the edit panel * and updates hotspot elements * * @return {bool} true on successful read and update */ readMetadata = function() { let hotspotsObj = [] let metadata let slotNum = 1 createHotspot = function(hsLabel, hsSlot, hsTag) { let newHs = document.createElement('button') newHs.classList.add('Hotspot') newHs.setAttribute('slot',`hotspot-${hsSlot}`) newHs.setAttribute('ontouchstart', 'event.stopPropagation()') newHs.setAttribute('onclick', 'onAnnotation(event)') newHs.setAttribute('onmousedown', 'grabAnnotation(event)') newHs.setAttribute('onmouseup', 'releaseAnnotation(event)') Object.keys(metadata.annotations[hsLabel]).forEach((prop) => { newHs.setAttribute(prop, metadata.annotations[hsLabel][prop]) }) let newAn = document.createElement('div') newAn.classList.add('HotspotAnnotation', 'HiddenAnnotation') newAn.innerText = hsLabel newHs.appendChild(newAn) newLabel = document.createElement('span') newLabel.innerText = hsTag || (hsSlot) newHs.appendChild(newLabel) hotspotsObj.push(newHs) } try { [_, metadata] = extractMetadata() } catch (err) { console.warn('Failed to read model metadata:' + err.message) return false } if (currentSet != 'default' && metadata.annotationSets[currentSet]) { metadata.annotationSets[currentSet].forEach(hs => { createHotspot(hs, slotNum) slotNum += 1 }) } Object.keys(metadata.annotations).forEach(hs => { if (currentSet != 'default' && metadata.annotationSets[currentSet] && metadata.annotationSets[currentSet].includes(hs)) { return } let label = (currentSet != 'default' && metadata.annotationSets[currentSet]) ? '-' : null createHotspot(hs, slotNum, label) slotNum += 1 }) $('model-viewer button').remove() const mView = $('model-viewer')[0] hotspotsObj.forEach(hs => { mView.appendChild(hs) }) return true } /** * Parses the current hotspots into json object * and writes the json string to the edit panel * * @return {bool} true on successful write to edit panel */ writeMetadata = function () { let annotationsObj = {} currentButtons = $('.Hotspot').each(function() { let buttonEl = $(this)[0] annotationsObj[buttonEl.childNodes[0].innerText] = { "data-position": buttonEl.getAttribute('data-position'), "data-normal": buttonEl.getAttribute('data-normal'), "data-orbit": buttonEl.getAttribute('data-orbit'), "data-target": buttonEl.getAttribute('data-target') } }) if (Object.keys(annotationsObj).length === 0) return false const [currentText, metadata] = extractMetadata() metadata.annotations = annotationsObj const newText = currentText.replace(/(.*?
)[\S\s]*?(<\/pre>.*)/,`$1\n${JSON.stringify(metadata, null, 2)}\n$2`)
    $('#wpTextbox1').val(newText)
    return true
}

/**
 * Convert text in the preview text editor to js object
 * 
 * @return object containing metadata information
 */
extractMetadata = function() {
    const editText = $('#wpTextbox1').val()
    const extractMetadata = editText.match(/
([\S\s]*?)<\/pre>/)
    let metadata = (extractMetadata.length >= 2) ? JSON.parse(extractMetadata[1]) : {viewerConfig: {}, annotations: {}, annotationSets: {}}
    if (metadata.annotations === undefined) {
        metadata.annotations = {}
    }
    return [editText, metadata]
}

/**
 * Sets listener and attributes on model-viewer to
 * allow for click registering of a new hotspot
 */
readyAddHotspot = function() {
    disableViewer('AddingHotspot', clickAddHotspot)
}

/**
 * Event listener callback to retrieve the info
 * about the model surface point selected by the
 * mouse and add that information to the editor
 * text input
 * 
 * @param {PointerEvent} e 
 */
clickAddHotspot = function(e) {
    let hsPosition = null
    let targetModel = enableViewer()
    if (targetModel) {
        hsPosition = targetModel.positionAndNormalFromPoint(e.clientX, e.clientY)
    }
    if (hsPosition) {
        let currentText = $('#wpTextbox1').val()
        let [_, metadata] = extractMetadata(currentText)
        let hsOutput = {}
        hsOutput['data-position'] = hsPosition.position.toString().replaceAll(/(\d{5})(\d*?m)/g,"$1m")
        hsOutput['data-normal'] = hsPosition.normal.toString().replaceAll(/(\d{5})(\d*?m)/g,"$1m")
        hsOutput['data-orbit'] = orb2degree(targetModel.getCameraOrbit().toString(),[2,2,5])
        let targetObj = targetModel.getCameraTarget()
        hsOutput['data-target'] = `${targetObj.x.toFixed(5)}m ${targetObj.y.toFixed(5)}m ${targetObj.z.toFixed(5)}m`
        metadata.annotations['Hotspot ' + (Object.keys(metadata.annotations).length + 1)] = hsOutput
        let newText = currentText.replace(/(.*?
)[\S\s]*?(<\/pre>.*)/,`$1\n${JSON.stringify(metadata, null, 2)}\n$2`)
        $('#wpTextbox1').val(newText)
    }
    readMetadata()
}

/**
 * Set flag and attributes on model-viewer to
 * delete the next hotspot that is clicked
 */
readyDelHotspot = function() {
    deleteHotspot = true
    disableViewer('DeletingHotspot', cancelDeleteHotspot)
}

/**
 * Unset deleting flag and return normal
 * function and style to model viewer
 */
cancelDeleteHotspot = function() {
    deleteHotspot = null
    enableViewer()
}

/**
 * Event listener callback to toggle the visibility
 * of a hotspot's annotation when the hotspot is 
 * clicked
 * 
 * @param {PointerEvent} e 
 */
onAnnotation = function(e) {
	e.stopPropagation()
    if (deleteHotspot) {
        deleteHotspot = null
        enableViewer()
        const anName = e.target.childNodes[0].innerText
        let purgeAnnotation = new RegExp('(?<="annotationSets"[\\S\\s]*?)(^.*?' + anName + '.*\n)','gm')
        e.target.remove()
        const editText = $('#wpTextbox1').val()
        const newText = editText.replace(purgeAnnotation,'')
        const finalText = newText.replace(/(,)(\n\s+])/gm,'$2')
        $('#wpTextbox1').val(finalText)
        writeMetadata()
        readMetadata()
        return     
    }
	let targetAnnotation = Number.parseInt(e.target.slot.split('-')[1])
	let targetModel = e.target.closest('model-viewer')
    selectAnnotation(targetModel, targetAnnotation)
}

/**
 * Event listener callback to hide all hotspot
 * annotations when the model-viewer receives
 * a click event
 */
clearAnnotations = function() {
	[...document.getElementsByClassName('HotspotAnnotation')].forEach( an => {
		an.classList.add('HiddenAnnotation')
	})
};

/**
 * Select the numbered hotspot of the given model
 * 
 * @param {ModelViewer} mView
 * @param {number} annotId
 * 
 * @return {bool} true if annotation selected false if unselected
 */
selectAnnotation = function(mView, annotId) {
    let anSelected = false;
    [...mView.querySelectorAll('.HotspotAnnotation')].forEach( (an, idx) => {
		if (idx + 1 == annotId && an.classList.contains('HiddenAnnotation')) {
			an.classList.remove('HiddenAnnotation');
			if (an.parentElement.dataset.target) {mView.cameraTarget = an.parentElement.dataset.target}
			if (an.parentElement.dataset.orbit) {mView.cameraOrbit = an.parentElement.dataset.orbit}
            anSelected = true
		} else {
			an.classList.add('HiddenAnnotation');
		}        
	});
    return anSelected
}

/**
 * Select the next numbered hotspot
 * 
 * @param {ModelViewer} mView
 * 
 * @return {number} ID number of the newly selected hotspot
 */
nextAnnotation = function(mView) {
    let incrAnnotation = 0
    const numSpots = [...mView.querySelectorAll('Button')].length
    const currentAnnotation = mView.querySelectorAll('Button:has(.HotspotAnnotation:not(.HiddenAnnotation))')[0]
    if (!currentAnnotation) {
        incrAnnotation = 1
    } else {
        const annotationId = Number.parseInt(currentAnnotation.slot.split('-')[1])
        incrAnnotation = (annotationId >= numSpots)
            ? 1
            : annotationId + 1
    }
    selectAnnotation(mView, incrAnnotation)
    return incrAnnotation
}

/**
 * Select the previous numbered hotspot
 * 
 * @param {ModelViewer} mView
 * 
 * @return {number} ID number of the newly selected hotspot
 */
prevAnnotation = function(mView) {
    let decrAnnotation = 0
    const numSpots = [...mView.querySelectorAll('Button')].length
    const currentAnnotation = mView.querySelectorAll('Button:has(.HotspotAnnotation:not(.HiddenAnnotation))')[0]
    if (!currentAnnotation) {
        decrAnnotation = numSpots
    } else {
        const annotationId = Number.parseInt(currentAnnotation.slot.split('-')[1])
        decrAnnotation = (annotationId <= 1)
            ? numSpots
            : annotationId - 1
    }
    selectAnnotation(mView, decrAnnotation)
    return decrAnnotation
}

/**
 * Cycle through the available annotations
 * 
 * @param {ModelViewer} mView
 * 
 * @param {Number} [slideDuration = 5000]
 * 
 * @return {intervalID} ID of the created interval timer
 */
slideshowAnnotations = function(mView, slideDuration = 3000) {
    if (slideShowInterval) {
        clearInterval(slideShowInterval)
    } else {
        nextAnnotation(mView)
        slideShowInterval = setInterval(nextAnnotation, slideDuration, mView)
    }
}

/**
 * Toggle visibility of all annotations
 * 
 * @param {ModelViewer} mView 
 */
toggleAnnotations = function(mView) {
    if (slideShowInterval) {
        clearInterval(slideShowInterval)
        const slideButton = mView.parentElement.querySelector('[toggled]')
        if (slideButton) slideButton.toggleAttribute('toggled')
    }
    [...mView.querySelectorAll('button')].forEach( hs => {
        hs.toggleAttribute('hidden')
    })
    const hsButtons = [...mView.parentElement.querySelectorAll('.disable-on-hide')]
    hsButtons.forEach( mb => {
        mb.toggleAttribute('disabled')
    })
}

/**
 * Prepare to drag a hotspot
 * 
 * @param {MouseEvent} event
 */
grabAnnotation = function(e) {
    if (e.ctrlKey) {
        grabHotspot = {x: e.x, y: e.y}
        const contEl = $('.glmv-container')[0]
        contEl.addEventListener('mousemove', moveAnnotation)
        const mvEl = $('model-viewer')[0]
    } else {
        grabHotspot = null
    }
}

/**
 * Drag currently clicked hotspot
 * 
 * @param {MouseEvent} event
 */
moveAnnotation = function(e) {
    if (grabHotspot) {
        grabHotspot.move = true
        e.target.style['transform'] = `translate(${e.x - grabHotspot.x}px, ${e.y - grabHotspot.y}px) scale(1.1,1.1)`
    }
}

/**
 * End dragging a hotspot and update information
 * 
 * @param {MouseEvent} event
 */
releaseAnnotation = function(e) {
    if (grabHotspot && grabHotspot.move) {
        e.target.style['transform']=''
        const contEl = $('.glmv-container')[0]
        contEl.removeEventListener('mousemove', moveAnnotation)
        const mvEl = $('model-viewer')[0]
        let newPosition = mvEl.positionAndNormalFromPoint(e.clientX, e.clientY)
        const newPos = newPosition.position.toString().replaceAll(/(\d{5})(\d*?m)/g,"$1m")
        const newNorm = newPosition.normal.toString().replaceAll(/(\d{5})(\d*?m)/g,"$1m")
        mvEl.updateHotspot({
            name: e.target.slot,
            position: newPos,
            normal: newNorm
        })
        const newOrb = orb2degree(mvEl.getCameraOrbit().toString(),[2,2,5])
        e.target.setAttribute('data-orbit', newOrb)
        let targetObj = mvEl.getCameraTarget()
        const newTarg = `${targetObj.x.toFixed(5)}m ${targetObj.y.toFixed(5)}m ${targetObj.z.toFixed(5)}m`
        e.target.setAttribute('data-target', newTarg)
        let currentText = $('#wpTextbox1').val()
        let [_, metadata] = extractMetadata(currentText)
        metadata.annotations[e.target.childNodes[0].innerText] = {
            "data-position": newPos,
            "data-normal": newNorm,
            "data-orbit": newOrb,
            "data-target": newTarg
        }
        const newText = currentText.replace(/(.*?
)[\S\s]*?(<\/pre>.*)/,`$1\n${JSON.stringify(metadata, null, 2)}\n$2`)
        $('#wpTextbox1').val(newText)
    }
    grabHotspot = null
}

/**
 * Disable general interaction with model
 * viewer for specific additional function
 * 
 * @param {string} fnClass class to add to model-viewer
 * @param {callback} viewCall callback function to add to model-viewer
 * @return {Element} model-viewer element
 */
disableViewer = function(fnClass, viewCall) {
    const previewMv = $('model-viewer')
    if (viewCall) previewMv.one('click', viewCall)
    if (fnClass) previewMv.addClass(fnClass)
    previewMv[0].disableTap = true
    previewMv[0].toggleAttribute('camera-controls', false)
    return previewMv[0]
}

/**
 * Enable general interaction with model
 * viewer
 * 
 * @return {Element} model-viewer element
 */
enableViewer = function() {
    const previewMv = $('model-viewer')
    previewMv.off('click', clickAddHotspot)
    previewMv.off('click', cancelDeleteHotspot)
    previewMv.removeClass('AddingHotspot DeletingHotspot')
    previewMv[0].disableTap = false
    previewMv[0].toggleAttribute('camera-controls', true)
    return previewMv[0]
}

/**
 * Use the model viewer methods to get image 
 * of current view and download
 * 
 * @param {string} defName wiki page name to use as base file name
 */
downloadImage = function(defName) {
    const imgName = defName.split('.')[0]
    const mView = $('model-viewer')[0]

    const dlA = document.createElement('a')
    dlA.setAttribute('download',imgName + '.png')

    const reader = new FileReader()
    reader.addEventListener("load", () => {
        dlA.setAttribute('href',reader.result)
        dlA.click()
    },{once: true})

    mView.toBlob(null, null, true)
        .then(imgBlob => {
            reader.readAsDataURL(imgBlob)
        })
}

/**
 * Respond to full screen changes on the gl container
 * 
 * @param {Element} glCont container element to enlarge or reduce
 */
toggleFullScreen = function(glCont) {
    if (document.fullscreenElement) {
        document.exitFullscreen()
    } else {
        glCont.requestFullscreen()
    }
}

/**
 * Send new default camera orbit values to the preview editor
 */
writeCameraOrbit = function() {
    const mView = $('model-viewer')[0]
    let newOrbit = orb2degree(mView.getCameraOrbit().toString(),[2,2,5])
    const textUpdate = $('#wpTextbox1').val().replace(/([\S\s]*?default[\S\s]*?"camera-orbit": ")(.*?)(",$[\S\s]*)/gm,'$1' + newOrbit + '$3')
    $('#wpTextbox1').val(textUpdate)
}

/**
 * Set new camera orbit limits and send values to the preview
 * editor
 * 
 * @param {string} axis [yaw|pitch] orbit value to set
 * @param {string} limit [max|min] limit value to set
 */
limitCameraOrbit = function(axis, limit) {
    const mView = $('model-viewer')[0]
    const newOrbit = orb2degree(mView.getCameraOrbit().toString(),[2,2,5])
    const newOrbitVals = newOrbit.split(' ')
    const valueIndex = (axis == 'yaw') ? 0 : 1
    let [currentText, metadata] = extractMetadata()
    const oldOrbit = metadata.viewerConfig.default[`${limit}-camera-orbit`]
    let oldOrbitVals = (oldOrbit) ? oldOrbit.split(' ') : Array(3).fill('auto')
    oldOrbitVals[valueIndex] = newOrbitVals[valueIndex]
    metadata.viewerConfig.default[`${limit}-camera-orbit`] = oldOrbitVals.join(' ')
    mView.setAttribute(`${limit}-camera-orbit`, oldOrbitVals.join(' '))
    const newText = currentText.replace(/(.*?
)[\S\s]*?(<\/pre>.*)/,`$1\n${JSON.stringify(metadata, null, 2)}\n$2`)
    $('#wpTextbox1').val(newText)
}

/**
 * Convert all radian values returned by model-viewer to degrees
 * 
 * @param {string} orbString string with any number of `(number)rad` sub strings
 * @param {number|array} fix Optional: number of decimal places to return in converted numbers
 * @return {string} string with all radian values and units converted to degrees
 */
orb2degree = function(orbString, fix = null) {
    let degArray = orbString.split(' ').map(s => {
        if (s.includes('rad')) {
            return (Number.parseFloat(s) / Math.PI * 180) + 'deg'
        } else {
            return s
        }
    })
    if (fix && !['number', 'object'].includes(typeof fix)) {
        console.warn('orb2degree: fix parameter invalid type. Ignoring.')
        fix = null
    }
    if (fix) {
        degArray = degArray.map((v, idx) => {
            let fixReg = new RegExp('(\\d*.\\d{' + (((typeof fix) == 'object') ? fix[idx] : fix) + '})(\\d*)([a-z]*)')
            return v.replace(fixReg,'$1$3')
        })
    }
    return degArray.join(' ')
}

/**
 * Change the currently selected annotation set
 * 
 * @param {string} newSet name of annotation set to select
 */
selectAnnotationSet = function(newSet) {
    currentSet = newSet
    readMetadata()
}