let slideShowInterval = null let grabHotspotTimer = null let grabHotspotStart = null /** * Sets listener and attributes on model-viewer to * allow for click registering of a new hotspot */ readyAddHotspot = function() { const previewMv = $('model-viewer') previewMv.one('click', clickAddHotspot) previewMv.addClass('AddingHotspot') previewMv[0].disableTap = true previewMv[0].toggleAttribute('camera-controls') } /** * 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) { const previewMv = $('model-viewer') previewMv.removeClass('AddingHotspot') let hsPosition = null let targetModel = previewMv[0] targetModel.disableTap = false targetModel.toggleAttribute('camera-controls') 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") let orbitObj = targetModel.getCameraOrbit() hsOutput['data-orbit'] = `${orbitObj.theta.toFixed(2)}rad ${orbitObj.phi.toFixed(2)}rad ${orbitObj.radius.toFixed(2)}m` let targetObj = targetModel.getCameraTarget() hsOutput['data-target'] = `${targetObj.x.toFixed(5)}m ${targetObj.y.toFixed(5)}m ${targetObj.z.toFixed(5)}m` metadata.annotations['New Hotspot'] = hsOutput let newText = currentText.replace(/(.*?
)[\S\s]*?(<\/pre>.*)/,`$1\n${JSON.stringify(metadata, null, 2)}\n$2`)
        $('#wpTextbox1').val(newText)
    }
}

/**
 * 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()
	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 = 5000) {
    if (slideShowInterval) {
        clearInterval(slideShowInterval)
    } else {
        nextAnnotation(mView)
        slideShowInterval = setInterval(nextAnnotation, slideDuration, mView)
    }
}

/**
 * Toggle visibility of all annotations
 * 
 * @param {ModelViewer} mView 
 */
toggleAnnotations = function(mView) {
    [...mView.querySelectorAll('button')].forEach( hs => {
        hs.toggleAttribute('hidden')
    })
}

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

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

/**
 * End dragging a hotspot and update information
 * 
 * @param {MouseEvent} event
 */
releaseAnnotation = function(e) {
    if (grabHotspotStart) {
        e.target.style['transform']=''
        grabHotspotStart = null
        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
        })
        let orbitObj = mvEl.getCameraOrbit()
        const newOrb = `${orbitObj.theta.toFixed(2)}rad ${orbitObj.phi.toFixed(2)}rad ${orbitObj.radius.toFixed(2)}m`
        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)
    }
}

/**
 * Convert text in the preview text editor to js object
 * 
 * @param {string} editText
 * 
 * @return object containing metadata information
 */
extractMetadata = function(editText) {
    let 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 metadata
}