Merge pull request #31 from bs-community/typescript

Migrate to TypeScript
This commit is contained in:
Haowei Wen 2018-08-23 16:33:57 +08:00 committed by GitHub
commit 63f2aa56f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 2125 additions and 3047 deletions

View File

@ -1,20 +0,0 @@
{
"presets": [
[
"env",
{
"targets": {
"browsers": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
},
"modules": false
}
]
],
"plugins": [
"external-helpers"
]
}

View File

@ -11,4 +11,3 @@ quote_type = double
[*.{yml,yaml}]
indent_style = space
indent_size = 2

5
.gitignore vendored
View File

@ -57,5 +57,8 @@ typings/
# dotenv environment variables file
.env
build/
dist/
_ignore/
dist/
.DS_Store
.rpt2_cache

View File

@ -1,23 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>skinview3d</title>
<link href="https://fonts.googleapis.com/css?family=Archivo+Black" rel="stylesheet">
<style>
html,
body {
margin: 0;
padding: 0;
background-color: #1e1e1e;
}
</style>
</head>
<body>
<div id="skin_container"></div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.min.js"></script>
<script type="text/javascript" src="../build/skinview3d.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<script type="text/javascript" src="../dist/skinview3d.js"></script>
<script>
let skinViewer = new skinview3d.SkinViewer({
domElement: document.getElementById("skin_container"),
width: 400,
height: 400,
width: 900,
height: 900,
skinUrl: "./1_8_texturemap_redux.png"
});
@ -35,4 +45,5 @@
</body>
</html>

View File

@ -7,11 +7,11 @@ module.exports = function (config) {
basePath: "",
frameworks: ["mocha"],
files: [
"test/test.js"
"test/test.ts"
],
exclude: [],
preprocessors: {
"test/test.js": ["webpack"]
"test/test.ts": ["webpack"]
},
webpack: {
mode: "development",
@ -20,19 +20,32 @@ module.exports = function (config) {
{
test: /\.png$/i,
loader: "url-loader"
},
{
test: /\.ts$/,
loader: "ts-loader",
options: {
transpileOnly: true
}
}
]
},
resolve: {
extensions: [".ts", ".js", ".json"]
}
},
webpackMiddleware: {
stats: "errors-only"
},
mime: {
"text/x-typescript": ["ts"]
},
reporters: ["progress"],
port: 9876,
colors: true,
logLevel: config.LOG_WARN,
autoWatch: false,
browsers: [process.env.TRAVIS ? "ChromeHeadlessNoSandbox" : "ChromeHeadless"],
browsers: ["ChromeHeadlessNoSandbox"],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: "ChromeHeadless",

2839
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -2,16 +2,14 @@
"name": "skinview3d",
"version": "1.1.0",
"description": "Three.js powered Minecraft skin viewer",
"module": "build/skinview3d.module.js",
"main": "build/skinview3d.js",
"typings": "types/skinview3d.d.ts",
"module": "dist/skinview3d.module.js",
"main": "dist/skinview3d.js",
"scripts": {
"build": "rollup -c tools/rollup.module.js && rollup -c tools/rollup.browser.js && rollup -c tools/rollup.browser.min.js",
"prepare": "npm test && rimraf build && npm run build",
"test": "karma start && npm run lint",
"lint": "eslint src/** tools/** && tslint -c tslint.json types/**.ts",
"build": "rollup -c",
"lint": "tslint --formatters-dir ./node_modules/tslint-formatter-beauty -t beauty -p .",
"dev": "npm-run-all --parallel watch serve",
"watch": "rollup -w -c tools/rollup.browser.js",
"watch": "rollup -w -c",
"test": "karma start && npm run lint",
"serve": "ws"
},
"repository": {
@ -31,17 +29,15 @@
},
"homepage": "https://github.com/bs-community/skinview3d",
"files": [
"types",
"build"
"dist"
],
"dependencies": {
"three": "^0.95.0"
},
"devDependencies": {
"@types/chai": "^4.1.4",
"@types/mocha": "^5.2.5",
"@types/three": "^0.92.17",
"babel-cli": "^6.26.0",
"babel-plugin-external-helpers": "^6.22.0",
"babel-preset-env": "^1.7.0",
"chai": "^4.1.2",
"eslint": "^5.4.0",
"karma": "^3.0.0",
@ -54,14 +50,16 @@
"puppeteer": "^1.7.0",
"rimraf": "^2.6.2",
"rollup": "^0.64.1",
"rollup-plugin-babel": "^3.0.7",
"rollup-plugin-license": "^0.7.0",
"rollup-plugin-node-resolve": "^3.3.0",
"rollup-plugin-typescript2": "^0.16.1",
"rollup-plugin-uglify": "^4.0.0",
"ts-loader": "^4.5.0",
"tslint": "^5.11.0",
"tslint-formatter-beauty": "^3.0.0-beta.2",
"typescript": "^3.0.1",
"uglify-es": "^3.3.10",
"url-loader": "^1.1.1",
"webpack": "^4.16.5"
"webpack": "^4.17.1"
}
}

50
rollup.config.js Normal file
View File

@ -0,0 +1,50 @@
import { uglify } from "rollup-plugin-uglify";
import typescript from "rollup-plugin-typescript2";
import resolve from "rollup-plugin-node-resolve";
import license from "rollup-plugin-license";
const base = {
input: "src/skinview3d.ts",
output: [
{
format: "umd",
name: "skinview3d",
file: "dist/skinview3d.js",
indent: "\t",
globals: {
"three": "THREE"
}
},
{
format: "es",
file: "dist/skinview3d.module.js",
indent: "\t"
}
],
external: [
"three"
],
plugins: [
resolve(),
typescript(),
license({
banner: `
skinview3d (https://github.com/bs-community/skinview3d)
MIT License
`
})
]
};
export default [
base,
Object.assign({}, base, {
output: Object.assign({}, base.output[0], { file: "dist/skinview3d.min.js" }),
plugins: (() => {
const plugin = base.plugins.slice();
plugin.splice(1, 0, uglify());
return plugin;
})()
})
];

View File

@ -1,5 +0,0 @@
module.exports = {
"env": {
"browser": true
}
}

View File

@ -1,127 +0,0 @@
function invokeAnimation(animation, player, time) {
if (animation instanceof CompositeAnimation) {
animation.play(player, time);
} else if (animation instanceof Function) {
animation(player, time);
} else {
throw `Not an animation: ${animation}`;
}
}
class AnimationHandle {
constructor(animation) {
this.animation = animation;
this.paused = this._paused = false;
this.speed = this._speed = 1.0;
this._lastChange = null;
this._lastChangeX = null;
}
play(player, time) {
if (this._lastChange === null) {
this._lastChange = time;
this._lastChangeX = 0;
} else if (this.paused !== this._paused || this.speed !== this._speed) {
let dt = time - this._lastChange;
if (this._paused === false) {
this._lastChangeX += dt * this._speed;
}
this._paused = this.paused;
this._speed = this.speed;
this._lastChange = time;
}
if (this.paused === false) {
let dt = time - this._lastChange;
let x = this._lastChangeX + this.speed * dt;
invokeAnimation(this.animation, player, x);
}
}
reset(){
this._lastChange = null;
}
}
class CompositeAnimation {
constructor() {
this.handles = new Set();
}
add(animation) {
let handle = new AnimationHandle(animation);
handle.remove = () => this.handles.delete(handle);
this.handles.add(handle);
return handle;
}
play(player, time) {
this.handles.forEach(handle => handle.play(player, time));
}
}
let WalkingAnimation = (player, time) => {
let skin = player.skin;
// Multiply by animation's natural speed
time *= 8;
// Leg swing
skin.leftLeg.rotation.x = Math.sin(time) * 0.5;
skin.rightLeg.rotation.x = Math.sin(time + Math.PI) * 0.5;
// Arm swing
skin.leftArm.rotation.x = Math.sin(time + Math.PI) * 0.5;
skin.rightArm.rotation.x = Math.sin(time) * 0.5;
let basicArmRotationZ = Math.PI * 0.02;
skin.leftArm.rotation.z = Math.cos(time) * 0.03 + basicArmRotationZ;
skin.rightArm.rotation.z = Math.cos(time + Math.PI) * 0.03 - basicArmRotationZ;
// Head shaking with different frequency & amplitude
skin.head.rotation.y = Math.sin(time / 4) * 0.2;
skin.head.rotation.x = Math.sin(time / 5) * 0.1;
// Always add an angle for cape around the x axis
let basicCapeRotationX = Math.PI * 0.06;
player.cape.rotation.x = Math.sin(time / 1.5) * 0.06 + basicCapeRotationX;
};
let RunningAnimation = (player, time) => {
let skin = player.skin;
time *= 15;
// Leg swing with larger amplitude
skin.leftLeg.rotation.x = Math.cos(time + Math.PI) * 1.3;
skin.rightLeg.rotation.x = Math.cos(time) * 1.3;
// Arm swing
skin.leftArm.rotation.x = Math.cos(time) * 1.5;
skin.rightArm.rotation.x = Math.cos(time + Math.PI) * 1.5;
let basicArmRotationZ = Math.PI * 0.1;
skin.leftArm.rotation.z = Math.cos(time) * 0.1 + basicArmRotationZ;
skin.rightArm.rotation.z = Math.cos(time + Math.PI) * 0.1 - basicArmRotationZ;
// Jumping
player.position.y = Math.cos(time * 2);
// Dodging when running
player.position.x = Math.cos(time) * 0.15;
// Slightly tilting when running
player.rotation.z = Math.cos(time + Math.PI) * 0.01;
// Apply higher swing frequency, lower amplitude,
// and greater basic rotation around x axis,
// to cape when running.
let basicCapeRotationX = Math.PI * 0.3;
player.cape.rotation.x = Math.sin(time * 2) * 0.1 + basicCapeRotationX;
// What about head shaking?
// You shouldn't glance right and left when running dude :P
};
let RotatingAnimation = (player, time) => {
player.rotation.y = time;
};
export {
CompositeAnimation,
invokeAnimation,
WalkingAnimation,
RunningAnimation,
RotatingAnimation
};

150
src/animation.ts Normal file
View File

@ -0,0 +1,150 @@
import { PlayerObject } from "./model";
export interface IAnimation {
play(player: PlayerObject, time: number): void;
}
export type AnimationFn = (player: PlayerObject, time: number) => void;
export type Animation = AnimationFn | IAnimation;
export function invokeAnimation(animation: Animation, player: PlayerObject, time: number) {
if (animation instanceof Function) {
animation(player, time);
} else {
// must be IAnimation here
animation.play(player, time);
}
}
// This interface is used to control animations
export interface AnimationHandle {
paused: boolean;
speed: number;
readonly animation: Animation;
reset(): void;
remove(): void;
}
class AnimationWrapper implements AnimationHandle, IAnimation {
public paused = false;
public speed: number = 1.0;
public readonly animation: Animation;
private _paused = false;
private _lastChange: number | null = null;
private _speed: number = 1.0;
private _lastChangeX: number | null = null;
constructor(animation: Animation) {
this.animation = animation;
}
play(player: PlayerObject, time: number) {
if (this._lastChange === null) {
this._lastChange = time;
this._lastChangeX = 0;
} else if (this.paused !== this._paused || this.speed !== this._speed) {
const dt = time - this._lastChange;
if (this._paused === false) {
this._lastChangeX! += dt * this._speed;
}
this._paused = this.paused;
this._speed = this.speed;
this._lastChange = time;
}
if (this.paused === false) {
const dt = time - this._lastChange;
const x = this._lastChangeX! + this.speed * dt;
invokeAnimation(this.animation, player, x);
}
}
reset() {
this._lastChange = null;
}
remove() {
// stub get's overriden
}
}
export class CompositeAnimation implements IAnimation {
readonly handles: Set<AnimationHandle & IAnimation> = new Set();
add(animation: Animation): AnimationHandle {
const handle = new AnimationWrapper(animation);
handle.remove = () => this.handles.delete(handle);
this.handles.add(handle);
return handle;
}
play(player: PlayerObject, time: number) {
this.handles.forEach(handle => handle.play(player, time));
}
}
export const WalkingAnimation: Animation = (player, time) => {
const skin = player.skin;
// Multiply by animation's natural speed
time *= 8;
// Leg swing
skin.leftLeg.rotation.x = Math.sin(time) * 0.5;
skin.rightLeg.rotation.x = Math.sin(time + Math.PI) * 0.5;
// Arm swing
skin.leftArm.rotation.x = Math.sin(time + Math.PI) * 0.5;
skin.rightArm.rotation.x = Math.sin(time) * 0.5;
const basicArmRotationZ = Math.PI * 0.02;
skin.leftArm.rotation.z = Math.cos(time) * 0.03 + basicArmRotationZ;
skin.rightArm.rotation.z = Math.cos(time + Math.PI) * 0.03 - basicArmRotationZ;
// Head shaking with different frequency & amplitude
skin.head.rotation.y = Math.sin(time / 4) * 0.2;
skin.head.rotation.x = Math.sin(time / 5) * 0.1;
// Always add an angle for cape around the x axis
const basicCapeRotationX = Math.PI * 0.06;
player.cape.rotation.x = Math.sin(time / 1.5) * 0.06 + basicCapeRotationX;
};
export const RunningAnimation: Animation = (player, time) => {
const skin = player.skin;
time *= 15;
// Leg swing with larger amplitude
skin.leftLeg.rotation.x = Math.cos(time + Math.PI) * 1.3;
skin.rightLeg.rotation.x = Math.cos(time) * 1.3;
// Arm swing
skin.leftArm.rotation.x = Math.cos(time) * 1.5;
skin.rightArm.rotation.x = Math.cos(time + Math.PI) * 1.5;
const basicArmRotationZ = Math.PI * 0.1;
skin.leftArm.rotation.z = Math.cos(time) * 0.1 + basicArmRotationZ;
skin.rightArm.rotation.z = Math.cos(time + Math.PI) * 0.1 - basicArmRotationZ;
// Jumping
player.position.y = Math.cos(time * 2);
// Dodging when running
player.position.x = Math.cos(time) * 0.15;
// Slightly tilting when running
player.rotation.z = Math.cos(time + Math.PI) * 0.01;
// Apply higher swing frequency, lower amplitude,
// and greater basic rotation around x axis,
// to cape when running.
const basicCapeRotationX = Math.PI * 0.3;
player.cape.rotation.x = Math.sin(time * 2) * 0.1 + basicCapeRotationX;
// What about head shaking?
// You shouldn't glance right and left when running dude :P
};
export const RotatingAnimation: Animation = (player, time) => {
player.rotation.y = time;
};

View File

@ -1,6 +1,6 @@
import * as THREE from "three";
function toFaceVertices(x1, y1, x2, y2, w, h) {
function toFaceVertices(x1: number, y1: number, x2: number, y2: number, w: number, h: number) {
return [
new THREE.Vector2(x1 / w, 1.0 - y2 / h),
new THREE.Vector2(x2 / w, 1.0 - y2 / h),
@ -9,15 +9,16 @@ function toFaceVertices(x1, y1, x2, y2, w, h) {
];
}
function toSkinVertices(x1, y1, x2, y2) {
function toSkinVertices(x1: number, y1: number, x2: number, y2: number) {
return toFaceVertices(x1, y1, x2, y2, 64.0, 64.0);
}
function toCapeVertices(x1, y1, x2, y2) {
function toCapeVertices(x1: number, y1: number, x2: number, y2: number) {
return toFaceVertices(x1, y1, x2, y2, 64.0, 32.0);
}
function setVertices(box, top, bottom, left, front, right, back) {
function setVertices(box: THREE.BoxGeometry, top: Array<THREE.Vector2>, bottom: Array<THREE.Vector2>, left: Array<THREE.Vector2>, front: Array<THREE.Vector2>, right: Array<THREE.Vector2>, back: Array<THREE.Vector2>) {
box.faceVertexUvs[0] = [];
box.faceVertexUvs[0][0] = [right[3], right[0], right[2]];
box.faceVertexUvs[0][1] = [right[0], right[1], right[2]];
@ -35,16 +36,26 @@ function setVertices(box, top, bottom, left, front, right, back) {
const esp = 0.002;
class SkinObject extends THREE.Group {
constructor(layer1Material, layer2Material) {
super();
export class SkinObject extends THREE.Group {
this.modelListeners = []; // called when model(slim property) is changed
// body parts
readonly head: THREE.Group;
readonly body: THREE.Group;
readonly rightArm: THREE.Group;
readonly leftArm: THREE.Group;
readonly rightLeg: THREE.Group;
readonly leftLeg: THREE.Group;
private modelListeners: Array<() => void> = []; // called when model(slim property) is changed
private _slim = false;
constructor(layer1Material: THREE.MeshBasicMaterial, layer2Material: THREE.MeshBasicMaterial) {
super();
// Head
this.head = new THREE.Group();
let headBox = new THREE.BoxGeometry(8, 8, 8, 0, 0, 0);
const headBox = new THREE.BoxGeometry(8, 8, 8, 0, 0, 0);
setVertices(headBox,
toSkinVertices(8, 0, 16, 8),
toSkinVertices(16, 0, 24, 8),
@ -53,10 +64,10 @@ class SkinObject extends THREE.Group {
toSkinVertices(16, 8, 24, 16),
toSkinVertices(24, 8, 32, 16)
);
let headMesh = new THREE.Mesh(headBox, layer1Material);
const headMesh = new THREE.Mesh(headBox, layer1Material);
this.head.add(headMesh);
let head2Box = new THREE.BoxGeometry(9, 9, 9, 0, 0, 0);
const head2Box = new THREE.BoxGeometry(9, 9, 9, 0, 0, 0);
setVertices(head2Box,
toSkinVertices(40, 0, 48, 8),
toSkinVertices(48, 0, 56, 8),
@ -65,17 +76,16 @@ class SkinObject extends THREE.Group {
toSkinVertices(48, 8, 56, 16),
toSkinVertices(56, 8, 64, 16)
);
let head2Mesh = new THREE.Mesh(head2Box, layer2Material);
const head2Mesh = new THREE.Mesh(head2Box, layer2Material);
head2Mesh.renderOrder = -1;
this.head.add(head2Mesh);
this.add(this.head);
// Body
this.body = new THREE.Group();
let bodyBox = new THREE.BoxGeometry(8, 12, 4, 0, 0, 0);
const bodyBox = new THREE.BoxGeometry(8, 12, 4, 0, 0, 0);
setVertices(bodyBox,
toSkinVertices(20, 16, 28, 20),
toSkinVertices(28, 16, 36, 20),
@ -84,10 +94,10 @@ class SkinObject extends THREE.Group {
toSkinVertices(28, 20, 32, 32),
toSkinVertices(32, 20, 40, 32)
);
let bodyMesh = new THREE.Mesh(bodyBox, layer1Material);
const bodyMesh = new THREE.Mesh(bodyBox, layer1Material);
this.body.add(bodyMesh);
let body2Box = new THREE.BoxGeometry(9, 13.5, 4.5, 0, 0, 0);
const body2Box = new THREE.BoxGeometry(9, 13.5, 4.5, 0, 0, 0);
setVertices(body2Box,
toSkinVertices(20, 32, 28, 36),
toSkinVertices(28, 32, 36, 36),
@ -96,19 +106,18 @@ class SkinObject extends THREE.Group {
toSkinVertices(28, 36, 32, 48),
toSkinVertices(32, 36, 40, 48)
);
let body2Mesh = new THREE.Mesh(body2Box, layer2Material);
const body2Mesh = new THREE.Mesh(body2Box, layer2Material);
this.body.add(body2Mesh);
this.body.position.y = -10;
this.add(this.body);
// Right Arm
this.rightArm = new THREE.Group();
let rightArmPivot = new THREE.Group();
const rightArmPivot = new THREE.Group();
let rightArmBox = new THREE.BoxGeometry(1, 1, 1, 0, 0, 0); // w/d/h is model-related
let rightArmMesh = new THREE.Mesh(rightArmBox, layer1Material);
const rightArmBox = new THREE.BoxGeometry(1, 1, 1, 0, 0, 0); // w/d/h is model-related
const rightArmMesh = new THREE.Mesh(rightArmBox, layer1Material);
rightArmPivot.add(rightArmMesh);
this.modelListeners.push(() => {
rightArmMesh.scale.x = (this.slim ? 3 : 4) - esp;
@ -137,8 +146,8 @@ class SkinObject extends THREE.Group {
rightArmBox.elementsNeedUpdate = true;
});
let rightArm2Box = new THREE.BoxGeometry(1, 1, 1, 0, 0, 0); // w/d/h is model-related
let rightArm2Mesh = new THREE.Mesh(rightArm2Box, layer2Material);
const rightArm2Box = new THREE.BoxGeometry(1, 1, 1, 0, 0, 0); // w/d/h is model-related
const rightArm2Mesh = new THREE.Mesh(rightArm2Box, layer2Material);
rightArm2Mesh.renderOrder = 1;
rightArmPivot.add(rightArm2Mesh);
this.modelListeners.push(() => {
@ -176,13 +185,12 @@ class SkinObject extends THREE.Group {
});
this.add(this.rightArm);
// Left Arm
this.leftArm = new THREE.Group();
let leftArmPivot = new THREE.Group();
const leftArmPivot = new THREE.Group();
let leftArmBox = new THREE.BoxGeometry(1, 1, 1, 0, 0, 0); // w/d/h is model-related
let leftArmMesh = new THREE.Mesh(leftArmBox, layer1Material);
const leftArmBox = new THREE.BoxGeometry(1, 1, 1, 0, 0, 0); // w/d/h is model-related
const leftArmMesh = new THREE.Mesh(leftArmBox, layer1Material);
leftArmPivot.add(leftArmMesh);
this.modelListeners.push(() => {
leftArmMesh.scale.x = (this.slim ? 3 : 4) - esp;
@ -208,11 +216,11 @@ class SkinObject extends THREE.Group {
);
}
leftArmBox.uvsNeedUpdate = true;
leftArmBox.elementsNeedUpdate=true;
leftArmBox.elementsNeedUpdate = true;
});
let leftArm2Box = new THREE.BoxGeometry(1, 1, 1, 0, 0, 0); // w/d/h is model-related
let leftArm2Mesh = new THREE.Mesh(leftArm2Box, layer2Material);
const leftArm2Box = new THREE.BoxGeometry(1, 1, 1, 0, 0, 0); // w/d/h is model-related
const leftArm2Mesh = new THREE.Mesh(leftArm2Box, layer2Material);
leftArm2Mesh.renderOrder = 1;
leftArmPivot.add(leftArm2Mesh);
this.modelListeners.push(() => {
@ -250,12 +258,11 @@ class SkinObject extends THREE.Group {
});
this.add(this.leftArm);
// Right Leg
this.rightLeg = new THREE.Group();
let rightLegPivot = new THREE.Group();
const rightLegPivot = new THREE.Group();
let rightLegBox = new THREE.BoxGeometry(4 - esp, 12 - esp, 4 - esp, 0, 0, 0);
const rightLegBox = new THREE.BoxGeometry(4 - esp, 12 - esp, 4 - esp, 0, 0, 0);
setVertices(rightLegBox,
toSkinVertices(4, 16, 8, 20),
toSkinVertices(8, 16, 12, 20),
@ -264,10 +271,10 @@ class SkinObject extends THREE.Group {
toSkinVertices(8, 20, 12, 32),
toSkinVertices(12, 20, 16, 32)
);
let rightLegMesh = new THREE.Mesh(rightLegBox, layer1Material);
const rightLegMesh = new THREE.Mesh(rightLegBox, layer1Material);
rightLegPivot.add(rightLegMesh);
let rightLeg2Box = new THREE.BoxGeometry(4.5 - esp, 13.5 - esp, 4.5 - esp, 0, 0, 0);
const rightLeg2Box = new THREE.BoxGeometry(4.5 - esp, 13.5 - esp, 4.5 - esp, 0, 0, 0);
setVertices(rightLeg2Box,
toSkinVertices(4, 32, 8, 36),
toSkinVertices(8, 32, 12, 36),
@ -276,7 +283,7 @@ class SkinObject extends THREE.Group {
toSkinVertices(8, 36, 12, 48),
toSkinVertices(12, 36, 16, 48)
);
let rightLeg2Mesh = new THREE.Mesh(rightLeg2Box, layer2Material);
const rightLeg2Mesh = new THREE.Mesh(rightLeg2Box, layer2Material);
rightLeg2Mesh.renderOrder = 1;
rightLegPivot.add(rightLeg2Mesh);
@ -288,9 +295,9 @@ class SkinObject extends THREE.Group {
// Left Leg
this.leftLeg = new THREE.Group();
let leftLegPivot = new THREE.Group();
const leftLegPivot = new THREE.Group();
let leftLegBox = new THREE.BoxGeometry(4 - esp, 12 - esp, 4 - esp, 0, 0, 0);
const leftLegBox = new THREE.BoxGeometry(4 - esp, 12 - esp, 4 - esp, 0, 0, 0);
setVertices(leftLegBox,
toSkinVertices(20, 48, 24, 52),
toSkinVertices(24, 48, 28, 52),
@ -299,10 +306,10 @@ class SkinObject extends THREE.Group {
toSkinVertices(24, 52, 28, 64),
toSkinVertices(28, 52, 32, 64)
);
let leftLegMesh = new THREE.Mesh(leftLegBox, layer1Material);
const leftLegMesh = new THREE.Mesh(leftLegBox, layer1Material);
leftLegPivot.add(leftLegMesh);
let leftLeg2Box = new THREE.BoxGeometry(4.5 - esp, 13.5 - esp, 4.5 - esp, 0, 0, 0);
const leftLeg2Box = new THREE.BoxGeometry(4.5 - esp, 13.5 - esp, 4.5 - esp, 0, 0, 0);
setVertices(leftLeg2Box,
toSkinVertices(4, 48, 8, 52),
toSkinVertices(8, 48, 12, 52),
@ -311,7 +318,7 @@ class SkinObject extends THREE.Group {
toSkinVertices(8, 52, 12, 64),
toSkinVertices(12, 52, 16, 64)
);
let leftLeg2Mesh = new THREE.Mesh(leftLeg2Box, layer2Material);
const leftLeg2Mesh = new THREE.Mesh(leftLeg2Box, layer2Material);
leftLeg2Mesh.renderOrder = 1;
leftLegPivot.add(leftLeg2Mesh);
@ -329,20 +336,21 @@ class SkinObject extends THREE.Group {
}
set slim(value) {
if (this._slim !== value) {
this._slim = value;
this.modelListeners.forEach(listener => listener());
}
this._slim = value;
this.modelListeners.forEach(listener => listener());
}
}
class CapeObject extends THREE.Group {
constructor(capeMaterial) {
export class CapeObject extends THREE.Group {
readonly cape: THREE.Mesh;
constructor(capeMaterial: THREE.MeshBasicMaterial) {
super();
// back = outside
// front = inside
let capeBox = new THREE.BoxGeometry(10, 16, 1, 0, 0, 0);
const capeBox = new THREE.BoxGeometry(10, 16, 1, 0, 0, 0);
setVertices(capeBox,
toCapeVertices(1, 0, 11, 1),
toCapeVertices(11, 0, 21, 1),
@ -358,8 +366,12 @@ class CapeObject extends THREE.Group {
}
}
class PlayerObject extends THREE.Group {
constructor(layer1Material, layer2Material, capeMaterial) {
export class PlayerObject extends THREE.Group {
readonly skin: SkinObject;
readonly cape: CapeObject;
constructor(layer1Material: THREE.MeshBasicMaterial, layer2Material: THREE.MeshBasicMaterial, capeMaterial: THREE.MeshBasicMaterial) {
super();
this.skin = new SkinObject(layer1Material, layer2Material);
@ -374,5 +386,3 @@ class PlayerObject extends THREE.Group {
this.add(this.cape);
}
}
export { SkinObject, CapeObject, PlayerObject };

View File

@ -1,609 +0,0 @@
import * as THREE from "three";
class OrbitControls extends THREE.EventDispatcher {
/**
* @preserve
* The code was originally from https://github.com/mrdoob/three.js/blob/d45a042cf962e9b1aa9441810ba118647b48aacb/examples/js/controls/OrbitControls.js
*/
/**
* @license
* Copyright (C) 2010-2017 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.
*
*
* @author qiao / https://github.com/qiao
* @author mrdoob / http://mrdoob.com
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author erich666 / http://erichaines.com
*/
// This set of controls performs orbiting, dollying (zooming), and panning.
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
//
// Orbit - left mouse / touch: one finger move
// Zoom - middle mouse, or mousewheel / touch: two finger spread or squish
// Pan - right mouse, or arrow keys / touch: three finger swipe
constructor(object, domElement) {
super();
this.object = object;
this.domElement = (domElement !== undefined) ? domElement : document;
// Set to false to disable this control
this.enabled = true;
// "target" sets the location of focus, where the object orbits around
this.target = new THREE.Vector3();
// How far you can dolly in and out (PerspectiveCamera only)
this.minDistance = 0;
this.maxDistance = Infinity;
// How far you can zoom in and out (OrthographicCamera only)
this.minZoom = 0;
this.maxZoom = Infinity;
// How far you can orbit vertically, upper and lower limits.
// Range is 0 to Math.PI radians.
this.minPolarAngle = 0; // radians
this.maxPolarAngle = Math.PI; // radians
// How far you can orbit horizontally, upper and lower limits.
// If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
this.minAzimuthAngle = -Infinity; // radians
this.maxAzimuthAngle = Infinity; // radians
// Set to true to enable damping (inertia)
// If damping is enabled, you must call controls.update() in your animation loop
this.enableDamping = false;
this.dampingFactor = 0.25;
// This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
// Set to false to disable zooming
this.enableZoom = true;
this.zoomSpeed = 1.0;
// Set to false to disable rotating
this.enableRotate = true;
this.rotateSpeed = 1.0;
// Set to false to disable panning
this.enablePan = true;
this.keyPanSpeed = 7.0; // pixels moved per arrow key push
// Set to true to automatically rotate around the target
// If auto-rotate is enabled, you must call controls.update() in your animation loop
this.autoRotate = false;
this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
// Set to false to disable use of the keys
this.enableKeys = true;
// The four arrow keys
this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 };
// Mouse buttons
this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT };
// for reset
this.target0 = this.target.clone();
this.position0 = this.object.position.clone();
this.zoom0 = this.object.zoom;
//
// public methods
//
this.getPolarAngle = function () {
return spherical.phi;
};
this.getAzimuthalAngle = function () {
return spherical.theta;
};
this.saveState = function () {
scope.target0.copy(scope.target);
scope.position0.copy(scope.object.position);
scope.zoom0 = scope.object.zoom;
};
this.reset = function () {
scope.target.copy(scope.target0);
scope.object.position.copy(scope.position0);
scope.object.zoom = scope.zoom0;
scope.object.updateProjectionMatrix();
scope.dispatchEvent(changeEvent);
scope.update();
state = STATE.NONE;
};
// this method is exposed, but perhaps it would be better if we can make it private...
this.update = function () {
let offset = new THREE.Vector3();
// so camera.up is the orbit axis
let quat = new THREE.Quaternion().setFromUnitVectors(object.up, new THREE.Vector3(0, 1, 0));
let quatInverse = quat.clone().inverse();
let lastPosition = new THREE.Vector3();
let lastQuaternion = new THREE.Quaternion();
return function update() {
let position = scope.object.position;
offset.copy(position).sub(scope.target);
// rotate offset to "y-axis-is-up" space
offset.applyQuaternion(quat);
// angle from z-axis around y-axis
spherical.setFromVector3(offset);
if (scope.autoRotate && state === STATE.NONE) {
rotateLeft(getAutoRotationAngle());
}
spherical.theta += sphericalDelta.theta;
spherical.phi += sphericalDelta.phi;
// restrict theta to be between desired limits
spherical.theta = Math.max(scope.minAzimuthAngle, Math.min(scope.maxAzimuthAngle, spherical.theta));
// restrict phi to be between desired limits
spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
spherical.makeSafe();
spherical.radius *= scale;
// restrict radius to be between desired limits
spherical.radius = Math.max(scope.minDistance, Math.min(scope.maxDistance, spherical.radius));
// move target to panned location
scope.target.add(panOffset);
offset.setFromSpherical(spherical);
// rotate offset back to "camera-up-vector-is-up" space
offset.applyQuaternion(quatInverse);
position.copy(scope.target).add(offset);
scope.object.lookAt(scope.target);
if (scope.enableDamping === true) {
sphericalDelta.theta *= (1 - scope.dampingFactor);
sphericalDelta.phi *= (1 - scope.dampingFactor);
}
else {
sphericalDelta.set(0, 0, 0);
}
scale = 1;
panOffset.set(0, 0, 0);
// update condition is:
// min(camera displacement, camera rotation in radians)^2 > EPS
// using small-angle approximation cos(x/2) = 1 - x^2 / 8
if (zoomChanged ||
lastPosition.distanceToSquared(scope.object.position) > EPS ||
8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS) {
scope.dispatchEvent(changeEvent);
lastPosition.copy(scope.object.position);
lastQuaternion.copy(scope.object.quaternion);
zoomChanged = false;
return true;
}
return false;
};
}();
this.dispose = function () {
scope.domElement.removeEventListener("contextmenu", onContextMenu, false);
scope.domElement.removeEventListener("mousedown", onMouseDown, false);
scope.domElement.removeEventListener("wheel", onMouseWheel, false);
scope.domElement.removeEventListener("touchstart", onTouchStart, false);
scope.domElement.removeEventListener("touchend", onTouchEnd, false);
scope.domElement.removeEventListener("touchmove", onTouchMove, false);
document.removeEventListener("mousemove", onMouseMove, false);
document.removeEventListener("mouseup", onMouseUp, false);
window.removeEventListener("keydown", onKeyDown, false);
//scope.dispatchEvent({ type: "dispose" }); // should this be added here?
};
//
// internals
//
let scope = this;
let changeEvent = { type: "change" };
let startEvent = { type: "start" };
let endEvent = { type: "end" };
let STATE = { NONE: -1, ROTATE: 0, DOLLY: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_DOLLY: 4, TOUCH_PAN: 5 };
let state = STATE.NONE;
let EPS = 0.000001;
// current position in spherical coordinates
let spherical = new THREE.Spherical();
let sphericalDelta = new THREE.Spherical();
let scale = 1;
let panOffset = new THREE.Vector3();
let zoomChanged = false;
let rotateStart = new THREE.Vector2();
let rotateEnd = new THREE.Vector2();
let rotateDelta = new THREE.Vector2();
let panStart = new THREE.Vector2();
let panEnd = new THREE.Vector2();
let panDelta = new THREE.Vector2();
let dollyStart = new THREE.Vector2();
let dollyEnd = new THREE.Vector2();
let dollyDelta = new THREE.Vector2();
function getAutoRotationAngle() {
return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
}
function getZoomScale() {
return Math.pow(0.95, scope.zoomSpeed);
}
function rotateLeft(angle) {
sphericalDelta.theta -= angle;
}
function rotateUp(angle) {
sphericalDelta.phi -= angle;
}
let panLeft = function () {
let v = new THREE.Vector3();
return function panLeft(distance, objectMatrix) {
v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
v.multiplyScalar(-distance);
panOffset.add(v);
};
}();
let panUp = function () {
let v = new THREE.Vector3();
return function panUp(distance, objectMatrix) {
v.setFromMatrixColumn(objectMatrix, 1); // get Y column of objectMatrix
v.multiplyScalar(distance);
panOffset.add(v);
};
}();
// deltaX and deltaY are in pixels; right and down are positive
let pan = function () {
let offset = new THREE.Vector3();
return function pan(deltaX, deltaY) {
let element = scope.domElement === document ? scope.domElement.body : scope.domElement;
if (scope.object instanceof THREE.PerspectiveCamera) {
// perspective
let position = scope.object.position;
offset.copy(position).sub(scope.target);
let targetDistance = offset.length();
// half of the fov is center to top of screen
targetDistance *= Math.tan((scope.object.fov / 2) * Math.PI / 180.0);
// we actually don't use screenWidth, since perspective camera is fixed to screen height
panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
}
else if (scope.object instanceof THREE.OrthographicCamera) {
// orthographic
panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
}
else {
// camera neither orthographic nor perspective
console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");
scope.enablePan = false;
}
};
}();
function dollyIn(dollyScale) {
if (scope.object instanceof THREE.PerspectiveCamera) {
scale /= dollyScale;
}
else if (scope.object instanceof THREE.OrthographicCamera) {
scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom * dollyScale));
scope.object.updateProjectionMatrix();
zoomChanged = true;
}
else {
console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
scope.enableZoom = false;
}
}
function dollyOut(dollyScale) {
if (scope.object instanceof THREE.PerspectiveCamera) {
scale *= dollyScale;
}
else if (scope.object instanceof THREE.OrthographicCamera) {
scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / dollyScale));
scope.object.updateProjectionMatrix();
zoomChanged = true;
}
else {
console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
scope.enableZoom = false;
}
}
//
// event callbacks - update the object state
//
function handleMouseDownRotate(event) {
rotateStart.set(event.clientX, event.clientY);
}
function handleMouseDownDolly(event) {
dollyStart.set(event.clientX, event.clientY);
}
function handleMouseDownPan(event) {
panStart.set(event.clientX, event.clientY);
}
function handleMouseMoveRotate(event) {
rotateEnd.set(event.clientX, event.clientY);
rotateDelta.subVectors(rotateEnd, rotateStart);
let element = scope.domElement === document ? scope.domElement.body : scope.domElement;
// rotating across whole screen goes 360 degrees around
rotateLeft(2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed);
// rotating up and down along whole screen attempts to go 360, but limited to 180
rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed);
rotateStart.copy(rotateEnd);
scope.update();
}
function handleMouseMoveDolly(event) {
dollyEnd.set(event.clientX, event.clientY);
dollyDelta.subVectors(dollyEnd, dollyStart);
if (dollyDelta.y > 0) {
dollyIn(getZoomScale());
}
else if (dollyDelta.y < 0) {
dollyOut(getZoomScale());
}
dollyStart.copy(dollyEnd);
scope.update();
}
function handleMouseMovePan(event) {
panEnd.set(event.clientX, event.clientY);
panDelta.subVectors(panEnd, panStart);
pan(panDelta.x, panDelta.y);
panStart.copy(panEnd);
scope.update();
}
function handleMouseUp(event) {
}
function handleMouseWheel(event) {
if (event.deltaY < 0) {
dollyOut(getZoomScale());
}
else if (event.deltaY > 0) {
dollyIn(getZoomScale());
}
scope.update();
}
function handleKeyDown(event) {
switch (event.keyCode) {
case scope.keys.UP:
pan(0, scope.keyPanSpeed);
scope.update();
break;
case scope.keys.BOTTOM:
pan(0, -scope.keyPanSpeed);
scope.update();
break;
case scope.keys.LEFT:
pan(scope.keyPanSpeed, 0);
scope.update();
break;
case scope.keys.RIGHT:
pan(-scope.keyPanSpeed, 0);
scope.update();
break;
}
}
function handleTouchStartRotate(event) {
rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
}
function handleTouchStartDolly(event) {
let dx = event.touches[0].pageX - event.touches[1].pageX;
let dy = event.touches[0].pageY - event.touches[1].pageY;
let distance = Math.sqrt(dx * dx + dy * dy);
dollyStart.set(0, distance);
}
function handleTouchStartPan(event) {
panStart.set(event.touches[0].pageX, event.touches[0].pageY);
}
function handleTouchMoveRotate(event) {
rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
rotateDelta.subVectors(rotateEnd, rotateStart);
let element = scope.domElement === document ? scope.domElement.body : scope.domElement;
rotateLeft(2 * Math.PI * rotateDelta.x / element.clientWidth * scope.rotateSpeed);
rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight * scope.rotateSpeed);
rotateStart.copy(rotateEnd);
scope.update();
}
function handleTouchMoveDolly(event) {
let dx = event.touches[0].pageX - event.touches[1].pageX;
let dy = event.touches[0].pageY - event.touches[1].pageY;
let distance = Math.sqrt(dx * dx + dy * dy);
dollyEnd.set(0, distance);
dollyDelta.subVectors(dollyEnd, dollyStart);
if (dollyDelta.y > 0) {
dollyOut(getZoomScale());
}
else if (dollyDelta.y < 0) {
dollyIn(getZoomScale());
}
dollyStart.copy(dollyEnd);
scope.update();
}
function handleTouchMovePan(event) {
panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
panDelta.subVectors(panEnd, panStart);
pan(panDelta.x, panDelta.y);
panStart.copy(panEnd);
scope.update();
}
function handleTouchEnd(event) {
}
//
// event handlers - FSM: listen for events and reset state
//
function onMouseDown(event) {
if (scope.enabled === false)
return;
switch (event.button) {
case scope.mouseButtons.ORBIT:
if (scope.enableRotate === false)
return;
handleMouseDownRotate(event);
state = STATE.ROTATE;
break;
case scope.mouseButtons.ZOOM:
if (scope.enableZoom === false)
return;
handleMouseDownDolly(event);
state = STATE.DOLLY;
break;
case scope.mouseButtons.PAN:
if (scope.enablePan === false)
return;
handleMouseDownPan(event);
state = STATE.PAN;
break;
}
event.preventDefault();
if (state !== STATE.NONE) {
document.addEventListener("mousemove", onMouseMove, false);
document.addEventListener("mouseup", onMouseUp, false);
scope.dispatchEvent(startEvent);
}
}
function onMouseMove(event) {
if (scope.enabled === false)
return;
switch (state) {
case STATE.ROTATE:
if (scope.enableRotate === false)
return;
handleMouseMoveRotate(event);
break;
case STATE.DOLLY:
if (scope.enableZoom === false)
return;
handleMouseMoveDolly(event);
break;
case STATE.PAN:
if (scope.enablePan === false)
return;
handleMouseMovePan(event);
break;
}
event.preventDefault();
}
function onMouseUp(event) {
if (scope.enabled === false)
return;
handleMouseUp(event);
document.removeEventListener("mousemove", onMouseMove, false);
document.removeEventListener("mouseup", onMouseUp, false);
scope.dispatchEvent(endEvent);
state = STATE.NONE;
}
function onMouseWheel(event) {
if (scope.enabled === false || scope.enableZoom === false || (state !== STATE.NONE && state !== STATE.ROTATE))
return;
event.preventDefault();
event.stopPropagation();
handleMouseWheel(event);
scope.dispatchEvent(startEvent); // not sure why these are here...
scope.dispatchEvent(endEvent);
}
function onKeyDown(event) {
if (scope.enabled === false || scope.enableKeys === false || scope.enablePan === false)
return;
handleKeyDown(event);
}
function onTouchStart(event) {
if (scope.enabled === false)
return;
switch (event.touches.length) {
case 1:// one-fingered touch: rotate
if (scope.enableRotate === false)
return;
handleTouchStartRotate(event);
state = STATE.TOUCH_ROTATE;
break;
case 2:// two-fingered touch: dolly
if (scope.enableZoom === false)
return;
handleTouchStartDolly(event);
state = STATE.TOUCH_DOLLY;
break;
case 3:// three-fingered touch: pan
if (scope.enablePan === false)
return;
handleTouchStartPan(event);
state = STATE.TOUCH_PAN;
break;
default:
state = STATE.NONE;
}
if (state !== STATE.NONE) {
scope.dispatchEvent(startEvent);
}
}
function onTouchMove(event) {
if (scope.enabled === false)
return;
switch (event.touches.length) {
case 1:// one-fingered touch: rotate
if (scope.enableRotate === false)
return;
if (state !== STATE.TOUCH_ROTATE)
return; // is this needed?...
handleTouchMoveRotate(event);
break;
case 2:// two-fingered touch: dolly
if (scope.enableZoom === false)
return;
if (state !== STATE.TOUCH_DOLLY)
return; // is this needed?...
handleTouchMoveDolly(event);
break;
case 3:// three-fingered touch: pan
if (scope.enablePan === false)
return;
if (state !== STATE.TOUCH_PAN)
return; // is this needed?...
handleTouchMovePan(event);
break;
default:
state = STATE.NONE;
}
event.preventDefault();
event.stopPropagation();
}
function onTouchEnd(event) {
if (scope.enabled === false)
return;
handleTouchEnd(event);
scope.dispatchEvent(endEvent);
state = STATE.NONE;
}
function onContextMenu(event) {
if (scope.enabled === false || scope.enablePan === false)
return;
event.preventDefault();
}
//
scope.domElement.addEventListener("contextmenu", onContextMenu, false);
scope.domElement.addEventListener("mousedown", onMouseDown, false);
scope.domElement.addEventListener("wheel", onMouseWheel, false);
scope.domElement.addEventListener("touchstart", onTouchStart, false);
scope.domElement.addEventListener("touchend", onTouchEnd, false);
scope.domElement.addEventListener("touchmove", onTouchMove, false);
window.addEventListener("keydown", onKeyDown, false);
// force an update at start
this.update();
}
}
function createOrbitControls(skinViewer) {
let control = new OrbitControls(skinViewer.camera, skinViewer.renderer.domElement);
// default configuration
control.enablePan = false;
control.target = new THREE.Vector3(0, -12, 0);
control.minDistance = 10;
control.maxDistance = 256;
control.update();
return control;
}
export { OrbitControls, createOrbitControls };

729
src/orbit_controls.ts Normal file
View File

@ -0,0 +1,729 @@
import * as THREE from "three";
import { SkinViewer } from "./viewer";
const STATE = {
NONE: - 1,
ROTATE: 0,
DOLLY: 1,
PAN: 2,
TOUCH_ROTATE: 3,
TOUCH_DOLLY: 4,
TOUCH_PAN: 5
};
const CHANGE_EVENT = { type: "change" };
const START_EVENT = { type: "start" };
const END_EVENT = { type: "end" };
const EPS = 0.000001;
export class OrbitControls extends THREE.EventDispatcher {
/**
* @preserve
* The code was originally from https://github.com/mrdoob/three.js/blob/d45a042cf962e9b1aa9441810ba118647b48aacb/examples/js/controls/OrbitControls.js
*/
/**
* @license
* Copyright (C) 2010-2017 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.
*
*
* @author qiao / https://github.com/qiao
* @author mrdoob / http://mrdoob.com
* @author alteredq / http://alteredqualia.com/
* @author WestLangley / http://github.com/WestLangley
* @author erich666 / http://erichaines.com
*/
// This set of controls performs orbiting, dollying (zooming), and panning.
// Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
//
// Orbit - left mouse / touch: one finger move
// Zoom - middle mouse, or mousewheel / touch: two finger spread or squish
// Pan - right mouse, or arrow keys / touch: three finger swipe
object: THREE.Camera;
domElement: HTMLElement | HTMLDocument;
window: Window;
// API
enabled: boolean;
target: THREE.Vector3;
enableZoom: boolean;
zoomSpeed: number;
minDistance: number;
maxDistance: number;
enableRotate: boolean;
rotateSpeed: number;
enablePan: boolean;
keyPanSpeed: number;
autoRotate: boolean;
autoRotateSpeed: number;
minZoom: number;
maxZoom: number;
minPolarAngle: number;
maxPolarAngle: number;
minAzimuthAngle: number;
maxAzimuthAngle: number;
enableKeys: boolean;
keys: { LEFT: number; UP: number; RIGHT: number; BOTTOM: number; };
mouseButtons: { ORBIT: THREE.MOUSE; ZOOM: THREE.MOUSE; PAN: THREE.MOUSE; };
enableDamping: boolean;
dampingFactor: number;
private spherical: THREE.Spherical;
private sphericalDelta: THREE.Spherical;
private scale: number;
private target0: THREE.Vector3;
private position0: THREE.Vector3;
private zoom0: any;
private state: number;
private panOffset: THREE.Vector3;
private zoomChanged: boolean;
private rotateStart: THREE.Vector2;
private rotateEnd: THREE.Vector2;
private rotateDelta: THREE.Vector2;
private panStart: THREE.Vector2;
private panEnd: THREE.Vector2;
private panDelta: THREE.Vector2;
private dollyStart: THREE.Vector2;
private dollyEnd: THREE.Vector2;
private dollyDelta: THREE.Vector2;
private updateLastPosition: THREE.Vector3;
private updateOffset: THREE.Vector3;
private updateQuat: THREE.Quaternion;
private updateLastQuaternion: THREE.Quaternion;
private updateQuatInverse: THREE.Quaternion;
private panLeftV: THREE.Vector3;
private panUpV: THREE.Vector3;
private panInternalOffset: THREE.Vector3;
private onContextMenu: EventListener;
private onMouseUp: EventListener;
private onMouseDown: EventListener;
private onMouseMove: EventListener;
private onMouseWheel: EventListener;
private onTouchStart: EventListener;
private onTouchEnd: EventListener;
private onTouchMove: EventListener;
private onKeyDown: EventListener;
constructor(object: THREE.Camera, domElement?: HTMLElement, domWindow?: Window) {
super();
this.object = object;
this.domElement = (domElement !== undefined) ? domElement : document;
this.window = (domWindow !== undefined) ? domWindow : window;
// Set to false to disable this control
this.enabled = true;
// "target" sets the location of focus, where the object orbits around
this.target = new THREE.Vector3();
// How far you can dolly in and out ( PerspectiveCamera only )
this.minDistance = 0;
this.maxDistance = Infinity;
// How far you can zoom in and out ( OrthographicCamera only )
this.minZoom = 0;
this.maxZoom = Infinity;
// How far you can orbit vertically, upper and lower limits.
// Range is 0 to Math.PI radians.
this.minPolarAngle = 0; // radians
this.maxPolarAngle = Math.PI; // radians
// How far you can orbit horizontally, upper and lower limits.
// If set, must be a sub-interval of the interval [ - Math.PI, Math.PI ].
this.minAzimuthAngle = - Infinity; // radians
this.maxAzimuthAngle = Infinity; // radians
// Set to true to enable damping (inertia)
// If damping is enabled, you must call controls.update() in your animation loop
this.enableDamping = false;
this.dampingFactor = 0.25;
// This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
// Set to false to disable zooming
this.enableZoom = true;
this.zoomSpeed = 1.0;
// Set to false to disable rotating
this.enableRotate = true;
this.rotateSpeed = 1.0;
// Set to false to disable panning
this.enablePan = true;
this.keyPanSpeed = 7.0; // pixels moved per arrow key push
// Set to true to automatically rotate around the target
// If auto-rotate is enabled, you must call controls.update() in your animation loop
this.autoRotate = false;
this.autoRotateSpeed = 2.0; // 30 seconds per round when fps is 60
// Set to false to disable use of the keys
this.enableKeys = true;
// The four arrow keys
this.keys = { LEFT: 37, UP: 38, RIGHT: 39, BOTTOM: 40 };
// Mouse buttons
this.mouseButtons = { ORBIT: THREE.MOUSE.LEFT, ZOOM: THREE.MOUSE.MIDDLE, PAN: THREE.MOUSE.RIGHT };
// for reset
this.target0 = this.target.clone();
this.position0 = this.object.position.clone();
this.zoom0 = (this.object as any).zoom;
// for update speedup
this.updateOffset = new THREE.Vector3();
// so camera.up is the orbit axis
this.updateQuat = new THREE.Quaternion().setFromUnitVectors(object.up, new THREE.Vector3(0, 1, 0));
this.updateQuatInverse = this.updateQuat.clone().inverse();
this.updateLastPosition = new THREE.Vector3();
this.updateLastQuaternion = new THREE.Quaternion();
this.state = STATE.NONE;
this.scale = 1;
// current position in spherical coordinates
this.spherical = new THREE.Spherical();
this.sphericalDelta = new THREE.Spherical();
this.panOffset = new THREE.Vector3();
this.zoomChanged = false;
this.rotateStart = new THREE.Vector2();
this.rotateEnd = new THREE.Vector2();
this.rotateDelta = new THREE.Vector2();
this.panStart = new THREE.Vector2();
this.panEnd = new THREE.Vector2();
this.panDelta = new THREE.Vector2();
this.dollyStart = new THREE.Vector2();
this.dollyEnd = new THREE.Vector2();
this.dollyDelta = new THREE.Vector2();
this.panLeftV = new THREE.Vector3();
this.panUpV = new THREE.Vector3();
this.panInternalOffset = new THREE.Vector3();
// event handlers - FSM: listen for events and reset state
this.onMouseDown = (event: ThreeEvent) => {
if (this.enabled === false) return;
event.preventDefault();
if ((event as any).button === this.mouseButtons.ORBIT) {
if (this.enableRotate === false) return;
this.rotateStart.set(event.clientX, event.clientY);
this.state = STATE.ROTATE;
} else if (event.button === this.mouseButtons.ZOOM) {
if (this.enableZoom === false) return;
this.dollyStart.set(event.clientX, event.clientY);
this.state = STATE.DOLLY;
} else if (event.button === this.mouseButtons.PAN) {
if (this.enablePan === false) return;
this.panStart.set(event.clientX, event.clientY);
this.state = STATE.PAN;
}
if (this.state !== STATE.NONE) {
document.addEventListener("mousemove", this.onMouseMove, false);
document.addEventListener("mouseup", this.onMouseUp, false);
this.dispatchEvent(START_EVENT);
}
};
this.onMouseMove = (event: ThreeEvent) => {
if (this.enabled === false) return;
event.preventDefault();
if (this.state === STATE.ROTATE) {
if (this.enableRotate === false) return;
this.rotateEnd.set(event.clientX, event.clientY);
this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
const element = this.domElement === document ? this.domElement.body : this.domElement;
// rotating across whole screen goes 360 degrees around
this.rotateLeft(2 * Math.PI * this.rotateDelta.x / (element as any).clientWidth * this.rotateSpeed);
// rotating up and down along whole screen attempts to go 360, but limited to 180
this.rotateUp(2 * Math.PI * this.rotateDelta.y / (element as any).clientHeight * this.rotateSpeed);
this.rotateStart.copy(this.rotateEnd);
this.update();
} else if (this.state === STATE.DOLLY) {
if (this.enableZoom === false) return;
this.dollyEnd.set(event.clientX, event.clientY);
this.dollyDelta.subVectors(this.dollyEnd, this.dollyStart);
if (this.dollyDelta.y > 0) {
this.dollyIn(this.getZoomScale());
} else if (this.dollyDelta.y < 0) {
this.dollyOut(this.getZoomScale());
}
this.dollyStart.copy(this.dollyEnd);
this.update();
} else if (this.state === STATE.PAN) {
if (this.enablePan === false) return;
this.panEnd.set(event.clientX, event.clientY);
this.panDelta.subVectors(this.panEnd, this.panStart);
this.pan(this.panDelta.x, this.panDelta.y);
this.panStart.copy(this.panEnd);
this.update();
}
};
this.onMouseUp = (event: ThreeEvent) => {
if (this.enabled === false) return;
document.removeEventListener("mousemove", this.onMouseMove, false);
document.removeEventListener("mouseup", this.onMouseUp, false);
this.dispatchEvent(END_EVENT);
this.state = STATE.NONE;
};
this.onMouseWheel = (event: ThreeEvent) => {
if (this.enabled === false || this.enableZoom === false || (this.state !== STATE.NONE && this.state !== STATE.ROTATE)) return;
event.preventDefault();
event.stopPropagation();
if (event.deltaY < 0) {
this.dollyOut(this.getZoomScale());
} else if (event.deltaY > 0) {
this.dollyIn(this.getZoomScale());
}
this.update();
this.dispatchEvent(START_EVENT); // not sure why these are here...
this.dispatchEvent(END_EVENT);
};
this.onKeyDown = (event: ThreeEvent) => {
if (this.enabled === false || this.enableKeys === false || this.enablePan === false) return;
switch (event.keyCode) {
case this.keys.UP: {
this.pan(0, this.keyPanSpeed);
this.update();
break;
}
case this.keys.BOTTOM: {
this.pan(0, - this.keyPanSpeed);
this.update();
break;
}
case this.keys.LEFT: {
this.pan(this.keyPanSpeed, 0);
this.update();
break;
}
case this.keys.RIGHT: {
this.pan(- this.keyPanSpeed, 0);
this.update();
break;
}
}
};
this.onTouchStart = (event: ThreeEvent) => {
if (this.enabled === false) return;
switch (event.touches.length) {
// one-fingered touch: rotate
case 1: {
if (this.enableRotate === false) return;
this.rotateStart.set(event.touches[0].pageX, event.touches[0].pageY);
this.state = STATE.TOUCH_ROTATE;
break;
}
// two-fingered touch: dolly
case 2: {
if (this.enableZoom === false) return;
const dx = event.touches[0].pageX - event.touches[1].pageX;
const dy = event.touches[0].pageY - event.touches[1].pageY;
const distance = Math.sqrt(dx * dx + dy * dy);
this.dollyStart.set(0, distance);
this.state = STATE.TOUCH_DOLLY;
break;
}
// three-fingered touch: pan
case 3: {
if (this.enablePan === false) return;
this.panStart.set(event.touches[0].pageX, event.touches[0].pageY);
this.state = STATE.TOUCH_PAN;
break;
}
default: {
this.state = STATE.NONE;
}
}
if (this.state !== STATE.NONE) {
this.dispatchEvent(START_EVENT);
}
};
this.onTouchMove = (event: ThreeEvent) => {
if (this.enabled === false) return;
event.preventDefault();
event.stopPropagation();
switch (event.touches.length) {
// one-fingered touch: rotate
case 1: {
if (this.enableRotate === false) return;
if (this.state !== STATE.TOUCH_ROTATE) return; // is this needed?...
this.rotateEnd.set(event.touches[0].pageX, event.touches[0].pageY);
this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
const element = this.domElement === document ? this.domElement.body : this.domElement;
// rotating across whole screen goes 360 degrees around
this.rotateLeft(2 * Math.PI * this.rotateDelta.x / (element as any).clientWidth * this.rotateSpeed);
// rotating up and down along whole screen attempts to go 360, but limited to 180
this.rotateUp(2 * Math.PI * this.rotateDelta.y / (element as any).clientHeight * this.rotateSpeed);
this.rotateStart.copy(this.rotateEnd);
this.update();
break;
}
// two-fingered touch: dolly
case 2: {
if (this.enableZoom === false) return;
if (this.state !== STATE.TOUCH_DOLLY) return; // is this needed?...
// console.log( "handleTouchMoveDolly" );
const dx = event.touches[0].pageX - event.touches[1].pageX;
const dy = event.touches[0].pageY - event.touches[1].pageY;
const distance = Math.sqrt(dx * dx + dy * dy);
this.dollyEnd.set(0, distance);
this.dollyDelta.subVectors(this.dollyEnd, this.dollyStart);
if (this.dollyDelta.y > 0) {
this.dollyOut(this.getZoomScale());
} else if (this.dollyDelta.y < 0) {
this.dollyIn(this.getZoomScale());
}
this.dollyStart.copy(this.dollyEnd);
this.update();
break;
}
// three-fingered touch: pan
case 3: {
if (this.enablePan === false) return;
if (this.state !== STATE.TOUCH_PAN) return; // is this needed?...
this.panEnd.set(event.touches[0].pageX, event.touches[0].pageY);
this.panDelta.subVectors(this.panEnd, this.panStart);
this.pan(this.panDelta.x, this.panDelta.y);
this.panStart.copy(this.panEnd);
this.update();
break;
}
default: {
this.state = STATE.NONE;
}
}
};
this.onTouchEnd = (event: Event) => {
if (this.enabled === false) return;
this.dispatchEvent(END_EVENT);
this.state = STATE.NONE;
};
this.onContextMenu = event => {
event.preventDefault();
};
this.domElement.addEventListener("contextmenu", this.onContextMenu, false);
this.domElement.addEventListener("mousedown", this.onMouseDown, false);
this.domElement.addEventListener("wheel", this.onMouseWheel, false);
this.domElement.addEventListener("touchstart", this.onTouchStart, false);
this.domElement.addEventListener("touchend", this.onTouchEnd, false);
this.domElement.addEventListener("touchmove", this.onTouchMove, false);
this.window.addEventListener("keydown", this.onKeyDown, false);
// force an update at start
this.update();
}
update() {
const position = this.object.position;
this.updateOffset.copy(position).sub(this.target);
// rotate offset to "y-axis-is-up" space
this.updateOffset.applyQuaternion(this.updateQuat);
// angle from z-axis around y-axis
this.spherical.setFromVector3(this.updateOffset);
if (this.autoRotate && this.state === STATE.NONE) {
this.rotateLeft(this.getAutoRotationAngle());
}
(this.spherical as any).theta += (this.sphericalDelta as any).theta;
(this.spherical as any).phi += (this.sphericalDelta as any).phi;
// restrict theta to be between desired limits
(this.spherical as (any) as any).theta = Math.max(this.minAzimuthAngle, Math.min(this.maxAzimuthAngle, (this.spherical as any).theta));
// restrict phi to be between desired limits
(this.spherical as any).phi = Math.max(this.minPolarAngle, Math.min(this.maxPolarAngle, (this.spherical as any).phi));
this.spherical.makeSafe();
(this.spherical as any).radius *= this.scale;
// restrict radius to be between desired limits
(this.spherical as any).radius = Math.max(this.minDistance, Math.min(this.maxDistance, (this.spherical as any).radius));
// move target to panned location
this.target.add(this.panOffset);
this.updateOffset.setFromSpherical(this.spherical);
// rotate offset back to "camera-up-vector-is-up" space
this.updateOffset.applyQuaternion(this.updateQuatInverse);
position.copy(this.target).add(this.updateOffset);
this.object.lookAt(this.target);
if (this.enableDamping === true) {
(this.sphericalDelta as any).theta *= (1 - this.dampingFactor);
(this.sphericalDelta as any).phi *= (1 - this.dampingFactor);
} else {
this.sphericalDelta.set(0, 0, 0);
}
this.scale = 1;
this.panOffset.set(0, 0, 0);
// update condition is:
// min(camera displacement, camera rotation in radians)^2 > EPS
// using small-angle approximation cos(x/2) = 1 - x^2 / 8
if (this.zoomChanged ||
this.updateLastPosition.distanceToSquared(this.object.position) > EPS ||
8 * (1 - this.updateLastQuaternion.dot(this.object.quaternion)) > EPS) {
this.dispatchEvent(CHANGE_EVENT);
this.updateLastPosition.copy(this.object.position);
this.updateLastQuaternion.copy(this.object.quaternion);
this.zoomChanged = false;
return true;
}
return false;
}
panLeft(distance: number, objectMatrix) {
this.panLeftV.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
this.panLeftV.multiplyScalar(- distance);
this.panOffset.add(this.panLeftV);
}
panUp(distance: number, objectMatrix) {
this.panUpV.setFromMatrixColumn(objectMatrix, 1); // get Y column of objectMatrix
this.panUpV.multiplyScalar(distance);
this.panOffset.add(this.panUpV);
}
// deltaX and deltaY are in pixels; right and down are positive
pan(deltaX: number, deltaY: number) {
const element = this.domElement === document ? this.domElement.body : this.domElement;
if (this.object instanceof THREE.PerspectiveCamera) {
// perspective
const position = this.object.position;
this.panInternalOffset.copy(position).sub(this.target);
let targetDistance = this.panInternalOffset.length();
// half of the fov is center to top of screen
targetDistance *= Math.tan((this.object.fov / 2) * Math.PI / 180.0);
// we actually don"t use screenWidth, since perspective camera is fixed to screen height
this.panLeft(2 * deltaX * targetDistance / (element as any).clientHeight, this.object.matrix);
this.panUp(2 * deltaY * targetDistance / (element as any).clientHeight, this.object.matrix);
} else if (this.object instanceof THREE.OrthographicCamera) {
// orthographic
this.panLeft(deltaX * (this.object.right - this.object.left) / this.object.zoom / (element as any).clientWidth, this.object.matrix);
this.panUp(deltaY * (this.object.top - this.object.bottom) / this.object.zoom / (element as any).clientHeight, this.object.matrix);
} else {
// camera neither orthographic nor perspective
console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.");
this.enablePan = false;
}
}
dollyIn(dollyScale) {
if (this.object instanceof THREE.PerspectiveCamera) {
this.scale /= dollyScale;
} else if (this.object instanceof THREE.OrthographicCamera) {
this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom * dollyScale));
this.object.updateProjectionMatrix();
this.zoomChanged = true;
} else {
console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
this.enableZoom = false;
}
}
dollyOut(dollyScale) {
if (this.object instanceof THREE.PerspectiveCamera) {
this.scale *= dollyScale;
} else if (this.object instanceof THREE.OrthographicCamera) {
this.object.zoom = Math.max(this.minZoom, Math.min(this.maxZoom, this.object.zoom / dollyScale));
this.object.updateProjectionMatrix();
this.zoomChanged = true;
} else {
console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.");
this.enableZoom = false;
}
}
getAutoRotationAngle() {
return 2 * Math.PI / 60 / 60 * this.autoRotateSpeed;
}
getZoomScale() {
return Math.pow(0.95, this.zoomSpeed);
}
rotateLeft(angle: number) {
(this.sphericalDelta as any).theta -= angle;
}
rotateUp(angle: number) {
(this.sphericalDelta as any).phi -= angle;
}
getPolarAngle(): number {
return (this.spherical as any).phi;
}
getAzimuthalAngle(): number {
return (this.spherical as any).theta;
}
dispose(): void {
this.domElement.removeEventListener("contextmenu", this.onContextMenu, false);
this.domElement.removeEventListener("mousedown", this.onMouseDown, false);
this.domElement.removeEventListener("wheel", this.onMouseWheel, false);
this.domElement.removeEventListener("touchstart", this.onTouchStart, false);
this.domElement.removeEventListener("touchend", this.onTouchEnd, false);
this.domElement.removeEventListener("touchmove", this.onTouchMove, false);
document.removeEventListener("mousemove", this.onMouseMove, false);
document.removeEventListener("mouseup", this.onMouseUp, false);
this.window.removeEventListener("keydown", this.onKeyDown, false);
// this.dispatchEvent( { type: "dispose" } ); // should this be added here?
}
reset(): void {
this.target.copy(this.target0);
this.object.position.copy(this.position0);
(this.object as any).zoom = this.zoom0;
(this.object as any).updateProjectionMatrix();
this.dispatchEvent(CHANGE_EVENT);
this.update();
this.state = STATE.NONE;
}
// backward compatibility
// get center(): THREE.Vector3 {
// console.warn("THREE.OrbitControls: .center has been renamed to .target");
// return this.target;
// }
// get noZoom(): boolean {
// console.warn("THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.");
// return !this.enableZoom;
// }
// set noZoom(value: boolean) {
// console.warn("THREE.OrbitControls: .noZoom has been deprecated. Use .enableZoom instead.");
// this.enableZoom = !value;
// }
}
interface ThreeEvent extends Event {
clientX: number;
clientY: number;
deltaY: number;
button: THREE.MOUSE;
touches: Array<any>;
keyCode: number;
}
export function createOrbitControls(skinViewer: SkinViewer) {
const control = new OrbitControls(skinViewer.camera, skinViewer.renderer.domElement);
// default configuration
control.enablePan = false;
control.target = new THREE.Vector3(0, -12, 0);
control.minDistance = 10;
control.maxDistance = 256;
control.update();
return control;
}

View File

@ -5,7 +5,8 @@ export {
} from "./model";
export {
SkinViewer
SkinViewer,
SkinViewerOptions
} from "./viewer";
export {
@ -14,8 +15,13 @@ export {
} from "./orbit_controls";
export {
IAnimation,
AnimationFn,
Animation,
invokeAnimation,
AnimationHandle,
CompositeAnimation,
WalkingAnimation,
RunningAnimation,
RotatingAnimation

View File

@ -1,19 +1,19 @@
function copyImage(context, sX, sY, w, h, dX, dY, flipHorizontal) {
let imgData = context.getImageData(sX, sY, w, h);
function copyImage(context: CanvasRenderingContext2D, sX: number, sY: number, w: number, h: number, dX: number, dY: number, flipHorizontal: boolean) {
const imgData = context.getImageData(sX, sY, w, h);
if (flipHorizontal) {
for (let y = 0; y < h; y++) {
for (let x = 0; x < (w / 2); x++) {
let index = (x + y * w) * 4;
let index2 = ((w - x - 1) + y * w) * 4;
let pA1 = imgData.data[index];
let pA2 = imgData.data[index + 1];
let pA3 = imgData.data[index + 2];
let pA4 = imgData.data[index + 3];
const index = (x + y * w) * 4;
const index2 = ((w - x - 1) + y * w) * 4;
const pA1 = imgData.data[index];
const pA2 = imgData.data[index + 1];
const pA3 = imgData.data[index + 2];
const pA4 = imgData.data[index + 3];
let pB1 = imgData.data[index2];
let pB2 = imgData.data[index2 + 1];
let pB3 = imgData.data[index2 + 2];
let pB4 = imgData.data[index2 + 3];
const pB1 = imgData.data[index2];
const pB2 = imgData.data[index2 + 1];
const pB3 = imgData.data[index2 + 2];
const pB4 = imgData.data[index2 + 3];
imgData.data[index] = pB1;
imgData.data[index + 1] = pB2;
@ -30,11 +30,11 @@ function copyImage(context, sX, sY, w, h, dX, dY, flipHorizontal) {
context.putImageData(imgData, dX, dY);
}
function hasTransparency(context, x0, y0, w, h) {
let imgData = context.getImageData(x0, y0, w, h);
function hasTransparency(context: CanvasRenderingContext2D, x0: number, y0: number, w: number, h: number) {
const imgData = context.getImageData(x0, y0, w, h);
for (let x = 0; x < w; x++) {
for (let y = 0; y < h; y++) {
let offset = (x + y * w) * 4;
const offset = (x + y * w) * 4;
if (imgData.data[offset + 3] !== 0xff) {
return true;
}
@ -43,16 +43,16 @@ function hasTransparency(context, x0, y0, w, h) {
return false;
}
function computeSkinScale(width) {
function computeSkinScale(width: number) {
return width / 64.0;
}
function fixOpaqueSkin(context, width) {
function fixOpaqueSkin(context: CanvasRenderingContext2D, width: number) {
// Some ancient skins don't have transparent pixels (nor have helm).
// We have to make the helm area transparent, otherwise it will be rendered as black.
if (!hasTransparency(context, 0, 0, width, width / 2)) {
let scale = computeSkinScale(width);
let clearArea = (x, y, w, h) => context.clearRect(x * scale, y * scale, w * scale, h * scale);
const scale = computeSkinScale(width);
const clearArea = (x, y, w, h) => context.clearRect(x * scale, y * scale, w * scale, h * scale);
clearArea(40, 0, 8, 8); // Helm Top
clearArea(48, 0, 8, 8); // Helm Bottom
clearArea(32, 8, 8, 8); // Helm Right
@ -62,9 +62,9 @@ function fixOpaqueSkin(context, width) {
}
}
function convertSkinTo1_8(context, width) {
let scale = computeSkinScale(width);
let copySkin = (sX, sY, w, h, dX, dY, flipHorizontal) => copyImage(context, sX * scale, sY * scale, w * scale, h * scale, dX * scale, dY * scale, flipHorizontal);
function convertSkinTo1_8(context: CanvasRenderingContext2D, width: number) {
const scale = computeSkinScale(width);
const copySkin = (sX, sY, w, h, dX, dY, flipHorizontal) => copyImage(context, sX * scale, sY * scale, w * scale, h * scale, dX * scale, dY * scale, flipHorizontal);
fixOpaqueSkin(context, width);
@ -82,19 +82,19 @@ function convertSkinTo1_8(context, width) {
copySkin(52, 20, 4, 12, 44, 52, true); // Back Arm
}
function loadSkinToCanvas(canvas, image) {
export function loadSkinToCanvas(canvas: HTMLCanvasElement, image: HTMLImageElement) {
let isOldFormat = false;
if (image.width !== image.height) {
if (image.width === 2 * image.height) {
isOldFormat = true;
} else {
throw `Bad skin size: ${image.width}x${image.height}`;
throw new Error(`Bad skin size: ${image.width}x${image.height}`);
}
}
let context = canvas.getContext("2d");
const context = canvas.getContext("2d")!;
if (isOldFormat) {
let sideLength = image.width;
const sideLength = image.width;
canvas.width = sideLength;
canvas.height = sideLength;
context.clearRect(0, 0, sideLength, sideLength);
@ -108,20 +108,20 @@ function loadSkinToCanvas(canvas, image) {
}
}
function loadCapeToCanvas(canvas, image) {
export function loadCapeToCanvas(canvas: HTMLCanvasElement, image: HTMLImageElement) {
let isOldFormat = false;
if (image.width !== 2 * image.height) {
if (image.width * 17 == image.height * 22) {
if (image.width * 17 === image.height * 22) {
// width/height = 22/17
isOldFormat = true;
} else {
throw `Bad cape size: ${image.width}x${image.height}`;
throw new Error(`Bad cape size: ${image.width}x${image.height}`);
}
}
let context = canvas.getContext("2d");
const context = canvas.getContext("2d")!;
if (isOldFormat) {
let width = image.width * 64 / 22;
const width = image.width * 64 / 22;
canvas.width = width;
canvas.height = width / 2;
} else {
@ -132,7 +132,7 @@ function loadCapeToCanvas(canvas, image) {
context.drawImage(image, 0, 0, image.width, image.height);
}
function isSlimSkin(canvasOrImage) {
export function isSlimSkin(canvasOrImage: HTMLCanvasElement | HTMLImageElement): boolean {
// Detects whether the skin is default or slim.
//
// The right arm area of *default* skins:
@ -175,22 +175,18 @@ function isSlimSkin(canvasOrImage) {
// as transparent pixels are not allowed in the first layer.
if (canvasOrImage instanceof HTMLCanvasElement) {
let canvas = canvasOrImage;
let scale = computeSkinScale(canvas.width);
let context = canvas.getContext("2d");
let checkArea = (x, y, w, h) => hasTransparency(context, x * scale, y * scale, w * scale, h * scale);
const canvas = canvasOrImage;
const scale = computeSkinScale(canvas.width);
const context = canvas.getContext("2d")!;
const checkArea = (x, y, w, h) => hasTransparency(context, x * scale, y * scale, w * scale, h * scale);
return checkArea(50, 16, 2, 4) ||
checkArea(54, 20, 2, 12) ||
checkArea(42, 48, 2, 4) ||
checkArea(46, 52, 2, 12);
} else if (canvasOrImage instanceof HTMLImageElement) {
let image = canvasOrImage;
let canvas = document.createElement("canvas");
} else {
const image = canvasOrImage;
const canvas = document.createElement("canvas");
loadSkinToCanvas(canvas, image);
return isSlimSkin(canvas);
} else {
throw `Illegal argument: ${canvasOrImage}`;
}
}
export { isSlimSkin, loadSkinToCanvas, loadCapeToCanvas };

View File

@ -1,16 +1,51 @@
import * as THREE from "three";
import { PlayerObject } from "./model";
import { invokeAnimation } from "./animation";
import { loadSkinToCanvas,loadCapeToCanvas, isSlimSkin } from "./utils";
import { loadSkinToCanvas, loadCapeToCanvas, isSlimSkin } from "./utils";
class SkinViewer {
constructor(options) {
export interface SkinViewerOptions {
domElement: Node;
animation?: Animation;
skinUrl?: string;
capeUrl?: string;
width?: number;
height?: number;
detectModel?: boolean;
}
export class SkinViewer {
public readonly domElement: Node;
public animation: Animation | null;
public detectModel: boolean = true;
public animationPaused: boolean = false;
public animationTime: number = 0;
public disposed: boolean = false;
public readonly skinImg: HTMLImageElement;
public readonly skinCanvas: HTMLCanvasElement;
public readonly skinTexture: THREE.Texture;
public readonly capeImg: HTMLImageElement;
public readonly capeCanvas: HTMLCanvasElement;
public readonly capeTexture: THREE.Texture;
public readonly layer1Material: THREE.MeshBasicMaterial;
public readonly layer2Material: THREE.MeshBasicMaterial;
public readonly capeMaterial: THREE.MeshBasicMaterial;
public readonly scene: THREE.Scene;
public readonly camera: THREE.PerspectiveCamera;
public readonly renderer: THREE.WebGLRenderer;
public readonly playerObject: PlayerObject;
constructor(options: SkinViewerOptions) {
this.domElement = options.domElement;
this.animation = options.animation || null;
this.detectModel = options.detectModel !== false; // true by default
this.animationPaused = false;
this.animationTime = 0;
this.disposed = false;
if (options.detectModel === false) {
this.detectModel = false;
}
// texture
this.skinImg = new Image();
@ -37,7 +72,7 @@ class SkinViewer {
this.camera.position.y = -12;
this.camera.position.z = 60;
this.renderer = new THREE.WebGLRenderer({ angleRot: true, alpha: true, antialias: false });
this.renderer = new THREE.WebGLRenderer({ alpha: true, antialias: false });
this.renderer.setSize(300, 300); // default size
this.renderer.context.getShaderInfoLog = () => ""; // shut firefox up
this.domElement.appendChild(this.renderer.domElement);
@ -78,7 +113,7 @@ class SkinViewer {
if (options.width) this.width = options.width;
if (options.height) this.height = options.height;
let draw = () => {
const draw = () => {
if (this.disposed) return;
window.requestAnimationFrame(draw);
if (!this.animationPaused) {
@ -138,5 +173,3 @@ class SkinViewer {
this.setSize(this.width, newHeight);
}
}
export { SkinViewer };

4
test/shims.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
declare module "*.png" {
let content: any;
export default content;
}

View File

@ -1,9 +1,12 @@
/// <reference path="shims.d.ts"/>
import { expect } from "chai";
import * as skinview3d from "../src/skinview3d";
import skin1_8Default from "./textures/skin-1.8-default-no_hd.png";
import skin1_8Slim from "./textures/skin-1.8-slim-no_hd.png";
import skinOldDefault from "./textures/skin-old-default-no_hd.png";
import skinLegacyHatDefault from "./textures/skin-legacyhat-default-no_hd.png";
describe("detect model of texture", () => {
it("1.8 default", async () => {
@ -26,4 +29,13 @@ describe("detect model of texture", () => {
await Promise.resolve();
expect(skinview3d.isSlimSkin(image)).to.equal(false);
});
/* TODO: implement transparent hat check for 64x32 skins
it("legacy hat test", async () => {
const image = document.createElement("img");
image.src = skinLegacyHatDefault;
await Promise.resolve();
});
*/
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 526 B

View File

@ -1,5 +0,0 @@
module.exports = {
"env": {
"node": true
}
}

View File

@ -1,76 +0,0 @@
import { uglify } from "rollup-plugin-uglify";
import babel from "rollup-plugin-babel";
import resolve from "rollup-plugin-node-resolve";
import license from "rollup-plugin-license";
import fs from "fs";
let buildType = config => {
let options = {
input: "src/skinview3d.js",
output: [],
external: [
"three"
],
plugins: [
resolve()
]
};
switch (config.format) {
case "umd":
options.output.push({
format: "umd",
name: "skinview3d",
file: `build/skinview3d${config.postfix}.js`,
indent: "\t",
sourcemap: true,
globals: {
"three": "THREE"
}
});
break;
case "es":
options.output.push({
format: "es",
file: `build/skinview3d${config.postfix}.js`,
indent: "\t",
sourcemap: true,
});
break;
default:
throw `Unknown format: ${config.format}`;
}
if (config.babel) {
options.plugins.push(
babel({
exclude: "node_modules/**"
})
);
}
if (config.uglify) {
options.plugins.push(
uglify({
output: {
comments: "some"
}
})
);
}
options.plugins.push(
license({
sourcemap: true,
banner: `
skinview3d (https://github.com/to2mbn/skinview3d)
${fs.readFileSync("LICENSE").toString()}
`
})
);
return options;
};
export { buildType };

View File

@ -1,7 +0,0 @@
import { buildType } from "./rollup-util";
export default buildType({
postfix: "",
babel: true,
uglify: false,
format: "umd"
});

View File

@ -1,7 +0,0 @@
import { buildType } from "./rollup-util";
export default buildType({
postfix: ".min",
babel: true,
uglify: true,
format: "umd"
});

View File

@ -1,7 +0,0 @@
import { buildType } from "./rollup-util";
export default buildType({
postfix: ".module",
babel: true,
uglify: false,
format: "es"
});

17
tsconfig.json Normal file
View File

@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "es2015",
"target": "es5",
"declaration": true,
"strict": true,
"noImplicitAny": false,
"strictFunctionTypes": false,
"lib": [
"es2015",
"dom"
]
},
"include": [
"src/**.ts"
]
}

View File

@ -5,6 +5,16 @@
],
"jsRules": {},
"rules": {
"curly": false,
"ordered-imports": false,
"member-access": false,
"trailing-comma": [ false, {"multiline": "never", "singleline": "never"} ],
"max-line-length": false,
"variable-name": false,
"object-literal-sort-keys": false,
"arrow-parens": [true, "ban-single-arg-parens"],
"array-type": [true, "generic"],
"no-console": false,
"indent": [
true,
"tabs"

33
types/animation.d.ts vendored
View File

@ -1,33 +0,0 @@
import { PlayerObject } from "./model";
export interface IAnimation {
play(player: PlayerObject, time: number): void;
}
export type AnimationFn = (player: PlayerObject, time: number) => void;
export type Animation = AnimationFn | IAnimation;
export function invokeAnimation(
animation: Animation,
player: PlayerObject,
time: number,
): void;
export interface AnimationHandle extends IAnimation {
readonly animation: Animation;
paused: boolean;
speed: number;
reset(): void;
}
export class CompositeAnimation implements IAnimation {
constructor();
public add(animation: Animation): AnimationHandle;
public play(player: PlayerObject, time: number): void;
}
export const WalkingAnimation: AnimationFn;
export const RunningAnimation: AnimationFn;
export const RotatingAnimation: AnimationFn;

33
types/model.d.ts vendored
View File

@ -1,33 +0,0 @@
import * as THREE from "three";
export class SkinObject extends THREE.Group {
public slim: boolean;
public readonly head: THREE.Group;
public readonly body: THREE.Group;
public readonly rightArm: THREE.Group;
public readonly leftArm: THREE.Group;
public readonly rightLeg: THREE.Group;
public readonly leftLeg: THREE.Group;
constructor(
layer1Material: THREE.Material,
layer2Material: THREE.Material,
);
}
export class CapeObject extends THREE.Group {
public readonly cape: THREE.Mesh;
constructor(capeMaterial: THREE.Material);
}
export class PlayerObject extends THREE.Group {
public readonly skin: SkinObject;
public readonly cape: CapeObject;
constructor(
layer1Material: THREE.Material,
layer2Material: THREE.Material,
capeMaterial: THREE.Material,
);
}

View File

@ -1,57 +0,0 @@
import * as THREE from "three";
import { SkinViewer } from "./viewer";
export class OrbitControls {
public readonly object: THREE.Camera;
public readonly domElement: HTMLElement | HTMLDocument;
public enabled: boolean;
public target: THREE.Vector3;
public minDistance: number;
public maxDistance: number;
public minZoom: number;
public maxZoom: number;
public minPolarAngle: number;
public maxPolarAngle: number;
public minAzimuthAngle: number;
public maxAzimuthAngle: number;
public enableDamping: boolean;
public dampingFactor: number;
public enableZoom: boolean;
public zoomSpeed: number;
public enableRotate: boolean;
public rotateSpeed: number;
public enablePan: boolean;
public keyPanSpeed: number;
public autoRotate: boolean;
public autoRotateSpeed: number;
public enableKeys: boolean;
public keys: { LEFT: number, UP: number, RIGHT: number, BOTTOM: number };
public mouseButtons: { ORBIT: THREE.MOUSE, ZOOM: THREE.MOUSE, PAN: THREE.MOUSE };
constructor(object: THREE.Camera, domElement?: HTMLElement);
public getPolarAngle(): number;
public getAzimuthalAngle(): number;
public saveState(): void;
public reset(): void;
public update(): boolean;
public dispose(): void;
}
export function createOrbitControls(skinViewer: SkinViewer): OrbitControls;

View File

@ -1,5 +0,0 @@
export * from "./model";
export * from "./animation";
export * from "./viewer";
export * from "./orbit_controls";
export * from "./utils";

1
types/utils.d.ts vendored
View File

@ -1 +0,0 @@
export function isSlimSkin(skinImage: HTMLImageElement): boolean;

36
types/viewer.d.ts vendored
View File

@ -1,36 +0,0 @@
import * as THREE from "three";
import { Animation } from "./animation";
import { PlayerObject } from "./model";
export interface SkinViewerOptions {
domElement: Node;
animation?: Animation;
skinUrl?: string;
capeUrl?: string;
width?: number;
height?: number;
detectModel?: boolean;
}
export class SkinViewer {
public readonly domElement: Node;
public readonly disposed: boolean;
public width: number;
public height: number;
public skinUrl: string;
public capeUrl: string;
public animation: Animation;
public animationPaused: boolean;
public animationTime: number;
public detectModel: boolean;
public readonly playerObject: PlayerObject;
public readonly scene: THREE.Scene;
public readonly camera: THREE.PerspectiveCamera;
public readonly renderer: THREE.Renderer;
constructor(options: SkinViewerOptions);
public setSize(width: number, height: number): void;
public dispose(): void;
}