diff --git a/.gitattributes b/.gitattributes index a314bc9c5d811100bc2f8b2966ffb2d39ddccc69..7cb82af77b574ba8f9ceecc2b3bbd772a35322ba 100644 --- a/.gitattributes +++ b/.gitattributes @@ -37,3 +37,5 @@ Auto-Photoshop-StableDiffusion-Plugin/docs/inpainting.gif filter=lfs diff=lfs me Auto-Photoshop-StableDiffusion-Plugin/docs/outpainting.gif filter=lfs diff=lfs merge=lfs -text Auto-Photoshop-StableDiffusion-Plugin/docs/prompt_shortcut.gif filter=lfs diff=lfs merge=lfs -text Stable-Diffusion-Webui-Civitai-Helper/img/all_in_one.png filter=lfs diff=lfs merge=lfs -text +posex/image/sample-webui2.jpg filter=lfs diff=lfs merge=lfs -text +posex/image/sample-webui2.png filter=lfs diff=lfs merge=lfs -text diff --git a/openpose-editor/scripts/openpose/util.py b/openpose-editor/scripts/openpose/util.py new file mode 100644 index 0000000000000000000000000000000000000000..647bad1c4ae693143a43afb499b368baa44832d8 --- /dev/null +++ b/openpose-editor/scripts/openpose/util.py @@ -0,0 +1,166 @@ +# This code from https://github.com/lllyasviel/ControlNet + +import math +import numpy as np +import matplotlib +import cv2 + + +def padRightDownCorner(img, stride, padValue): + h = img.shape[0] + w = img.shape[1] + + pad = 4 * [None] + pad[0] = 0 # up + pad[1] = 0 # left + pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down + pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right + + img_padded = img + pad_up = np.tile(img_padded[0:1, :, :]*0 + padValue, (pad[0], 1, 1)) + img_padded = np.concatenate((pad_up, img_padded), axis=0) + pad_left = np.tile(img_padded[:, 0:1, :]*0 + padValue, (1, pad[1], 1)) + img_padded = np.concatenate((pad_left, img_padded), axis=1) + pad_down = np.tile(img_padded[-2:-1, :, :]*0 + padValue, (pad[2], 1, 1)) + img_padded = np.concatenate((img_padded, pad_down), axis=0) + pad_right = np.tile(img_padded[:, -2:-1, :]*0 + padValue, (1, pad[3], 1)) + img_padded = np.concatenate((img_padded, pad_right), axis=1) + + return img_padded, pad + +# transfer caffe model to pytorch which will match the layer name +def transfer(model, model_weights): + transferred_model_weights = {} + for weights_name in model.state_dict().keys(): + transferred_model_weights[weights_name] = model_weights['.'.join(weights_name.split('.')[1:])] + return transferred_model_weights + +# draw the body keypoint and lims +def draw_bodypose(canvas, candidate, subset): + stickwidth = 4 + limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \ + [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \ + [1, 16], [16, 18], [3, 17], [6, 18]] + + colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \ + [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \ + [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]] + for i in range(18): + for n in range(len(subset)): + index = int(subset[n][i]) + if index == -1: + continue + x, y = candidate[index][0:2] + cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1) + for i in range(17): + for n in range(len(subset)): + index = subset[n][np.array(limbSeq[i]) - 1] + if -1 in index: + continue + cur_canvas = canvas.copy() + Y = candidate[index.astype(int), 0] + X = candidate[index.astype(int), 1] + mX = np.mean(X) + mY = np.mean(Y) + length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5 + angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1])) + polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1) + cv2.fillConvexPoly(cur_canvas, polygon, colors[i]) + canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0) + # plt.imsave("preview.jpg", canvas[:, :, [2, 1, 0]]) + # plt.imshow(canvas[:, :, [2, 1, 0]]) + return canvas + + +# image drawn by opencv is not good. +def draw_handpose(canvas, all_hand_peaks, show_number=False): + edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \ + [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]] + + for peaks in all_hand_peaks: + for ie, e in enumerate(edges): + if np.sum(np.all(peaks[e], axis=1)==0)==0: + x1, y1 = peaks[e[0]] + x2, y2 = peaks[e[1]] + cv2.line(canvas, (x1, y1), (x2, y2), matplotlib.colors.hsv_to_rgb([ie/float(len(edges)), 1.0, 1.0])*255, thickness=2) + + for i, keyponit in enumerate(peaks): + x, y = keyponit + cv2.circle(canvas, (x, y), 4, (0, 0, 255), thickness=-1) + if show_number: + cv2.putText(canvas, str(i), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 0), lineType=cv2.LINE_AA) + return canvas + +# detect hand according to body pose keypoints +# please refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/src/openpose/hand/handDetector.cpp +def handDetect(candidate, subset, oriImg): + # right hand: wrist 4, elbow 3, shoulder 2 + # left hand: wrist 7, elbow 6, shoulder 5 + ratioWristElbow = 0.33 + detect_result = [] + image_height, image_width = oriImg.shape[0:2] + for person in subset.astype(int): + # if any of three not detected + has_left = np.sum(person[[5, 6, 7]] == -1) == 0 + has_right = np.sum(person[[2, 3, 4]] == -1) == 0 + if not (has_left or has_right): + continue + hands = [] + #left hand + if has_left: + left_shoulder_index, left_elbow_index, left_wrist_index = person[[5, 6, 7]] + x1, y1 = candidate[left_shoulder_index][:2] + x2, y2 = candidate[left_elbow_index][:2] + x3, y3 = candidate[left_wrist_index][:2] + hands.append([x1, y1, x2, y2, x3, y3, True]) + # right hand + if has_right: + right_shoulder_index, right_elbow_index, right_wrist_index = person[[2, 3, 4]] + x1, y1 = candidate[right_shoulder_index][:2] + x2, y2 = candidate[right_elbow_index][:2] + x3, y3 = candidate[right_wrist_index][:2] + hands.append([x1, y1, x2, y2, x3, y3, False]) + + for x1, y1, x2, y2, x3, y3, is_left in hands: + # pos_hand = pos_wrist + ratio * (pos_wrist - pos_elbox) = (1 + ratio) * pos_wrist - ratio * pos_elbox + # handRectangle.x = posePtr[wrist*3] + ratioWristElbow * (posePtr[wrist*3] - posePtr[elbow*3]); + # handRectangle.y = posePtr[wrist*3+1] + ratioWristElbow * (posePtr[wrist*3+1] - posePtr[elbow*3+1]); + # const auto distanceWristElbow = getDistance(poseKeypoints, person, wrist, elbow); + # const auto distanceElbowShoulder = getDistance(poseKeypoints, person, elbow, shoulder); + # handRectangle.width = 1.5f * fastMax(distanceWristElbow, 0.9f * distanceElbowShoulder); + x = x3 + ratioWristElbow * (x3 - x2) + y = y3 + ratioWristElbow * (y3 - y2) + distanceWristElbow = math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2) + distanceElbowShoulder = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) + width = 1.5 * max(distanceWristElbow, 0.9 * distanceElbowShoulder) + # x-y refers to the center --> offset to topLeft point + # handRectangle.x -= handRectangle.width / 2.f; + # handRectangle.y -= handRectangle.height / 2.f; + x -= width / 2 + y -= width / 2 # width = height + # overflow the image + if x < 0: x = 0 + if y < 0: y = 0 + width1 = width + width2 = width + if x + width > image_width: width1 = image_width - x + if y + width > image_height: width2 = image_height - y + width = min(width1, width2) + # the max hand box value is 20 pixels + if width >= 20: + detect_result.append([int(x), int(y), int(width), is_left]) + + ''' + return value: [[x, y, w, True if left hand else False]]. + width=height since the network require squared input. + x, y is the coordinate of top left + ''' + return detect_result + +# get max index of 2d array +def npmax(array): + arrayindex = array.argmax(1) + arrayvalue = array.max(1) + i = arrayvalue.argmax() + j = arrayindex[i] + return i, j diff --git a/posex/.gitignore b/posex/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..22253400b227b257e5dfa1b98d89f8052881ac26 --- /dev/null +++ b/posex/.gitignore @@ -0,0 +1,3 @@ +__pycache__ +.vscode/ +venv/ diff --git a/posex/README.md b/posex/README.md new file mode 100644 index 0000000000000000000000000000000000000000..69b0a5604707fc40035a85e5ee9d58a796c2a1b7 --- /dev/null +++ b/posex/README.md @@ -0,0 +1,98 @@ +# Posex - Estimated Image Generator for Pose2Image + +![cover](./image/sample.png) + +## Quick Start with [Web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) + +1. Install [Mikubill/sd-webui-controlnet](https://github.com/Mikubill/sd-webui-controlnet). +2. Install Posex (this). +3. Open `Posex` accordion in t2i tab (or i2i as you like). Enable `Send this image to ControlNet` checkbox. Editor will appear. +4. Configure ControlNet as below. +``` +Preprocessor: none +Model: control_sd15_openpose +``` +5. Make pose. +6. Generate images. + +## How to use + +``` +Click: select body +Left Drag: move joint (on joint) + rotate camera (otherwise) +Right Drag: move whole body (if selected) + move camera (otherwise) +Wheel: zoom +``` + +## Installation + +- [Web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) Extension +- Online (Github Pages) +- Standalone + +### [Web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) Extension + +**Prerequirement: You need to install [Mikubill/sd-webui-controlnet](https://github.com/Mikubill/sd-webui-controlnet) to use Posex with ControlNet Pose2Img.** + +Go to `Extensions` tab, then select `Install from URL` tab and input `https://github.com/hnmr293/posex`. + +Or move to `extensions` directory and type `git clone https://github.com/hnmr293/posex`. + +In webui, open `Posex` accordion in `txt2img` or `img2img` tab, then click a checkbox. The canvas will be opened. + +### Online + +See Github Pages. + +[https://hnmr293.github.io/posex](https://hnmr293.github.io/posex) + +### Standalone + +``` +$ pip install -r requirements.txt +$ python app.py +``` + +Then open `localhost:55502` or `127.0.0.1:55502` in your browser. + +## Example + +### Web UI + +sample 1: + +![sample](./image/sample-webui.png) + +result: + +![sample result](./image/sample-webui2.jpg) + +sample 2: + +![sample 2](./saved_poses/bridge.png) + +result: + +![sample 2 result](./image/sample-webui3.png) + +### Standalone + +![sample](./image/sample.png) + +## History + +### v0.3 -> v0.4 features +- background setting +- save/load pose +- fixed camera roll + +### v0.2 -> v0.3 features +- Web UI extension + +### v0.1 -> v0.2 features +- copying the image to clipboard +- multiple bodies +- canvas size changing +- UI has become ugly >_<; diff --git a/posex/app.py b/posex/app.py new file mode 100644 index 0000000000000000000000000000000000000000..ad13a070c5725f2621085b3d591764b0f5e46092 --- /dev/null +++ b/posex/app.py @@ -0,0 +1,85 @@ +from typing import Union + +def ensure_install(module_name: str, lib_name: Union[str,None] = None): + from importlib.util import find_spec + + if lib_name is None: + lib_name = module_name + + if find_spec(module_name) is None: + import subprocess + try: + print('-' * 80, file=sys.stderr) + print(f'| installing {lib_name} ...', file=sys.stderr) + print('-' * 80, file=sys.stderr) + subprocess.check_call( + [sys.executable, "-m", "pip", "install", lib_name], + stdout=sys.stdout, + stderr=sys.stderr + ) + except Exception as e: + msg = ''.join(traceback.TracebackException.from_exception(e).format()) + print(msg, file=sys.stderr) + print('-' * 80, file=sys.stderr) + print(f'| failed to install {lib_name}. exit...', file=sys.stderr) + print('-' * 80, file=sys.stderr) + sys.exit(1) + +if __name__ == '__main__': + import mimetypes + mimetypes.add_type('application/javascript', '.js') + + import os, sys, traceback + from functools import wraps + + ensure_install('flask') + ensure_install('PIL', 'pillow') + + from flask import Flask, jsonify, request + from common import posex_utils as posex + + app = Flask(__name__, static_folder='.', static_url_path='') + + posex.set_save_dir(os.path.join(app.static_folder, 'saved_poses')) + + @app.route('/') + def index(): + return app.send_static_file('index.html') + + def api_try(fn): + @wraps(fn) + def f(*args, **kwargs): + try: + return fn(*args, **kwargs) + except Exception as e: + msg = ''.join(traceback.TracebackException.from_exception(e).format()) + print(msg, file=sys.stderr) + return jsonify(result=str(e), ok=False) + return f + + @app.route('/pose/all') + @api_try + def all_poses(): + return jsonify(list(posex.all_poses())) + + @app.route('/pose/save', methods=['POST']) + @api_try + def save_pose(): + data = request.json + posex.save_pose(data) + return jsonify(result='pose saved', ok=True) + + @app.route('/pose/delete', methods=['POST']) + @api_try + def delete_pose(): + data = request.json + posex.delete_pose(data['name']) + return jsonify(result='pose deleted', ok=True) + + @app.route('/pose/load', methods=['POST']) + @api_try + def load_pose(): + data = request.json + return jsonify(posex.load_pose(data['name'])) + + app.run(port=55502, debug=True) diff --git a/posex/common/__pycache__/posex_utils.cpython-310.pyc b/posex/common/__pycache__/posex_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dce24475db56cdb32fffa9772b3a6fa3b18c7a2 Binary files /dev/null and b/posex/common/__pycache__/posex_utils.cpython-310.pyc differ diff --git a/posex/common/posex_utils.py b/posex/common/posex_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e8fce8194645b8896e3194c0633ce9e12337b3d2 --- /dev/null +++ b/posex/common/posex_utils.py @@ -0,0 +1,111 @@ +import os, glob, json, base64, re +from io import BytesIO +from PIL import Image, PngImagePlugin + +_SAVED_POSES_DIR = '' + +def set_save_dir(dir: str): + global _SAVED_POSES_DIR + _SAVED_POSES_DIR = os.path.realpath(str(dir)) + +def get_save_dir(): + assert len(_SAVED_POSES_DIR) != 0 + return _SAVED_POSES_DIR + +def get_saved_path(name: str): + #return os.path.realpath(os.path.join(get_save_dir(), name)) + return os.path.join(get_save_dir(), name) + +def atoi(text): + return int(text) if text.isdigit() else text + +def natural_keys(text): + return [ atoi(c) for c in re.split(r'(\d+)', text) ] + +def sorted_glob(path): + return sorted(glob.glob(path), key=natural_keys) + +def name2path(name: str): + if not isinstance(name, str): + raise ValueError(f'str object expected, but {type(name)}') + + if len(name) == 0: + raise ValueError(f'empty name') + + if '.' in name or '/' in name or '\\' in name: + raise ValueError(f'invalid name: {name}') + + path = get_saved_path(f'{name}.png') + if not path.startswith(get_save_dir()): + raise ValueError(f'invalid name: {name}') + + return path + +def saved_poses(): + for path in sorted_glob(os.path.join(get_save_dir(), '*.png')): + yield Image.open(path) + +def all_poses(): + for img in saved_poses(): + buffer = BytesIO() + img.save(buffer, format='png') + + if not hasattr(img, 'text'): + continue + + pose_dict = { + 'name': img.text['name'], # type: ignore + 'image': base64.b64encode(buffer.getvalue()).decode('ascii'), + 'screen': json.loads(img.text['screen']), # type: ignore + 'camera': json.loads(img.text['camera']), # type: ignore + 'joints': json.loads(img.text['joints']), # type: ignore + } + + yield pose_dict + +def save_pose(data: dict): + name = data['name'] + screen = data['screen'] + camera = data['camera'] + joints = data['joints'] + + info = PngImagePlugin.PngInfo() + info.add_text('name', name) + info.add_text('screen', json.dumps(screen)) + info.add_text('camera', json.dumps(camera)) + info.add_text('joints', json.dumps(joints)) + + filepath = name2path(name) + + image = Image.open(BytesIO(base64.b64decode(data['image'][len('data:image/png;base64,'):]))) + unit = max(image.width, image.height) + mx, my = (unit - image.width) // 2, (unit - image.height) // 2 + canvas = Image.new('RGB', (unit, unit), color=(68, 68, 68)) + canvas.paste(image, (mx, my)) + image = canvas.resize((canvas.width//4, canvas.height//4)) + + image.save(filepath, pnginfo=info) + +def delete_pose(name: str): + filepath = name2path(name) + os.remove(filepath) + +def load_pose(name: str): + filepath = name2path(name) + img = Image.open(filepath) + + buffer = BytesIO() + img.save(buffer, format='png') + + if not hasattr(img, 'text'): + raise ValueError(f'not pose data: {filepath}') + + pose_dict = { + 'name': img.text['name'], # type: ignore + 'image': base64.b64encode(buffer.getvalue()).decode('ascii'), + 'screen': json.loads(img.text['screen']), # type: ignore + 'camera': json.loads(img.text['camera']), # type: ignore + 'joints': json.loads(img.text['joints']), # type: ignore + } + + return pose_dict diff --git a/posex/css/main.css b/posex/css/main.css new file mode 100644 index 0000000000000000000000000000000000000000..2fa2b2f7fdfe7a1d459a865c320a3b533a40bc48 --- /dev/null +++ b/posex/css/main.css @@ -0,0 +1,125 @@ +#cont { + display: flex; + flex-flow: column; + gap: 0.5em 0; + width: max-content; +} + +.box { + display: block; + border: 1px solid gray; + padding: 0.5em 0; + text-decoration: none; + text-align: center; +} + +#notation { + display: none; + position: absolute; + color: black; + background-color: rgba(255, 255, 255, 0.75); + padding: 0.1em 0.25em; + pointer-events: none; + font-size: small; +} + +#notifications { + left: 1em; + bottom: 0; + width: 25%; +} + +#notifications .item { + padding: 0.5em; + border: 1px solid gray; + animation: erase 2s ease-out 0.5s forwards; +} + +@keyframes erase { + 100% { + opacity: 0; + } +} + +#notifications .success { + background-color: #aaccaa; + color: #004000; +} + +#notifications .info { + background-color: white; + color: black; +} + +#notifications .error { + background-color: #ffcccc; + color: red; +} + +#body_indicator1 { + display: none; + position: absolute; + outline: 1px solid white; + pointer-events: none; +} + +#body_indicator2 { + display: none; + position: absolute; + outline: 1px solid gray; + pointer-events: none; +} + +#saved_poses { + display: flex; + flex-direction: row; + gap: 0.25em; + font-size: small; +} + +#saved_poses > * { + margin: 0; + outline: 1px solid gray; + max-width: 128px; +} + +#saved_poses img { + max-width: 128px; + max-height: 128px; +} + +#saved_poses figcaption { + padding: 0 0.25em; + overflow-wrap: anywhere; /* Opera Android may not be able to interpret `anywhere` keyword. */ +} + +#saved_poses .close { + position: absolute; + cursor: pointer; + border: 1px solid gray; + background-color: white; + opacity: 0.5; + width: 1.25em; + height: 1.25em; + text-align: center; + vertical-align: middle; + margin: 0; + font-family: monospace; +} + +#saved_poses .close:hover { + opacity: 1.0; +} + +#saved_poses .close2 { + display: none; + position: absolute; + left: 1.5em; + top: 0; +} + +#saved_poses .close:hover .close2 { + display: block; + color: white; + pointer-events: none; +} \ No newline at end of file diff --git a/posex/image/favicon.ico b/posex/image/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..6d0e28e3ab7e60f7f3b098e98711ef425e82b523 Binary files /dev/null and b/posex/image/favicon.ico differ diff --git a/posex/image/favicon.png b/posex/image/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..969595981c45f06b878b58990c6f078aae38f1a9 Binary files /dev/null and b/posex/image/favicon.png differ diff --git a/posex/image/sample-webui.png b/posex/image/sample-webui.png new file mode 100644 index 0000000000000000000000000000000000000000..e68914425f91ce58c7016cd5492a235937a9f6c6 Binary files /dev/null and b/posex/image/sample-webui.png differ diff --git a/posex/image/sample-webui2.jpg b/posex/image/sample-webui2.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0f9695dbb3f8e500881dc5cf10effe49489f91d2 --- /dev/null +++ b/posex/image/sample-webui2.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:223435fe63ead0763f59af73c8cc76fa4f54a22d98efcc2923b2bdbbee8ad97b +size 1364219 diff --git a/posex/image/sample-webui2.png b/posex/image/sample-webui2.png new file mode 100644 index 0000000000000000000000000000000000000000..f906d1c6095a0982c8e4935da8a566e783a82977 --- /dev/null +++ b/posex/image/sample-webui2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e1aec128752571d39aea4e7f9faad31976f14a538defb07637dc939e84a1af2a +size 4052870 diff --git a/posex/image/sample-webui3.png b/posex/image/sample-webui3.png new file mode 100644 index 0000000000000000000000000000000000000000..c056438c429068195152f0bc2f16a7923794b50e Binary files /dev/null and b/posex/image/sample-webui3.png differ diff --git a/posex/image/sample.png b/posex/image/sample.png new file mode 100644 index 0000000000000000000000000000000000000000..61c6e112c29b95dc34b867ec25bfdf42b32979c8 Binary files /dev/null and b/posex/image/sample.png differ diff --git a/posex/index.html b/posex/index.html new file mode 100644 index 0000000000000000000000000000000000000000..0d87505aa29897ac5b523fe2d096e3c1110975d6 --- /dev/null +++ b/posex/index.html @@ -0,0 +1,74 @@ + + + + + Posex - Estimated Image Generator for Pose2Image + + + + + + + + + +
+ +
+ + +
+
+ + + +
+
- Camera
+ +
- Body
+ + +
- Canvas Size
+ + +
- Background
+
+ + +
+
- Joints and Limbs
+ + + +
- Others
+ +
+
+
+
+
+ 💾 Save Image + 📋 Copy to clipboard +
+ +
+
+

+
+ + + \ No newline at end of file diff --git a/posex/javascript/lazyload/posex-webui.js b/posex/javascript/lazyload/posex-webui.js new file mode 100644 index 0000000000000000000000000000000000000000..510422fa8c316272be67eaaf5cffee4fdaa94820 --- /dev/null +++ b/posex/javascript/lazyload/posex-webui.js @@ -0,0 +1,386 @@ +async function _import() { + if (!globalThis.posex || !globalThis.posex.import) { + return await import('posex'); + } else { + return await globalThis.posex.imports.posex(); + } +} +const { init, init_3d } = await _import(); + +(async function () { + let _r = 0; + function to_gradio(v) { + // force call `change` event on gradio + return [v.toString(), (_r++).toString()]; + } + + function js2py(type, gradio_field, value) { + // set `value` to gradio's field + // (1) Click gradio's button. + // (2) Gradio will fire js callback to retrieve value to be set. + // (3) Gradio will fire another js callback to notify the process has been completed. + return new Promise(resolve => { + const callback_name = `posex-${type}-${gradio_field}`; + + // (2) + globalThis[callback_name] = () => { + + delete globalThis[callback_name]; + + // (3) + const callback_after = callback_name + '_after'; + globalThis[callback_after] = () => { + delete globalThis[callback_after]; + resolve(); + }; + + return to_gradio(value); + }; + + // (1) + gradioApp().querySelector(`#${callback_name}_set`).click(); + }); + } + + function py2js(type, pyname, ...args) { + // call python's function + // (1) Set args to gradio's field + // (2) Click gradio's button + // (3) JS callback will be kicked with return value from gradio + + // (1) + return (args.length == 0 ? Promise.resolve() : js2py(type, pyname + '_args', JSON.stringify(args))) + .then(() => { + return new Promise(resolve => { + const callback_name = `posex-${type}-${pyname}`; + // (3) + globalThis[callback_name] = value => { + delete globalThis[callback_name]; + resolve(value); + } + // (2) + gradioApp().querySelector(`#${callback_name}_get`).click(); + }); + }); + } + + function reload_poses(json, ui) { + const df = document.createDocumentFragment(); + for (let data of json) { + const fig = document.createElement('figure') + const img = document.createElement('img'); + const cap = document.createElement('figcaption'); + const clo = document.createElement('div'); + const cloimg = document.createElement('img'); + const clo2 = document.createElement('span'); + fig.dataset.poseName = data.name; + cap.textContent = data.name; + clo.classList.add('close'); + cloimg.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsSAAALEgHS3X78AAAAG3RFWHRTb2Z0d2FyZQBDZWxzeXMgU3R1ZGlvIFRvb2zBp+F8AAAAxElEQVQ4y82T0REBQRBEX0dAJk4GJwKXgZMBESADIiADJwKXATI4GRBB+1lqKa62+DFV+7E7U6+6e2plm19K/wWQ1AE2QBcobZ9fehVwCb3rWwWShmHwaLsfvW+BAihs71otSJoBc2BuexFBl7anSRlI2gN5OBXQxIpSAB2gCXlcgCzOJGkLkg5ABhyB/B5cqoI1UAb5BbCxPU4CSBqFdda2B1GoE9urVoCkHlCH68N3ZOfzGkNw9dvBZ3Bu+/SHf+GbugG9/4ThhKqF8gAAAABJRU5ErkJggg=='; + clo2.classList.add('close2'); + clo2.textContent = 'delete'; + clo.append(cloimg, clo2); + + img.src = 'data:image/png;base64,' + data.image; + img.title = data.name; + fig.append(clo, img, cap); + + df.appendChild(fig); + } + + ui.saved_poses.innerHTML = ''; + ui.saved_poses.appendChild(df); + } + + function init_ui(type, api) { + const $ = x => document.createElement(x); + + const all_reset = $('button'); + all_reset.innerHTML = '🔄 All Reset'; + all_reset.classList.add('posex_all_reset', 'posex_box'); + + const reset_camera = $('button'); + reset_camera.innerHTML = '🎥 Reset Camera'; + reset_camera.classList.add('posex_reset_camera', 'posex_box'); + + const reset_pose = $('button'); + reset_pose.innerHTML = '🧍 Reset Pose'; + reset_pose.classList.add('posex_reset_pose', 'posex_box'); + + const reset_cont = $('div'); + reset_cont.classList.add('posex_reset_cont'); + reset_cont.append(reset_camera, reset_pose); + + const canvas = $('canvas'); + canvas.width = 512; + canvas.height = 512; + + const camera_marker = $('div'); camera_marker.textContent = '- Camera'; + const fixed_roll_label = $('label'); + const fixed_roll = $('input'); fixed_roll.type = 'checkbox'; fixed_roll.classList.add('posex_fixed_roll', 'posex_camera'); fixed_roll.checked = true; + fixed_roll_label.append(fixed_roll, document.createTextNode('Fixed Roll')); + const body_marker = $('div'); body_marker.textContent = '- Body'; + const add_body = $('button'); add_body.classList.add('posex_add_body', 'posex_body'); add_body.innerHTML = '➕ Add'; + const remove_body = $('button'); remove_body.classList.add('posex_remove_body', 'posex_body'); remove_body.innerHTML = '➖ Remove'; + const canvas_marker = $('div'); canvas_marker.textContent = '- Canvas Size'; + const canvas_width = $('input'); canvas_width.type = 'number'; canvas_width.value = 512; canvas_width.min = 64; canvas_width.classList.add('posex_canvas_width', 'posex_canvas_size'); + const canvas_height = $('input'); canvas_height.type = 'number'; canvas_height.value = 512; canvas_height.min = 64; canvas_height.classList.add('posex_canvas_height', 'posex_canvas_size'); + const bg_marker = $('div'); bg_marker.textContent = '- Background'; + const set_bg = $('label'); set_bg.classList.add('posex_bg'); + const bg_button = $('button'); bg_button.innerHTML = '🖼 Set'; bg_button.onclick = () => bg_input.click(); + const bg_input = $('input'); bg_input.type = 'file'; bg_input.style.display = 'none'; + set_bg.append(bg_button, bg_input); + const reset_bg = $('button'); reset_bg.classList.add('posex_bg'); reset_bg.innerHTML = '❌ Del'; + const bg_cont = $('div'); bg_cont.classList.add('posex_bg_cont'); + bg_cont.append(set_bg, reset_bg); + const joint_marker = $('div'); joint_marker.textContent = '- Joints and Limbs'; + const limb_width_label = $('label'); + const limb_width = $('input'); limb_width.type = 'range'; limb_width.min = 1; limb_width.max = 16; limb_width.value = 4; limb_width.classList.add('posex_joints', 'posex_limb_width'); + limb_width_label.append(limb_width, document.createTextNode('Limb Width')); + const elliptic_limbs_label = $('label'); + const elliptic_limbs = $('input'); elliptic_limbs.type = 'checkbox'; elliptic_limbs.classList.add('posex_joints', 'posex_elliptic_limbs'); elliptic_limbs.checked = true; + elliptic_limbs_label.append(elliptic_limbs, document.createTextNode('Elliptic Limbs')); + const other_marker = $('div'); other_marker.textContent = '- Others'; + const low_fps_label = $('label'); + const low_fps = $('input'); low_fps.type = 'checkbox'; low_fps.classList.add('posex_low_fps', 'posex_others'); low_fps.checked = false; + low_fps_label.append(low_fps, document.createTextNode('Low fps')); + + const setting_cont = $('div'); + setting_cont.classList.add('posex_setting_cont'); + setting_cont.append( + camera_marker, + fixed_roll_label, + body_marker, + add_body, + remove_body, + canvas_marker, + canvas_width, + canvas_height, + bg_marker, + bg_cont, + joint_marker, + limb_width_label, + elliptic_limbs_label, + other_marker, + low_fps_label, + ); + + const canvas_cont = $('div'); + canvas_cont.classList.add('posex_canvas_cont'); + canvas_cont.append( + canvas, + setting_cont, + ); + + const notation = $('p'); + notation.classList.add('posex_notation'); + + const indicator1 = $('div'); + indicator1.classList.add('posex_indicator1'); + + const indicator2 = $('div'); + indicator2.classList.add('posex_indicator2'); + + const copy = $('button'); copy.classList.add('posex_copy', 'posex_misc', 'posex_box'); copy.innerHTML = '📋 Copy to clipboard'; + const save = $('button'); save.classList.add('posex_save', 'posex_misc', 'posex_box'); save.innerHTML = '💾 Download image'; + + const misc_cont = $('div'); + misc_cont.classList.add('posex_misc_cont'); + misc_cont.append( + copy, + save + ); + + const save_pose = $('button'); + save_pose.classList.add('posex_save_pose', 'posex_box'); + save_pose.innerHTML = '💾🧍 Save Pose'; + + const save_pose_callback = async obj => { + await py2js(type, 'savepose', obj); + const json = await py2js(type, 'allposes') + reload_poses(JSON.parse(json), ui); + return { result: '', ok: true }; + }; + + const saved_poses = $('div'); + saved_poses.classList.add('posex_saved_poses'); + + saved_poses.addEventListener('click', async e => { + const get_name = ele => { + while (ele && ele !== document) { + if (ele.dataset && ele.dataset.poseName !== undefined) + return ele.dataset.poseName; + ele = ele.parentNode; + } + return ''; + }; + + let target = e.target; + if (target.tagName === 'IMG') target = target.parentNode; + if (target.classList.contains('close2')) target = target.parentNode; + if (target.tagName === 'FIGURE') { + const name = get_name(target); + if (name.length != 0) { + const json = await py2js(type, 'loadpose', name); + ui.loadPose(JSON.parse(json)); + } + } else if (target.classList.contains('close')) { + const name = get_name(target); + if (name.length != 0) { + await py2js(type, 'delpose', name); + const json = await py2js(type, 'allposes') + reload_poses(JSON.parse(json), ui); + } + } + }, false); + + const ui = { + canvas, + notation, + indicator1, + indicator2, + all_reset, + reset_camera, + reset_pose, + fixed_roll, + add_body, + remove_body, + canvas_width, + canvas_height, + bg: bg_input, + reset_bg, + limb_width, + elliptic_limbs, + low_fps, + save, + copy, + save_pose, + save_pose_callback, + saved_poses, + }; + + const df = document.createDocumentFragment(); + df.append( + all_reset, + reset_cont, + canvas_cont, + indicator2, + indicator1, + notation, + misc_cont, + save_pose, + saved_poses, + ); + + return { ui, df }; + }; + + async function init_canvas( + type, + enabled, + generate_button, + container, + api + ) { + container.classList.add('posex_cont'); + container.innerHTML = ''; + const { ui, df } = init_ui(type, api); + container.appendChild(df); + + ui.container = container; + ui.notify = function (str, type) { if (type === 'error') console.error(str); }; + + if (!posex[`${type}_click`]) { + // Send canvas image to ControlNet when button is clicked. + let force = false; + gradioApp().addEventListener('click', async e => { + if (e.target !== generate_button) return; + + if (!enabled.checked) return; + + if (force) { + force = false; + return; + } + + // hook `generate` button to add canvas data + e.preventDefault(); + e.stopPropagation(); + + const data_url = await ui.getDataURL(); + await js2py(type, 'base64', data_url); + force = true; + generate_button.click(); + }, true); + posex[`${type}_click`] = true; + } + + { + // Load saved poses. + const json = await py2js(type, 'allposes') + reload_poses(JSON.parse(json), ui); + } + + init(ui); + + const animate = init_3d(ui); + + animate(); + + onUiTabChange(() => { + const tabname = get_uiCurrentTabContent().id; + if (type === 't2i') { + if (0 <= tabname.indexOf('txt2img')) { + ui.play(); + } else { + ui.stop(); + } + } else if (type === 'i2i') { + if (0 <= tabname.indexOf('img2img')) { + ui.play(); + } else { + ui.stop(); + } + } else { + ui.stop(); + } + }); + } + + async function init_t2i() { + const app = gradioApp(); + await init_canvas( + 't2i', + app.querySelector('#posex-t2i-enabled input[type=checkbox]'), + app.querySelector('#txt2img_generate'), + Array.from(app.querySelectorAll('#posex-t2i-html')).at(-1), // ! + { + load_all_poses: app.querySelector('#posex-t2i-api-all_pose'), + delete_pose: app.querySelector('#posex-t2i-api-delete_pose'), + } + ); + } + + async function init_i2i() { + const app = gradioApp(); + await init_canvas( + 'i2i', + app.querySelector('#posex-i2i-enabled input[type=checkbox]'), + app.querySelector('#img2img_generate'), + Array.from(app.querySelectorAll('#posex-i2i-html')).at(-1), // ! + { + load_all_poses: app.querySelector('#posex-i2i-api-all_pose'), + delete_pose: app.querySelector('#posex-i2i-api-delete_pose'), + } + ); + } + + if (!globalThis.posex) globalThis.posex = {}; + const posex = globalThis.posex; + posex.init_t2i = init_t2i; + posex.init_i2i = init_i2i; + + posex.script_loaded = true; + document.dispatchEvent(new CustomEvent('posexscriptloaded')); + +})(); diff --git a/posex/javascript/posex-webui.js b/posex/javascript/posex-webui.js new file mode 100644 index 0000000000000000000000000000000000000000..caca72f99de4e4b5e411d8064883f973949cd494 --- /dev/null +++ b/posex/javascript/posex-webui.js @@ -0,0 +1,93 @@ +(function () { + if (!globalThis.posex) globalThis.posex = {}; + const posex = globalThis.posex; + + function load(cont) { + function load_() { + if (posex.script_loading || posex.script_loaded) return; + posex.script_loading = true; + + const scripts = cont.textContent.trim().split('\n'); + const base_path = `/file=${scripts.shift()}/js`; + cont.textContent = ''; + + const df = document.createDocumentFragment(); + for (let src of scripts) { + console.log(`[Posex] loading ${src}`); + const script = document.createElement('script'); + script.async = true; + script.type = 'module'; + script.src = `file=${src}`; + df.appendChild(script); + } + + globalThis.posex.import = async () => { + const THREE = await import(`${base_path}/three.module.js`); + const { TrackballControls } = await import(`${base_path}/TrackballControls.js`); + const { DragControls } = await import(`${base_path}/DragControls.js`); + const { MeshLine, MeshLineMaterial } = await import(`${base_path}/THREE.MeshLine.Module.min.js`); + return { THREE, TrackballControls, DragControls, MeshLine, MeshLineMaterial }; + }; + if (!globalThis.posex.imports) globalThis.posex.imports = {}; + if (!globalThis.posex.imports.three) globalThis.posex.imports.three = async () => await import(`${base_path}/three.module.js`); + if (!globalThis.posex.imports.posex) globalThis.posex.imports.posex = async () => await import(`${base_path}/posex.js`); + cont.appendChild(df); + } + + return posex.script_loaded ? Promise.resolve() : new Promise(resolve => { + document.addEventListener('posexscriptloaded', () => resolve(), false); + load_(); + }); + } + + function lazy(fn, timeout) { + if (timeout === undefined) timeout = 500; + return new Promise(function callback(resolve) { + const result = fn(); + if (result) { + resolve(result); + } else { + setTimeout(() => callback(resolve), timeout); + } + }); + } + + function hook_acc(acc, fn) { + const observer = new MutationObserver(list => { + for (let mut of list) { + if (mut.type === 'childList') { + if (mut.addedNodes.length != 0) { + // closed -> opened + fn(); + } else { + // opened -> closed + // do nothing + } + } + } + }); + observer.observe(acc, { childList: true, attributes: false, subtree: false }); + } + + function launch(type) { + return lazy(() => gradioApp()?.querySelector(`#posex-${type}-accordion`)). + then(acc => hook_acc(acc, async () => { + const cont = Array.from(acc.querySelectorAll(`#posex-${type}-js`)).at(-1); // ! + const enabled = acc.querySelector(`#posex-${type}-enabled input[type=checkbox]`); + await load(cont); + if (enabled.checked) { + await posex[`init_${type}`](); + console.log(`[Posex] ${type} initialized`); + } else { + enabled.addEventListener('change', async () => { + await posex[`init_${type}`](); + console.log(`[Posex] ${type} initialized`); + }, { once: true }); + } + })); + } + + launch('t2i'); + launch('i2i'); + +})(); diff --git a/posex/js/DragControls.js b/posex/js/DragControls.js new file mode 100644 index 0000000000000000000000000000000000000000..6745c5bf41d82d5d82ade3e7f42255c330383dfc --- /dev/null +++ b/posex/js/DragControls.js @@ -0,0 +1,228 @@ +async function _import() { + if (!globalThis.posex || !globalThis.posex.import) { + return await import('three'); + } else { + return await globalThis.posex.imports.three(); + } +} +const { + EventDispatcher, + Matrix4, + Plane, + Raycaster, + Vector2, + Vector3 +} = await _import(); + +const _plane = new Plane(); +const _raycaster = new Raycaster(); + +const _pointer = new Vector2(); +const _offset = new Vector3(); +const _intersection = new Vector3(); +const _worldPosition = new Vector3(); +const _inverseMatrix = new Matrix4(); + +class DragControls extends EventDispatcher { + + constructor( _objects, _camera, _domElement ) { + + super(); + + _domElement.style.touchAction = 'none'; // disable touch scroll + + let _selected = null, _hovered = null; + + const _intersections = []; + + // + + const scope = this; + + function activate() { + + _domElement.addEventListener( 'pointermove', onPointerMove ); + _domElement.addEventListener( 'pointerdown', onPointerDown ); + _domElement.addEventListener( 'pointerup', onPointerCancel ); + _domElement.addEventListener( 'pointerleave', onPointerCancel ); + + } + + function deactivate() { + + _domElement.removeEventListener( 'pointermove', onPointerMove ); + _domElement.removeEventListener( 'pointerdown', onPointerDown ); + _domElement.removeEventListener( 'pointerup', onPointerCancel ); + _domElement.removeEventListener( 'pointerleave', onPointerCancel ); + + _domElement.style.cursor = ''; + + } + + function dispose() { + + deactivate(); + + } + + function getObjects() { + + return _objects; + + } + + function getRaycaster() { + + return _raycaster; + + } + + function onPointerMove( event ) { + + if ( scope.enabled === false ) return; + + updatePointer( event ); + + _raycaster.setFromCamera( _pointer, _camera ); + + if ( _selected ) { + + if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) { + + _selected.position.copy( _intersection.sub( _offset ).applyMatrix4( _inverseMatrix ) ); + + } + + scope.dispatchEvent( { type: 'drag', object: _selected } ); + + return; + + } + + // hover support + + if ( event.pointerType === 'mouse' || event.pointerType === 'pen' ) { + + _intersections.length = 0; + + _raycaster.setFromCamera( _pointer, _camera ); + _raycaster.intersectObjects( _objects, true, _intersections ); + + if ( _intersections.length > 0 ) { + + const object = _intersections[ 0 ].object; + + _plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( object.matrixWorld ) ); + + if ( _hovered !== object && _hovered !== null ) { + + scope.dispatchEvent( { type: 'hoveroff', object: _hovered } ); + + _domElement.style.cursor = 'auto'; + _hovered = null; + + } + + if ( _hovered !== object ) { + + scope.dispatchEvent( { type: 'hoveron', object: object } ); + + _domElement.style.cursor = 'pointer'; + _hovered = object; + + } + + } else { + + if ( _hovered !== null ) { + + scope.dispatchEvent( { type: 'hoveroff', object: _hovered } ); + + _domElement.style.cursor = 'auto'; + _hovered = null; + + } + + } + + } + + } + + function onPointerDown( event ) { + + if ( scope.enabled === false ) return; + + updatePointer( event ); + + _intersections.length = 0; + + _raycaster.setFromCamera( _pointer, _camera ); + _raycaster.intersectObjects( _objects, true, _intersections ); + + if ( _intersections.length > 0 ) { + + _selected = ( scope.transformGroup === true ) ? _objects[ 0 ] : _intersections[ 0 ].object; + + _plane.setFromNormalAndCoplanarPoint( _camera.getWorldDirection( _plane.normal ), _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) ); + + if ( _raycaster.ray.intersectPlane( _plane, _intersection ) ) { + + _inverseMatrix.copy( _selected.parent.matrixWorld ).invert(); + _offset.copy( _intersection ).sub( _worldPosition.setFromMatrixPosition( _selected.matrixWorld ) ); + + } + + _domElement.style.cursor = 'move'; + + scope.dispatchEvent( { type: 'dragstart', object: _selected } ); + + } + + + } + + function onPointerCancel() { + + if ( scope.enabled === false ) return; + + if ( _selected ) { + + scope.dispatchEvent( { type: 'dragend', object: _selected } ); + + _selected = null; + + } + + _domElement.style.cursor = _hovered ? 'pointer' : 'auto'; + + } + + function updatePointer( event ) { + + const rect = _domElement.getBoundingClientRect(); + + _pointer.x = ( event.clientX - rect.left ) / rect.width * 2 - 1; + _pointer.y = - ( event.clientY - rect.top ) / rect.height * 2 + 1; + + } + + activate(); + + // API + + this.enabled = true; + this.transformGroup = false; + + this.activate = activate; + this.deactivate = deactivate; + this.dispose = dispose; + this.getObjects = getObjects; + this.getRaycaster = getRaycaster; + this.onPointerDown = onPointerDown; + + } + +} + +export { DragControls }; diff --git a/posex/js/LICENSE/THREE.MeshLine b/posex/js/LICENSE/THREE.MeshLine new file mode 100644 index 0000000000000000000000000000000000000000..2913a08c822a881da3c1e95a969c65dc48c1f774 --- /dev/null +++ b/posex/js/LICENSE/THREE.MeshLine @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jaume Sanchez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/posex/js/LICENSE/es-module-shims b/posex/js/LICENSE/es-module-shims new file mode 100644 index 0000000000000000000000000000000000000000..a1902579052c1c4d3c0cc1e785f12004b0a57055 --- /dev/null +++ b/posex/js/LICENSE/es-module-shims @@ -0,0 +1,10 @@ +MIT License +----------- + +Copyright (C) 2018-2021 Guy Bedford + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/posex/js/LICENSE/three b/posex/js/LICENSE/three new file mode 100644 index 0000000000000000000000000000000000000000..d07e209686512b9ac93d7df5481a4a6f622093e7 --- /dev/null +++ b/posex/js/LICENSE/three @@ -0,0 +1,21 @@ +The MIT License + +Copyright © 2010-2023 three.js authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/posex/js/THREE.MeshLine.Module.min.js b/posex/js/THREE.MeshLine.Module.min.js new file mode 100644 index 0000000000000000000000000000000000000000..5d1ff114f476cc7795eca28197965e155781abe0 --- /dev/null +++ b/posex/js/THREE.MeshLine.Module.min.js @@ -0,0 +1,15 @@ +/** + * Minified by jsDelivr using Terser v5.15.1. + * Original file: /npm/three.meshline.module@1.0.0/src/THREE.MeshLine.Module.js + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +async function _import() { + if (!globalThis.posex || !globalThis.posex.import) { + return await import('three'); + } else { + return await globalThis.posex.imports.three(); + } +} +const THREE=await _import();class MeshLine extends THREE.BufferGeometry{constructor(){super(),this.isMeshLine=!0,this.type="MeshLine",this.positions=[],this.previous=[],this.next=[],this.side=[],this.width=[],this.indices_array=[],this.uvs=[],this.counters=[],this._points=[],this._geom=null,this.widthCallback=null,this.matrixWorld=new THREE.Matrix4,Object.defineProperties(this,{geometry:{enumerable:!0,get:function(){return this}},geom:{enumerable:!0,get:function(){return this._geom},set:function(t){this.setGeometry(t,this.widthCallback)}},points:{enumerable:!0,get:function(){return this._points},set:function(t){this.setPoints(t,this.widthCallback)}}})}}function MeshLineRaycast(t,e){var i=new THREE.Matrix4,s=new THREE.Ray,r=new THREE.Sphere,a=new THREE.Vector3,n=this.geometry;if(n.boundingSphere||n.computeBoundingSphere(),r.copy(n.boundingSphere),r.applyMatrix4(this.matrixWorld),!1!==t.ray.intersectSphere(r,a)){i.copy(this.matrixWorld).invert(),s.copy(t.ray).applyMatrix4(i);var o=new THREE.Vector3,u=new THREE.Vector3,h=new THREE.Vector3,l=this instanceof THREE.LineSegments?2:1,p=n.index,c=n.attributes;if(null!==p)for(var f=p.array,v=c.position.array,d=c.width.array,y=0,m=f.length-1;yA)){a.applyMatrix4(this.matrixWorld);var M=t.ray.origin.distanceTo(a);Mt.far||(e.push({distance:M,point:h.clone().applyMatrix4(this.matrixWorld),index:y,face:null,faceIndex:null,object:this}),y=m)}}}}function memcpy(t,e,i,s,r){var a;if(t=t.subarray||t.slice?t:t.buffer,i=i.subarray||i.slice?i:i.buffer,t=e?t.subarray?t.subarray(e,r&&e+r):t.slice(e,r&&e+r):t,i.set)i.set(t,s);else for(a=0;a0&&(e=this.copyV3(s),this.next.push(e[0],e[1],e[2]),this.next.push(e[0],e[1],e[2]))}e=this.compareV3(i-1,0)?this.copyV3(1):this.copyV3(i-1),this.next.push(e[0],e[1],e[2]),this.next.push(e[0],e[1],e[2]),this._attributes&&this._attributes.position.count===this.positions.length?(this._attributes.position.copyArray(new Float32Array(this.positions)),this._attributes.position.needsUpdate=!0,this._attributes.previous.copyArray(new Float32Array(this.previous)),this._attributes.previous.needsUpdate=!0,this._attributes.next.copyArray(new Float32Array(this.next)),this._attributes.next.needsUpdate=!0,this._attributes.side.copyArray(new Float32Array(this.side)),this._attributes.side.needsUpdate=!0,this._attributes.width.copyArray(new Float32Array(this.width)),this._attributes.width.needsUpdate=!0,this._attributes.uv.copyArray(new Float32Array(this.uvs)),this._attributes.uv.needsUpdate=!0,this._attributes.index.copyArray(new Uint16Array(this.indices_array)),this._attributes.index.needsUpdate=!0):this._attributes={position:new THREE.BufferAttribute(new Float32Array(this.positions),3),previous:new THREE.BufferAttribute(new Float32Array(this.previous),3),next:new THREE.BufferAttribute(new Float32Array(this.next),3),side:new THREE.BufferAttribute(new Float32Array(this.side),1),width:new THREE.BufferAttribute(new Float32Array(this.width),1),uv:new THREE.BufferAttribute(new Float32Array(this.uvs),2),index:new THREE.BufferAttribute(new Uint16Array(this.indices_array),1),counters:new THREE.BufferAttribute(new Float32Array(this.counters),1)},this.setAttribute("position",this._attributes.position),this.setAttribute("previous",this._attributes.previous),this.setAttribute("next",this._attributes.next),this.setAttribute("side",this._attributes.side),this.setAttribute("width",this._attributes.width),this.setAttribute("uv",this._attributes.uv),this.setAttribute("counters",this._attributes.counters),this.setIndex(this._attributes.index),this.computeBoundingSphere(),this.computeBoundingBox()},MeshLine.prototype.advance=function(t){var e=this._attributes.position.array,i=this._attributes.previous.array,s=this._attributes.next.array,r=e.length;memcpy(e,0,i,0,r),memcpy(e,6,e,0,r-6),e[r-6]=t.x,e[r-5]=t.y,e[r-4]=t.z,e[r-3]=t.x,e[r-2]=t.y,e[r-1]=t.z,memcpy(e,6,s,0,r-6),s[r-6]=t.x,s[r-5]=t.y,s[r-4]=t.z,s[r-3]=t.x,s[r-2]=t.y,s[r-1]=t.z,this._attributes.position.needsUpdate=!0,this._attributes.previous.needsUpdate=!0,this._attributes.next.needsUpdate=!0},THREE.ShaderChunk.meshline_vert=["",THREE.ShaderChunk.logdepthbuf_pars_vertex,THREE.ShaderChunk.fog_pars_vertex,"","attribute vec3 previous;","attribute vec3 next;","attribute float side;","attribute float width;","attribute float counters;","","uniform vec2 resolution;","uniform float lineWidth;","uniform vec3 color;","uniform float opacity;","uniform float sizeAttenuation;","","varying vec2 vUV;","varying vec4 vColor;","varying float vCounters;","","vec2 fix( vec4 i, float aspect ) {",""," vec2 res = i.xy / i.w;"," res.x *= aspect;","\t vCounters = counters;"," return res;","","}","","void main() {",""," float aspect = resolution.x / resolution.y;",""," vColor = vec4( color, opacity );"," vUV = uv;",""," mat4 m = projectionMatrix * modelViewMatrix;"," vec4 finalPosition = m * vec4( position, 1.0 );"," vec4 prevPos = m * vec4( previous, 1.0 );"," vec4 nextPos = m * vec4( next, 1.0 );",""," vec2 currentP = fix( finalPosition, aspect );"," vec2 prevP = fix( prevPos, aspect );"," vec2 nextP = fix( nextPos, aspect );",""," float w = lineWidth * width;",""," vec2 dir;"," if( nextP == currentP ) dir = normalize( currentP - prevP );"," else if( prevP == currentP ) dir = normalize( nextP - currentP );"," else {"," vec2 dir1 = normalize( currentP - prevP );"," vec2 dir2 = normalize( nextP - currentP );"," dir = normalize( dir1 + dir2 );",""," vec2 perp = vec2( -dir1.y, dir1.x );"," vec2 miter = vec2( -dir.y, dir.x );"," //w = clamp( w / dot( miter, perp ), 0., 4. * lineWidth * width );",""," }",""," //vec2 normal = ( cross( vec3( dir, 0. ), vec3( 0., 0., 1. ) ) ).xy;"," vec4 normal = vec4( -dir.y, dir.x, 0., 1. );"," normal.xy *= .5 * w;"," normal *= projectionMatrix;"," if( sizeAttenuation == 0. ) {"," normal.xy *= finalPosition.w;"," normal.xy /= ( vec4( resolution, 0., 1. ) * projectionMatrix ).xy;"," }",""," finalPosition.xy += normal.xy * side;",""," gl_Position = finalPosition;","",THREE.ShaderChunk.logdepthbuf_vertex,THREE.ShaderChunk.fog_vertex&&" vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",THREE.ShaderChunk.fog_vertex,"}"].join("\n"),THREE.ShaderChunk.meshline_frag=["",THREE.ShaderChunk.fog_pars_fragment,THREE.ShaderChunk.logdepthbuf_pars_fragment,"","uniform sampler2D map;","uniform sampler2D alphaMap;","uniform float useMap;","uniform float useAlphaMap;","uniform float useDash;","uniform float dashArray;","uniform float dashOffset;","uniform float dashRatio;","uniform float visibility;","uniform float alphaTest;","uniform vec2 repeat;","","varying vec2 vUV;","varying vec4 vColor;","varying float vCounters;","","void main() {","",THREE.ShaderChunk.logdepthbuf_fragment,""," vec4 c = vColor;"," if( useMap == 1. ) c *= texture2D( map, vUV * repeat );"," if( useAlphaMap == 1. ) c.a *= texture2D( alphaMap, vUV * repeat ).a;"," if( c.a < alphaTest ) discard;"," if( useDash == 1. ){"," c.a *= ceil(mod(vCounters + dashOffset, dashArray) - (dashArray * dashRatio));"," }"," gl_FragColor = c;"," gl_FragColor.a *= step(vCounters, visibility);","",THREE.ShaderChunk.fog_fragment,"}"].join("\n");class MeshLineMaterial extends THREE.ShaderMaterial{constructor(t){super({uniforms:Object.assign({},THREE.UniformsLib.fog,{lineWidth:{value:1},map:{value:null},useMap:{value:0},alphaMap:{value:null},useAlphaMap:{value:0},color:{value:new THREE.Color(16777215)},opacity:{value:1},resolution:{value:new THREE.Vector2(1,1)},sizeAttenuation:{value:1},dashArray:{value:0},dashOffset:{value:0},dashRatio:{value:.5},useDash:{value:0},visibility:{value:1},alphaTest:{value:0},repeat:{value:new THREE.Vector2(1,1)}}),vertexShader:THREE.ShaderChunk.meshline_vert,fragmentShader:THREE.ShaderChunk.meshline_frag}),this.isMeshLineMaterial=!0,this.type="MeshLineMaterial",Object.defineProperties(this,{lineWidth:{enumerable:!0,get:function(){return this.uniforms.lineWidth.value},set:function(t){this.uniforms.lineWidth.value=t}},map:{enumerable:!0,get:function(){return this.uniforms.map.value},set:function(t){this.uniforms.map.value=t}},useMap:{enumerable:!0,get:function(){return this.uniforms.useMap.value},set:function(t){this.uniforms.useMap.value=t}},alphaMap:{enumerable:!0,get:function(){return this.uniforms.alphaMap.value},set:function(t){this.uniforms.alphaMap.value=t}},useAlphaMap:{enumerable:!0,get:function(){return this.uniforms.useAlphaMap.value},set:function(t){this.uniforms.useAlphaMap.value=t}},color:{enumerable:!0,get:function(){return this.uniforms.color.value},set:function(t){this.uniforms.color.value=t}},opacity:{enumerable:!0,get:function(){return this.uniforms.opacity.value},set:function(t){this.uniforms.opacity.value=t}},resolution:{enumerable:!0,get:function(){return this.uniforms.resolution.value},set:function(t){this.uniforms.resolution.value.copy(t)}},sizeAttenuation:{enumerable:!0,get:function(){return this.uniforms.sizeAttenuation.value},set:function(t){this.uniforms.sizeAttenuation.value=t}},dashArray:{enumerable:!0,get:function(){return this.uniforms.dashArray.value},set:function(t){this.uniforms.dashArray.value=t,this.useDash=0!==t?1:0}},dashOffset:{enumerable:!0,get:function(){return this.uniforms.dashOffset.value},set:function(t){this.uniforms.dashOffset.value=t}},dashRatio:{enumerable:!0,get:function(){return this.uniforms.dashRatio.value},set:function(t){this.uniforms.dashRatio.value=t}},useDash:{enumerable:!0,get:function(){return this.uniforms.useDash.value},set:function(t){this.uniforms.useDash.value=t}},visibility:{enumerable:!0,get:function(){return this.uniforms.visibility.value},set:function(t){this.uniforms.visibility.value=t}},alphaTest:{enumerable:!0,get:function(){return this.uniforms.alphaTest.value},set:function(t){this.uniforms.alphaTest.value=t}},repeat:{enumerable:!0,get:function(){return this.uniforms.repeat.value},set:function(t){this.uniforms.repeat.value.copy(t)}}}),this.setValues(t)}}MeshLineMaterial.prototype.copy=function(t){return THREE.ShaderMaterial.prototype.copy.call(this,t),this.lineWidth=t.lineWidth,this.map=t.map,this.useMap=t.useMap,this.alphaMap=t.alphaMap,this.useAlphaMap=t.useAlphaMap,this.color.copy(t.color),this.opacity=t.opacity,this.resolution.copy(t.resolution),this.sizeAttenuation=t.sizeAttenuation,this.dashArray.copy(t.dashArray),this.dashOffset.copy(t.dashOffset),this.dashRatio.copy(t.dashRatio),this.useDash=t.useDash,this.visibility=t.visibility,this.alphaTest=t.alphaTest,this.repeat.copy(t.repeat),this};export{MeshLine,MeshLineMaterial,MeshLineRaycast}; +//# sourceMappingURL=/sm/a10f0fbff9ef9e01c8548236b6b20610cf5d5cba1f631d8ebab539add9c04974.map \ No newline at end of file diff --git a/posex/js/TrackballControls.js b/posex/js/TrackballControls.js new file mode 100644 index 0000000000000000000000000000000000000000..5c402f5848f51e2492a6321965b545404b4c4563 --- /dev/null +++ b/posex/js/TrackballControls.js @@ -0,0 +1,821 @@ +async function _import() { + if (!globalThis.posex || !globalThis.posex.import) { + return await import('three'); + } else { + return await globalThis.posex.imports.three(); + } +} +const { + EventDispatcher, + MOUSE, + Quaternion, + Vector2, + Vector3 +} = await _import(); + +const _changeEvent = { type: 'change' }; +const _startEvent = { type: 'start' }; +const _endEvent = { type: 'end' }; + +class TrackballControls extends EventDispatcher { + + constructor( object, domElement ) { + + super(); + + const scope = this; + const STATE = { NONE: - 1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM_PAN: 4 }; + + this.object = object; + this.domElement = domElement; + this.domElement.style.touchAction = 'none'; // disable touch scroll + + // API + + this.enabled = true; + + this.screen = { left: 0, top: 0, width: 0, height: 0 }; + + this.rotateSpeed = 1.0; + this.zoomSpeed = 1.2; + this.panSpeed = 0.3; + + this.noRotate = false; + this.noZoom = false; + this.noPan = false; + + this.staticMoving = false; + this.dynamicDampingFactor = 0.2; + + this.minDistance = 0; + this.maxDistance = Infinity; + + this.keys = [ 'KeyA' /*A*/, 'KeyS' /*S*/, 'KeyD' /*D*/ ]; + + this.mouseButtons = { LEFT: MOUSE.ROTATE, MIDDLE: MOUSE.DOLLY, RIGHT: MOUSE.PAN }; + + // internals + + this.target = new Vector3(); + + const EPS = 0.000001; + + const lastPosition = new Vector3(); + let lastZoom = 1; + + let _state = STATE.NONE, + _keyState = STATE.NONE, + + _touchZoomDistanceStart = 0, + _touchZoomDistanceEnd = 0, + + _lastAngle = 0; + + const _eye = new Vector3(), + + _movePrev = new Vector2(), + _moveCurr = new Vector2(), + + _lastAxis = new Vector3(), + + _zoomStart = new Vector2(), + _zoomEnd = new Vector2(), + + _panStart = new Vector2(), + _panEnd = new Vector2(), + + _pointers = [], + _pointerPositions = {}; + + // for reset + + this.target0 = this.target.clone(); + this.position0 = this.object.position.clone(); + this.up0 = this.object.up.clone(); + this.zoom0 = this.object.zoom; + + // methods + + this.handleResize = function () { + + const box = scope.domElement.getBoundingClientRect(); + // adjustments come from similar code in the jquery offset() function + const d = scope.domElement.ownerDocument.documentElement; + scope.screen.left = box.left + window.pageXOffset - d.clientLeft; + scope.screen.top = box.top + window.pageYOffset - d.clientTop; + scope.screen.width = box.width; + scope.screen.height = box.height; + + }; + + const getMouseOnScreen = ( function () { + + const vector = new Vector2(); + + return function getMouseOnScreen( pageX, pageY ) { + + vector.set( + ( pageX - scope.screen.left ) / scope.screen.width, + ( pageY - scope.screen.top ) / scope.screen.height + ); + + return vector; + + }; + + }() ); + + const getMouseOnCircle = ( function () { + + const vector = new Vector2(); + + return function getMouseOnCircle( pageX, pageY ) { + + vector.set( + ( ( pageX - scope.screen.width * 0.5 - scope.screen.left ) / ( scope.screen.width * 0.5 ) ), + ( ( scope.screen.height + 2 * ( scope.screen.top - pageY ) ) / scope.screen.width ) // screen.width intentional + ); + + return vector; + + }; + + }() ); + + this.rotateCamera = ( function () { + + const axis = new Vector3(), + quaternion = new Quaternion(), + eyeDirection = new Vector3(), + objectUpDirection = new Vector3(), + objectSidewaysDirection = new Vector3(), + moveDirection = new Vector3(); + + return function rotateCamera() { + + moveDirection.set( _moveCurr.x - _movePrev.x, _moveCurr.y - _movePrev.y, 0 ); + let angle = moveDirection.length(); + + if ( angle ) { + + _eye.copy( scope.object.position ).sub( scope.target ); + + eyeDirection.copy( _eye ).normalize(); + objectUpDirection.copy( scope.object.up ).normalize(); + objectSidewaysDirection.crossVectors( objectUpDirection, eyeDirection ).normalize(); + + objectUpDirection.setLength( _moveCurr.y - _movePrev.y ); + objectSidewaysDirection.setLength( _moveCurr.x - _movePrev.x ); + + moveDirection.copy( objectUpDirection.add( objectSidewaysDirection ) ); + + axis.crossVectors( moveDirection, _eye ).normalize(); + + angle *= scope.rotateSpeed; + quaternion.setFromAxisAngle( axis, angle ); + + _eye.applyQuaternion( quaternion ); + scope.object.up.applyQuaternion( quaternion ); + + _lastAxis.copy( axis ); + _lastAngle = angle; + + } else if ( ! scope.staticMoving && _lastAngle ) { + + _lastAngle *= Math.sqrt( 1.0 - scope.dynamicDampingFactor ); + _eye.copy( scope.object.position ).sub( scope.target ); + quaternion.setFromAxisAngle( _lastAxis, _lastAngle ); + _eye.applyQuaternion( quaternion ); + scope.object.up.applyQuaternion( quaternion ); + + } + + _movePrev.copy( _moveCurr ); + + }; + + }() ); + + + this.zoomCamera = function () { + + let factor; + + if ( _state === STATE.TOUCH_ZOOM_PAN ) { + + factor = _touchZoomDistanceStart / _touchZoomDistanceEnd; + _touchZoomDistanceStart = _touchZoomDistanceEnd; + + if ( scope.object.isPerspectiveCamera ) { + + _eye.multiplyScalar( factor ); + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.zoom /= factor; + scope.object.updateProjectionMatrix(); + + } else { + + console.warn( 'THREE.TrackballControls: Unsupported camera type' ); + + } + + } else { + + factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * scope.zoomSpeed; + + if ( factor !== 1.0 && factor > 0.0 ) { + + if ( scope.object.isPerspectiveCamera ) { + + _eye.multiplyScalar( factor ); + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.zoom /= factor; + scope.object.updateProjectionMatrix(); + + } else { + + console.warn( 'THREE.TrackballControls: Unsupported camera type' ); + + } + + } + + if ( scope.staticMoving ) { + + _zoomStart.copy( _zoomEnd ); + + } else { + + _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor; + + } + + } + + }; + + this.panCamera = ( function () { + + const mouseChange = new Vector2(), + objectUp = new Vector3(), + pan = new Vector3(); + + return function panCamera() { + + mouseChange.copy( _panEnd ).sub( _panStart ); + + if ( mouseChange.lengthSq() ) { + + if ( scope.object.isOrthographicCamera ) { + + const scale_x = ( scope.object.right - scope.object.left ) / scope.object.zoom / scope.domElement.clientWidth; + const scale_y = ( scope.object.top - scope.object.bottom ) / scope.object.zoom / scope.domElement.clientWidth; + + mouseChange.x *= scale_x; + mouseChange.y *= scale_y; + + } + + mouseChange.multiplyScalar( _eye.length() * scope.panSpeed ); + + pan.copy( _eye ).cross( scope.object.up ).setLength( mouseChange.x ); + pan.add( objectUp.copy( scope.object.up ).setLength( mouseChange.y ) ); + + scope.object.position.add( pan ); + scope.target.add( pan ); + + if ( scope.staticMoving ) { + + _panStart.copy( _panEnd ); + + } else { + + _panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( scope.dynamicDampingFactor ) ); + + } + + } + + }; + + }() ); + + this.checkDistances = function () { + + if ( ! scope.noZoom || ! scope.noPan ) { + + if ( _eye.lengthSq() > scope.maxDistance * scope.maxDistance ) { + + scope.object.position.addVectors( scope.target, _eye.setLength( scope.maxDistance ) ); + _zoomStart.copy( _zoomEnd ); + + } + + if ( _eye.lengthSq() < scope.minDistance * scope.minDistance ) { + + scope.object.position.addVectors( scope.target, _eye.setLength( scope.minDistance ) ); + _zoomStart.copy( _zoomEnd ); + + } + + } + + }; + + this.update = function () { + + _eye.subVectors( scope.object.position, scope.target ); + + if ( ! scope.noRotate ) { + + scope.rotateCamera(); + + } + + if ( ! scope.noZoom ) { + + scope.zoomCamera(); + + } + + if ( ! scope.noPan ) { + + scope.panCamera(); + + } + + scope.object.position.addVectors( scope.target, _eye ); + + if ( scope.object.isPerspectiveCamera ) { + + scope.checkDistances(); + + scope.object.lookAt( scope.target ); + + if ( lastPosition.distanceToSquared( scope.object.position ) > EPS ) { + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + + } + + } else if ( scope.object.isOrthographicCamera ) { + + scope.object.lookAt( scope.target ); + + if ( lastPosition.distanceToSquared( scope.object.position ) > EPS || lastZoom !== scope.object.zoom ) { + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + lastZoom = scope.object.zoom; + + } + + } else { + + console.warn( 'THREE.TrackballControls: Unsupported camera type' ); + + } + + }; + + this.reset = function () { + + _state = STATE.NONE; + _keyState = STATE.NONE; + + scope.target.copy( scope.target0 ); + scope.object.position.copy( scope.position0 ); + scope.object.up.copy( scope.up0 ); + scope.object.zoom = scope.zoom0; + + scope.object.updateProjectionMatrix(); + + _eye.subVectors( scope.object.position, scope.target ); + + scope.object.lookAt( scope.target ); + + scope.dispatchEvent( _changeEvent ); + + lastPosition.copy( scope.object.position ); + lastZoom = scope.object.zoom; + + }; + + // listeners + + function onPointerDown( event ) { + + if ( scope.enabled === false ) return; + + if ( _pointers.length === 0 ) { + + scope.domElement.setPointerCapture( event.pointerId ); + + scope.domElement.addEventListener( 'pointermove', onPointerMove ); + scope.domElement.addEventListener( 'pointerup', onPointerUp ); + + } + + // + + addPointer( event ); + + if ( event.pointerType === 'touch' ) { + + onTouchStart( event ); + + } else { + + onMouseDown( event ); + + } + + } + + function onPointerMove( event ) { + + if ( scope.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + onTouchMove( event ); + + } else { + + onMouseMove( event ); + + } + + } + + function onPointerUp( event ) { + + if ( scope.enabled === false ) return; + + if ( event.pointerType === 'touch' ) { + + onTouchEnd( event ); + + } else { + + onMouseUp(); + + } + + // + + removePointer( event ); + + if ( _pointers.length === 0 ) { + + scope.domElement.releasePointerCapture( event.pointerId ); + + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); + + } + + + } + + function onPointerCancel( event ) { + + removePointer( event ); + + } + + function keydown( event ) { + + if ( scope.enabled === false ) return; + + window.removeEventListener( 'keydown', keydown ); + + if ( _keyState !== STATE.NONE ) { + + return; + + } else if ( event.code === scope.keys[ STATE.ROTATE ] && ! scope.noRotate ) { + + _keyState = STATE.ROTATE; + + } else if ( event.code === scope.keys[ STATE.ZOOM ] && ! scope.noZoom ) { + + _keyState = STATE.ZOOM; + + } else if ( event.code === scope.keys[ STATE.PAN ] && ! scope.noPan ) { + + _keyState = STATE.PAN; + + } + + } + + function keyup() { + + if ( scope.enabled === false ) return; + + _keyState = STATE.NONE; + + window.addEventListener( 'keydown', keydown ); + + } + + function onMouseDown( event ) { + + if ( _state === STATE.NONE ) { + + switch ( event.button ) { + + case scope.mouseButtons.LEFT: + _state = STATE.ROTATE; + break; + + case scope.mouseButtons.MIDDLE: + _state = STATE.ZOOM; + break; + + case scope.mouseButtons.RIGHT: + _state = STATE.PAN; + break; + + } + + } + + const state = ( _keyState !== STATE.NONE ) ? _keyState : _state; + + if ( state === STATE.ROTATE && ! scope.noRotate ) { + + _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); + _movePrev.copy( _moveCurr ); + + } else if ( state === STATE.ZOOM && ! scope.noZoom ) { + + _zoomStart.copy( getMouseOnScreen( event.pageX, event.pageY ) ); + _zoomEnd.copy( _zoomStart ); + + } else if ( state === STATE.PAN && ! scope.noPan ) { + + _panStart.copy( getMouseOnScreen( event.pageX, event.pageY ) ); + _panEnd.copy( _panStart ); + + } + + scope.dispatchEvent( _startEvent ); + + } + + function onMouseMove( event ) { + + const state = ( _keyState !== STATE.NONE ) ? _keyState : _state; + + if ( state === STATE.ROTATE && ! scope.noRotate ) { + + _movePrev.copy( _moveCurr ); + _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); + + } else if ( state === STATE.ZOOM && ! scope.noZoom ) { + + _zoomEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) ); + + } else if ( state === STATE.PAN && ! scope.noPan ) { + + _panEnd.copy( getMouseOnScreen( event.pageX, event.pageY ) ); + + } + + } + + function onMouseUp() { + + _state = STATE.NONE; + + scope.dispatchEvent( _endEvent ); + + } + + function onMouseWheel( event ) { + + if ( scope.enabled === false ) return; + + if ( scope.noZoom === true ) return; + + event.preventDefault(); + + switch ( event.deltaMode ) { + + case 2: + // Zoom in pages + _zoomStart.y -= event.deltaY * 0.025; + break; + + case 1: + // Zoom in lines + _zoomStart.y -= event.deltaY * 0.01; + break; + + default: + // undefined, 0, assume pixels + _zoomStart.y -= event.deltaY * 0.00025; + break; + + } + + scope.dispatchEvent( _startEvent ); + scope.dispatchEvent( _endEvent ); + + } + + function onTouchStart( event ) { + + trackPointer( event ); + + switch ( _pointers.length ) { + + case 1: + _state = STATE.TOUCH_ROTATE; + _moveCurr.copy( getMouseOnCircle( _pointers[ 0 ].pageX, _pointers[ 0 ].pageY ) ); + _movePrev.copy( _moveCurr ); + break; + + default: // 2 or more + _state = STATE.TOUCH_ZOOM_PAN; + const dx = _pointers[ 0 ].pageX - _pointers[ 1 ].pageX; + const dy = _pointers[ 0 ].pageY - _pointers[ 1 ].pageY; + _touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy ); + + const x = ( _pointers[ 0 ].pageX + _pointers[ 1 ].pageX ) / 2; + const y = ( _pointers[ 0 ].pageY + _pointers[ 1 ].pageY ) / 2; + _panStart.copy( getMouseOnScreen( x, y ) ); + _panEnd.copy( _panStart ); + break; + + } + + scope.dispatchEvent( _startEvent ); + + } + + function onTouchMove( event ) { + + trackPointer( event ); + + switch ( _pointers.length ) { + + case 1: + _movePrev.copy( _moveCurr ); + _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); + break; + + default: // 2 or more + + const position = getSecondPointerPosition( event ); + + const dx = event.pageX - position.x; + const dy = event.pageY - position.y; + _touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy ); + + const x = ( event.pageX + position.x ) / 2; + const y = ( event.pageY + position.y ) / 2; + _panEnd.copy( getMouseOnScreen( x, y ) ); + break; + + } + + } + + function onTouchEnd( event ) { + + switch ( _pointers.length ) { + + case 0: + _state = STATE.NONE; + break; + + case 1: + _state = STATE.TOUCH_ROTATE; + _moveCurr.copy( getMouseOnCircle( event.pageX, event.pageY ) ); + _movePrev.copy( _moveCurr ); + break; + + case 2: + _state = STATE.TOUCH_ZOOM_PAN; + + for ( let i = 0; i < _pointers.length; i ++ ) { + + if ( _pointers[ i ].pointerId !== event.pointerId ) { + + const position = _pointerPositions[ _pointers[ i ].pointerId ]; + _moveCurr.copy( getMouseOnCircle( position.x, position.y ) ); + _movePrev.copy( _moveCurr ); + break; + + } + + } + + break; + + } + + scope.dispatchEvent( _endEvent ); + + } + + function contextmenu( event ) { + + if ( scope.enabled === false ) return; + + event.preventDefault(); + + } + + function addPointer( event ) { + + _pointers.push( event ); + + } + + function removePointer( event ) { + + delete _pointerPositions[ event.pointerId ]; + + for ( let i = 0; i < _pointers.length; i ++ ) { + + if ( _pointers[ i ].pointerId == event.pointerId ) { + + _pointers.splice( i, 1 ); + return; + + } + + } + + } + + function trackPointer( event ) { + + let position = _pointerPositions[ event.pointerId ]; + + if ( position === undefined ) { + + position = new Vector2(); + _pointerPositions[ event.pointerId ] = position; + + } + + position.set( event.pageX, event.pageY ); + + } + + function getSecondPointerPosition( event ) { + + const pointer = ( event.pointerId === _pointers[ 0 ].pointerId ) ? _pointers[ 1 ] : _pointers[ 0 ]; + + return _pointerPositions[ pointer.pointerId ]; + + } + + this.dispose = function () { + + scope.domElement.removeEventListener( 'contextmenu', contextmenu ); + + scope.domElement.removeEventListener( 'pointerdown', onPointerDown ); + scope.domElement.removeEventListener( 'pointercancel', onPointerCancel ); + scope.domElement.removeEventListener( 'wheel', onMouseWheel ); + + scope.domElement.removeEventListener( 'pointermove', onPointerMove ); + scope.domElement.removeEventListener( 'pointerup', onPointerUp ); + + window.removeEventListener( 'keydown', keydown ); + window.removeEventListener( 'keyup', keyup ); + + }; + + this.domElement.addEventListener( 'contextmenu', contextmenu ); + + this.domElement.addEventListener( 'pointerdown', onPointerDown ); + this.domElement.addEventListener( 'pointercancel', onPointerCancel ); + this.domElement.addEventListener( 'wheel', onMouseWheel, { passive: false } ); + + + window.addEventListener( 'keydown', keydown ); + window.addEventListener( 'keyup', keyup ); + + this.handleResize(); + + // force an update at start + this.update(); + + } + +} + +export { TrackballControls }; diff --git a/posex/js/app.js b/posex/js/app.js new file mode 100644 index 0000000000000000000000000000000000000000..20a0dd0aac57627b9181795b31bac31ccdce385e --- /dev/null +++ b/posex/js/app.js @@ -0,0 +1,145 @@ +const POSES = new Map(); + +function notify(str, type) { + if (type === undefined) type = 'success'; + + switch (type) { + case 'success': console.log(str); break; + case 'info': console.log(str); break; + case 'warn': console.warn(str); break; + case 'error': console.error(str); break; + } + + const p = document.createElement('p'); + p.textContent = str; + p.classList.add('item', type); + const cont = document.querySelector('#notifications'); + cont.appendChild(p); + setTimeout(() => cont.removeChild(p), 3000); +} + +async function save_pose(obj) { + const res = await fetch('/pose/save', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(obj), + }); + const result = await res.json(); + if (result.ok) reload_poses(); + return result; +} + +async function delete_pose(name) { + const res = await fetch('/pose/delete', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name }), + }); + const result = await res.json(); + notify(result.result, result.ok ? 'success' : 'error'); + if (result.ok) reload_poses(); + return result; +} + +async function reload_poses() { + POSES.clear(); + + const res = await fetch('/pose/all'); + const cont = document.querySelector('#saved_poses'); + cont.innerHTML = ''; + const df = document.createDocumentFragment(); + for (let data of await res.json()) { + POSES.set(data.name, data); + + const fig = document.createElement('figure') + const img = document.createElement('img'); + const cap = document.createElement('figcaption'); + const clo = document.createElement('div'); + const clo2 = document.createElement('span'); + fig.dataset.poseName = data.name; + cap.textContent = data.name; + clo.textContent = 'x'; + clo.classList.add('close'); + clo2.classList.add('close2'); + clo2.textContent = 'delete'; + clo.appendChild(clo2); + + img.src = 'data:image/png;base64,' + data.image; + img.title = data.name; + fig.append(clo, img, cap); + + df.appendChild(fig); + } + cont.appendChild(df); +} + +document.addEventListener('DOMContentLoaded', async () => { + + const ui = { + container: document.querySelector('#cont'), + canvas: document.querySelector('#main_canvas'), + notation: document.querySelector('#notation'), + indicator1: document.querySelector('#body_indicator1'), + indicator2: document.querySelector('#body_indicator2'), + all_reset: document.querySelector('#all_reset'), + reset_camera: document.querySelector('#reset_camera'), + reset_pose: document.querySelector('#reset_pose'), + fixed_roll: document.querySelector('#fixed_roll'), + add_body: document.querySelector('#add_body'), + remove_body: document.querySelector('#remove_body'), + canvas_width: document.querySelector('#canvas_width'), + canvas_height: document.querySelector('#canvas_height'), + bg: document.querySelector('#bg_file'), + reset_bg: document.querySelector('#reset_bg'), + elliptic_limbs: document.querySelector('#elliptic_limbs'), + //joint_radius: document.querySelector('#joint_radius'), + limb_width: document.querySelector('#limb_width'), + low_fps: document.querySelector('#low_fps'), + save: document.querySelector('#save_button'), + copy: document.querySelector('#copy_button'), + save_pose: document.querySelector('#save_pose'), + save_pose_callback: save_pose, + notify: notify, + }; + + document.addEventListener('poseload', e => { + const obj = POSES.get(e.detail.name); + if (obj) ui.loadPose(obj); + }, false); + + const { init, init_3d } = await import('posex'); + + init(ui); + const animate = init_3d(ui); + animate(); + + await reload_poses(); + +}, false); + +document.addEventListener('DOMContentLoaded', () => { + const get_name = ele => { + while (ele && ele !== document) { + if (ele.dataset && ele.dataset.poseName !== undefined) + return ele.dataset.poseName; + ele = ele.parentNode; + } + return ''; + }; + + document.querySelector('#saved_poses').addEventListener('click', e => { + let target = e.target; + if (target.tagName === 'IMG') target = target.parentNode; + if (target.classList.contains('close2')) target = target.parentNode; + if (target.tagName === 'FIGURE') { + const name = get_name(target); + const ev = new CustomEvent('poseload', { bubbles: true, detail: { name } }); + target.dispatchEvent(ev); + } else if (target.classList.contains('close')) { + const name = get_name(target); + if (name.length != 0) { + delete_pose(name); + } + } + }, false); +}, false); diff --git a/posex/js/es-module-shims.js b/posex/js/es-module-shims.js new file mode 100644 index 0000000000000000000000000000000000000000..14a7bae5f6711b287b46a2454e2818bdcfead327 --- /dev/null +++ b/posex/js/es-module-shims.js @@ -0,0 +1,790 @@ +// https://github.com/guybedford/es-module-shims + +/* ES Module Shims 1.3.6 */ +(function () { + + const edge = navigator.userAgent.match(/Edge\/\d\d\.\d+$/); + + let baseUrl; + + function createBlob(source, type = 'text/javascript') { + return URL.createObjectURL(new Blob([source], { type })); + } + + const noop = () => { }; + + const baseEl = document.querySelector('base[href]'); + if (baseEl) + baseUrl = baseEl.href; + + if (!baseUrl && typeof location !== 'undefined') { + baseUrl = location.href.split('#')[0].split('?')[0]; + const lastSepIndex = baseUrl.lastIndexOf('/'); + if (lastSepIndex !== -1) + baseUrl = baseUrl.slice(0, lastSepIndex + 1); + } + + function isURL(url) { + try { + new URL(url); + return true; + } + catch { + return false; + } + } + + const backslashRegEx = /\\/g; + function resolveIfNotPlainOrUrl(relUrl, parentUrl) { + // strip off any trailing query params or hashes + parentUrl = parentUrl && parentUrl.split('#')[0].split('?')[0]; + if (relUrl.indexOf('\\') !== -1) + relUrl = relUrl.replace(backslashRegEx, '/'); + // protocol-relative + if (relUrl[0] === '/' && relUrl[1] === '/') { + return parentUrl.slice(0, parentUrl.indexOf(':') + 1) + relUrl; + } + // relative-url + else if (relUrl[0] === '.' && (relUrl[1] === '/' || relUrl[1] === '.' && (relUrl[2] === '/' || relUrl.length === 2 && (relUrl += '/')) || + relUrl.length === 1 && (relUrl += '/')) || + relUrl[0] === '/') { + const parentProtocol = parentUrl.slice(0, parentUrl.indexOf(':') + 1); + // Disabled, but these cases will give inconsistent results for deep backtracking + //if (parentUrl[parentProtocol.length] !== '/') + // throw new Error('Cannot resolve'); + // read pathname from parent URL + // pathname taken to be part after leading "/" + let pathname; + if (parentUrl[parentProtocol.length + 1] === '/') { + // resolving to a :// so we need to read out the auth and host + if (parentProtocol !== 'file:') { + pathname = parentUrl.slice(parentProtocol.length + 2); + pathname = pathname.slice(pathname.indexOf('/') + 1); + } + else { + pathname = parentUrl.slice(8); + } + } + else { + // resolving to :/ so pathname is the /... part + pathname = parentUrl.slice(parentProtocol.length + (parentUrl[parentProtocol.length] === '/')); + } + + if (relUrl[0] === '/') + return parentUrl.slice(0, parentUrl.length - pathname.length - 1) + relUrl; + + // join together and split for removal of .. and . segments + // looping the string instead of anything fancy for perf reasons + // '../../../../../z' resolved to 'x/y' is just 'z' + const segmented = pathname.slice(0, pathname.lastIndexOf('/') + 1) + relUrl; + + const output = []; + let segmentIndex = -1; + for (let i = 0; i < segmented.length; i++) { + // busy reading a segment - only terminate on '/' + if (segmentIndex !== -1) { + if (segmented[i] === '/') { + output.push(segmented.slice(segmentIndex, i + 1)); + segmentIndex = -1; + } + } + + // new segment - check if it is relative + else if (segmented[i] === '.') { + // ../ segment + if (segmented[i + 1] === '.' && (segmented[i + 2] === '/' || i + 2 === segmented.length)) { + output.pop(); + i += 2; + } + // ./ segment + else if (segmented[i + 1] === '/' || i + 1 === segmented.length) { + i += 1; + } + else { + // the start of a new segment as below + segmentIndex = i; + } + } + // it is the start of a new segment + else { + segmentIndex = i; + } + } + // finish reading out the last segment + if (segmentIndex !== -1) + output.push(segmented.slice(segmentIndex)); + return parentUrl.slice(0, parentUrl.length - pathname.length) + output.join(''); + } + } + + /* + * Import maps implementation + * + * To make lookups fast we pre-resolve the entire import map + * and then match based on backtracked hash lookups + * + */ + function resolveUrl(relUrl, parentUrl) { + return resolveIfNotPlainOrUrl(relUrl, parentUrl) || (relUrl.indexOf(':') !== -1 ? relUrl : resolveIfNotPlainOrUrl('./' + relUrl, parentUrl)); + } + + function resolveAndComposePackages(packages, outPackages, baseUrl, parentMap) { + for (let p in packages) { + const resolvedLhs = resolveIfNotPlainOrUrl(p, baseUrl) || p; + if (outPackages[resolvedLhs]) { + throw new Error(`Dynamic import map rejected: Overrides entry "${resolvedLhs}" from ${outPackages[resolvedLhs]} to ${packages[resolvedLhs]}.`); + } + let target = packages[p]; + if (typeof target !== 'string') + continue; + const mapped = resolveImportMap(parentMap, resolveIfNotPlainOrUrl(target, baseUrl) || target, baseUrl); + if (mapped) { + outPackages[resolvedLhs] = mapped; + continue; + } + targetWarning(p, packages[p], 'bare specifier did not resolve'); + } + } + + function resolveAndComposeImportMap(json, baseUrl, parentMap) { + const outMap = { imports: Object.assign({}, parentMap.imports), scopes: Object.assign({}, parentMap.scopes) }; + + if (json.imports) + resolveAndComposePackages(json.imports, outMap.imports, baseUrl, parentMap); + + if (json.scopes) + for (let s in json.scopes) { + const resolvedScope = resolveUrl(s, baseUrl); + resolveAndComposePackages(json.scopes[s], outMap.scopes[resolvedScope] || (outMap.scopes[resolvedScope] = {}), baseUrl, parentMap); + } + + return outMap; + } + + function getMatch(path, matchObj) { + if (matchObj[path]) + return path; + let sepIndex = path.length; + do { + const segment = path.slice(0, sepIndex + 1); + if (segment in matchObj) + return segment; + } while ((sepIndex = path.lastIndexOf('/', sepIndex - 1)) !== -1) + } + + function applyPackages(id, packages) { + const pkgName = getMatch(id, packages); + if (pkgName) { + const pkg = packages[pkgName]; + if (pkg === null) return; + if (id.length > pkgName.length && pkg[pkg.length - 1] !== '/') + targetWarning(pkgName, pkg, "should have a trailing '/'"); + else + return pkg + id.slice(pkgName.length); + } + } + + function targetWarning(match, target, msg) { + console.warn("Package target " + msg + ", resolving target '" + target + "' for " + match); + } + + function resolveImportMap(importMap, resolvedOrPlain, parentUrl) { + let scopeUrl = parentUrl && getMatch(parentUrl, importMap.scopes); + while (scopeUrl) { + const packageResolution = applyPackages(resolvedOrPlain, importMap.scopes[scopeUrl]); + if (packageResolution) + return packageResolution; + scopeUrl = getMatch(scopeUrl.slice(0, scopeUrl.lastIndexOf('/')), importMap.scopes); + } + return applyPackages(resolvedOrPlain, importMap.imports) || resolvedOrPlain.indexOf(':') !== -1 && resolvedOrPlain; + } + + const optionsScript = document.querySelector('script[type=esms-options]'); + + const esmsInitOptions = optionsScript ? JSON.parse(optionsScript.innerHTML) : self.esmsInitOptions ? self.esmsInitOptions : {}; + + let shimMode = !!esmsInitOptions.shimMode; + const resolveHook = globalHook(shimMode && esmsInitOptions.resolve); + + const skip = esmsInitOptions.skip ? new RegExp(esmsInitOptions.skip) : null; + + let nonce = esmsInitOptions.nonce; + + if (!nonce) { + const nonceElement = document.querySelector('script[nonce]'); + if (nonceElement) + nonce = nonceElement.nonce || nonceElement.getAttribute('nonce'); + } + + const onerror = globalHook(esmsInitOptions.onerror || noop); + const onpolyfill = globalHook(esmsInitOptions.onpolyfill || noop); + + const { revokeBlobURLs, noLoadEventRetriggers } = esmsInitOptions; + + const fetchHook = esmsInitOptions.fetch ? globalHook(esmsInitOptions.fetch) : fetch; + + function globalHook(name) { + return typeof name === 'string' ? self[name] : name; + } + + const enable = Array.isArray(esmsInitOptions.polyfillEnable) ? esmsInitOptions.polyfillEnable : []; + const cssModulesEnabled = enable.includes('css-modules'); + const jsonModulesEnabled = enable.includes('json-modules'); + + function setShimMode() { + shimMode = true; + } + + let err; + window.addEventListener('error', _err => err = _err); + function dynamicImportScript(url, { errUrl = url } = {}) { + err = undefined; + const src = createBlob(`import*as m from'${url}';self._esmsi=m`); + const s = Object.assign(document.createElement('script'), { type: 'module', src }); + s.setAttribute('nonce', nonce); + s.setAttribute('noshim', ''); + const p = new Promise((resolve, reject) => { + // Safari is unique in supporting module script error events + s.addEventListener('error', cb); + s.addEventListener('load', cb); + + function cb(_err) { + document.head.removeChild(s); + if (self._esmsi) { + resolve(self._esmsi, baseUrl); + self._esmsi = undefined; + } + else { + reject(!(_err instanceof Event) && _err || err && err.error || new Error(`Error loading or executing the graph of ${errUrl} (check the console for ${src}).`)); + err = undefined; + } + } + }); + document.head.appendChild(s); + return p; + } + + let dynamicImport = dynamicImportScript; + + const supportsDynamicImportCheck = dynamicImportScript(createBlob('export default u=>import(u)')).then(_dynamicImport => { + if (_dynamicImport) + dynamicImport = _dynamicImport.default; + return !!_dynamicImport; + }, noop); + + // support browsers without dynamic import support (eg Firefox 6x) + let supportsJsonAssertions = false; + let supportsCssAssertions = false; + + let supportsImportMeta = false; + let supportsImportMaps = false; + + let supportsDynamicImport = false; + + const featureDetectionPromise = Promise.resolve(supportsDynamicImportCheck).then(_supportsDynamicImport => { + if (!_supportsDynamicImport) + return; + supportsDynamicImport = true; + + return Promise.all([ + dynamicImport(createBlob('import.meta')).then(() => supportsImportMeta = true, noop), + cssModulesEnabled && dynamicImport(createBlob('import"data:text/css,{}"assert{type:"css"}')).then(() => supportsCssAssertions = true, noop), + jsonModulesEnabled && dynamicImport(createBlob('import"data:text/json,{}"assert{type:"json"}')).then(() => supportsJsonAssertions = true, noop), + new Promise(resolve => { + self._$s = v => { + document.head.removeChild(iframe); + if (v) supportsImportMaps = true; + delete self._$s; + resolve(); + }; + const iframe = document.createElement('iframe'); + iframe.style.display = 'none'; + document.head.appendChild(iframe); + iframe.src = createBlob(`