Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                //////////// BBModelLoader ////////////
//  texture_name: Specify by array such as element name ["#texture"] of Canvas or IMG
//                in the same order as the texture list of BlockBench.
//                Entities use only one texture.
//  only_visible: Load only parts with display visible is true.
BBModelLoader = function( setting ){
	this.setting = setting;
	this.filename = setting.filename;
	this.file = setting.file;
	this.only_visible = setting.only_visible;
	this.side = setting.side ? setting.side: THREE.FrontSide;
	this.sides = setting.sides;
	this.doubleFace = setting.doubleFace; //entity only
	this.useAlpha = setting.useAlpha;
	this.depthWrite = setting.depthWrite != undefined ? setting.depthWrite: true;
	this.depthTest = setting.depthTest != undefined ? setting.depthTest: true;
	this.depthcheck = setting.depthcheck != undefined ? setting.depthcheck: false;
	this.texture_name = setting.texture_name;
	this.shadow = setting.shadow != undefined ? setting.shadow: true;
	this.onload = setting.onload;
	this.receiveShadow = setting.receiveShadow != undefined ? setting.receiveShadow: false;
	this.opacity = setting.opacity != undefined ? setting.opacity: 1.0;
	this.opacities = setting.opacities;
	this.materialType = setting.materialType != undefined ? setting.materialType: 0;
	this.isBetaModel = setting.isBetaModel;
	this.diagonalStretch = setting.diagonalStretch != undefined? setting.diagonalStretch: false;
	this.parts = {};
	this.object = null;
};

// useAlpha types
BBModelLoader.alphaNone = 0;
BBModelLoader.alphaByAlpha = 1;
BBModelLoader.alphaByColor = 2;
BBModelLoader.alphaByGamma = 3;
BBModelLoader.alphaByWhite = 4;
BBModelLoader.alphaByAlpha2 = 5;
BBModelLoader.alphaByZero = 6;

// materialType types
BBModelLoader.materialDefault = 0;
BBModelLoader.materialBasic = 1;

// Only for Entity model
//Arguments:
//  filename: xxxx.bbmodel Blockbench json file
//  onload: Callback function. Do it here because it is not automatically added to the scene.
//    Return arguments:
//         object:THREE.Object3D :  Grouped objects
//         parts:{name:THREE.Object3D,...} : Associative array. Each part can be obtained by name.
BBModelLoader.prototype.loadEntity = function (onload) {
	if(onload){
		this.onload = onload;
	}
	this.meshes = [];
	this.materials = [];
	
	let load = async (data) => {
		if (data.meta && data.meta.format == "1.0" && data["cubes"] && data["outliner"]) {
			this.object = new THREE.Object3D();
			this.object.name = data.name;
			this.resolution = data.resolution ? data.resolution: {width: 64, height: 32};

			let used_child = [];
			let texture;

			if(!this.useAlpha){
				let img_elem = document.querySelector(this.texture_name[0])
				if(img_elem.tagName == "IMG"){
					///// fix image loading issue
					let loader = new THREE.TextureLoader()
					texture = loader.load(img_elem.src)
				} else {
					texture = new THREE.CanvasTexture(img_elem);
				}
				texture.magFilter = THREE.NearestFilter;
				texture.minFilter = THREE.NearestFilter;
				texture.type = THREE.FloatType;
			}
			if(this.useAlpha){
				texture = await removeAlpha(document.querySelector(this.texture_name[0]));
				this.alphaMap = await createAlphaMap(document.querySelector(this.texture_name[0]), this.opacity, this.useAlpha);
			}
			let setting = { map: texture, side: this.side };
			setting.depthWrite = this.depthWrite ? this.depthWrite: false;
			setting.depthTest = this.depthTest != undefined ? this.depthTest: true;
			if(this.useAlpha){
				setting.transparent = true;
				setting.alphaMap = this.alphaMap;
			} else {
				setting.transparent = false;
				setting.alphaTest = 0.0001;
				setting.opacity = this.opacity;
			}
			this.materials[0] = this.materialType ? new THREE.MeshBasicMaterial( setting ) : new THREE.MeshLambertMaterial( setting )

			data.outliner.forEach(outline => {
				if (!this.only_visible || outline.visibility != false) {
					// outliner
					let outliner = new THREE.Object3D();
					outliner.name = outline.name;
					outliner.userDara.uuid = outline.uuid;
					let origin = [
						(outline.origin ? outline.origin[0] : 0),
						(outline.origin ? outline.origin[1] : 0),
						(outline.origin ? outline.origin[2] : 0),
					];
					data.cubes.forEach(element => {
						if (outline.children.indexOf(element.uuid) > -1 && (!this.only_visible || element.visibility != false)) {
							// cube
							let size = [
								Math.abs(element.from[0] - element.to[0]),
								Math.abs(element.from[1] - element.to[1]),
								Math.abs(element.from[2] - element.to[2])
							];
							let uv_offset = [
								element.uv_offset ? element.uv_offset[0] : 0,
								element.uv_offset ? element.uv_offset[1] : 0
							];
							let isCube = size[0] && size[1] && size[2];
							let flip = false || element.shade == false;
							let inflate = (element.inflate ? element.inflate : 0) * 2;

							let mesh = new THREE.Mesh(
								new THREE.MCBoxGeometry(size[0], size[1], size[2], inflate, uv_offset[0], uv_offset[1], data.resolution.width, data.resolution.height, flip, this.doubleFace, !this.depthcheck, this.isBetaModel),
								this.materials
							);
							
							mesh.receiveShadow = this.receiveShadow;
							mesh.castShadow = this.receiveShadow;
							mesh.geometry.translate(origin[0], origin[1], origin[2]);
							mesh.name = element.name;

							this.meshes.push(mesh);

							let cube = new THREE.Object3D();
							cube.add(mesh);
							cube.visible = element.visibility != false;
							cube.name = element.name;
							cube.userData.uuid = element.uuid;
							cube.userDara.parent = outliner.userDara.uuid;
							let center = [
								element.from[0] + size[0] / 2,
								element.from[1] + size[1] / 2,
								element.from[2] + size[2] / 2
							];
							let pos = [
								center[0] - origin[0],
								center[1] - origin[1],
								center[2] - origin[2]
							];
							cube.position.set(-pos[0], pos[1], -pos[2]);
							outliner.add(cube);

							//child added
							used_child.push(element.uuid);
						}
					});
					if (outline["rotation"]) {
						let axis = new THREE.Vector3(1, 0, 0);
						outliner.rotateOnWorldAxis(axis, deg2rad(-outline.rotation[0]));
						axis.set(0, 1, 0);
						outliner.rotateOnWorldAxis(axis, deg2rad(outline.rotation[1]));
						axis.set(0, 0, 1);
						outliner.rotateOnWorldAxis(axis, deg2rad(-outline.rotation[2]));
					}
					if (outline["origin"]) {
						//outliner.position.set(-origin[0], origin[1], -origin[2]);
					}
					this.parts[outliner.name] = outliner;
					this.object.add(outliner);
				}

			});
		}
		if (data.meta && data.meta.format_version >= 3 && data["elements"] && data["outliner"]) {
			this.object = new THREE.Object3D();
			this.object.name = data.name;
			this.resolution = data.resolution ? data.resolution: {width: 64, height: 32};

			this.zrotflip = (data.meta.format_version > 3.1);

			let cubes = [];
			let texture
			
			let img_elem = document.querySelector(this.texture_name[0])
			if(img_elem.tagName == "IMG"){
				///// fix image loading issue
				let loader = new THREE.TextureLoader()
				texture = loader.load(img_elem.src)
			} else {
				texture = new THREE.CanvasTexture(img_elem);
			}
			texture.magFilter = THREE.NearestFilter;
			texture.minFilter = THREE.NearestFilter;
			texture.type = THREE.FloatType;

			let alphaMap = null;
			if(this.useAlpha){
				alphaMap = await createAlphaMap(document.querySelector(this.texture_name[0]), this.opacity, this.useAlpha);
			}

			let setting = { map: texture, side: this.side };
			setting.depthWrite = this.depthWrite != undefined ? this.depthWrite: false;
			setting.depthTest = this.depthTest != undefined ? this.depthTest: true;
			if(this.useAlpha){
				setting.transparent = true;
				setting.alphaMap = alphaMap;
			} else {
				//if(!this.opacity){
					setting.transparent = false;
					setting.alphaTest = 0.0001;
				//} else {
				//	setting.transparent = true;
					setting.opacity = this.opacity;
				//}
			}
			this.materials[0] = this.materialType ? new THREE.MeshBasicMaterial( setting ) : new THREE.MeshLambertMaterial( setting )
			this.materials[0].name = data.name + "_mtl"
			 
			data.elements.forEach(element => {
				if ((!this.only_visible || element.visibility != false) && element.type != "locator") {

					// cube
					let size = [
						Math.abs(element.from[0] - element.to[0]),
						Math.abs(element.from[1] - element.to[1]),
						Math.abs(element.from[2] - element.to[2])
					];
					let uv_offset = [
						element.uv_offset ? element.uv_offset[0] : 0,
						element.uv_offset ? element.uv_offset[1] : 0
					];
					let isCube = size[0] && size[1] && size[2];
					let flip = false || element.shade == false;
					let inflate = (element.inflate ? element.inflate : 0) * 2;

					let mesh = new THREE.Mesh(
						new THREE.MCBoxGeometry(size[0], size[1], size[2], inflate, uv_offset[0], uv_offset[1], data.resolution.width, data.resolution.height, flip, this.doubleFace, !this.depthcheck, this.isBetaModel),
						this.materials
					);

					let center = [
						element.from[0] + size[0] / 2,
						element.from[1] + size[1] / 2,
						element.from[2] + size[2] / 2
					];
					let origin = [
						(element.origin ? element.origin[0] : center[0]),
						(element.origin ? element.origin[1] : center[1]),
						(element.origin ? element.origin[2] : center[2]),
					];
					let pos = [
						center[0] - origin[0],
						center[1] - origin[1],
						center[2] - origin[2],
					];

					mesh.position.set(-pos[0], pos[1], -pos[2]);
					mesh.name = element.name;
					this.meshes.push(mesh);

					let cube = new THREE.Object3D();
					cube.userData.origin = origin;
					cube.add(mesh);
					cube.visible = element.visibility != false;
					cube.name = element.name;
					cube.userData.uuid = element.uuid;
					cube.userData.children = [];
					cube.userData.center = origin;
					cube.position.set(-pos[0], pos[1], -pos[2]);
					if (element["rotation"]) {
						let axis = new THREE.Vector3(1, 0, 0);
						cube.rotateOnWorldAxis(axis, deg2rad(-element.rotation[0]));
						axis.set(0, 1, 0);
						cube.rotateOnWorldAxis(axis, deg2rad(element.rotation[1]));
						axis.set(0, 0, 1);
						cube.rotateOnWorldAxis(axis, deg2rad(-element.rotation[2] * (this.zrotflip? -1: 1)));
					}
					cubes.push(cube);
				}
			});
			
			data.outliner.forEach(outline => {
				appendChild.call(this, outline, this.object);

				function appendChild(json, owner){
					if (!this.only_visible || outline.visibility != false) {
						// outliner
						let outliner = new THREE.Object3D();
						outliner.name = json.name;
						outliner.userData.uuid = json.uuid;

						let origin = [
							(json.origin ? json.origin[0]: 0),
							(json.origin ? json.origin[1]: 0),
							(json.origin ? json.origin[2]: 0),
						];
						outliner.userData.origin = origin;
						if (json["rotation"]) {
							let axis = new THREE.Vector3(1, 0, 0);
							outliner.rotateOnWorldAxis(axis, deg2rad(-json.rotation[0]));
							axis.set(0, 1, 0);
							outliner.rotateOnWorldAxis(axis, deg2rad(json.rotation[1]));
							axis.set(0, 0, 1);
							outliner.rotateOnWorldAxis(axis, deg2rad(json.rotation[2] * (this.zrotflip? -1: 1)));
						}
						let pos = origin;
						if(owner && owner.userData.origin){
							pos = [
								origin[0] - owner.userData.origin[0],
								origin[1] - owner.userData.origin[1],
								origin[2] - owner.userData.origin[2]
							];
						}
						outliner.position.set(-pos[0], pos[1], -pos[2]);
						outliner.userData.center = pos;
						this.parts[outliner.name] = outliner;
						owner.add(outliner);
						
						//append child
						json.children.forEach(child => {
							if(typeof child === "string"){
								let child_uuid = child;
								cubes.forEach( cube => {
									if(cube.userData.uuid == child_uuid){
										let pos = [
											cube.userData.center[0] - outliner.userData.origin[0],
											cube.userData.center[1] - outliner.userData.origin[1],
											cube.userData.center[2] - outliner.userData.origin[2]
										];
										cube.position.set(-pos[0], pos[1], -pos[2]);
										cube.userData.parent = outliner.userData.uuid;
										outliner.add(cube);
									}
								});
							} else {
								appendChild.call(this, child, outliner);
							}
						});
					}
				}
			});
		}
		if (typeof this.onload === "function") {
			this.onload.call(this, this.object, this.parts);
		}
	}

	if(typeof this.filename == "string"){
		let self = this;
		$.getJSON(this.filename, function(data){
			load.call(self, data)
		});
	} else if( this.file instanceof Blob ){
		let self = this;
		let reader = new FileReader();
		reader.onload = function() {
			load.call(self, JSON.parse(this.result));
		}
		reader.readAsText(this.file);
	}

	return this;
}

// Only for Block model
//Arguments:
//  filename: xxxx.bbmodel Blockbench json file
//  onload: Callback function. Do it here because it is not automatically added to the scene.
//    Return arguments:
//         object:THREE.Object3D :  Grouped objects
//         parts:{name:THREE.Object3D,...} : Associative array. Each part can be obtained by name.
BBModelLoader.prototype.loadBlock = function (onload) {
	if(onload){
		this.onload = onload;
	}

	if(this.shadow == undefined || this.shadow == true) {
		this.shadow = []
		for(let i=0; i<this.texture_name.length; i++){
			this.shadow.push(true)
		}
	}

	let load = async function(data){
		
		if(this.texture_name.length < this.tex_length) throw "not enough textures.";

		if (data.meta && data.meta.format_version >= 3 && data.meta.model_format == "java_block" && data["elements"] && data["outliner"]) {
			
			this.tex_length = data.textures.length
			this.format = data.meta.model_format
			this.textures = data.textures
			this.userData = {}

			this.object = new THREE.Object3D();
			this.object.name = data.name;

			this.resolution = data.resolution ? data.resolution: {width: 16, height: 16};
			tex_sizes = [];

			this.materials = [];

			if(this.texture_name.length < this.tex_length){
				console.log("Not enough image")
				return undefined;
			}

			for(let i=0; i<this.tex_length; i++){
				let texture
				let setting = { transparent: false, side: this.sides ? this.sides[i]: this.side, name: data.textures[i].id };
				if(this.useAlpha && (this.useAlpha[i] || this.useAlpha > 0)){
					let img = document.querySelector(this.texture_name[i]);
					
					tex_sizes.push( {width: this.resolution.width, height: (img.height / img.width) * this.resolution.width} );
					setting.map = await removeAlpha(img);
					setting.transparent = true;
					setting.depthWrite = this.depthWrite ? this.depthWrite: false;
					setting.depthTest = this.depthTest != undefined ? this.depthTest: true;
					setting.premultipliedAlpha = true;
					setting.alphaMap = await createAlphaMap(img, this.opacities ? this.opacities[i]: this.opacity, this.useAlpha.length ? this.useAlpha[i] : this.useAlpha);
				} else {
					let img = document.querySelector(this.texture_name[i]);

					if(img){
						if(img.tagName == "IMG"){
							///// fix image loading issue
							let loader = new THREE.TextureLoader()
							texture = loader.load(img.src)
							tex_sizes.push( {width: this.resolution.width, height: (img.height / img.width) * this.resolution.width} );
						} else {
							texture = await removeAlpha2(img)
							tex_sizes.push( {width: this.resolution.width, height: (img.height / img.width) * this.resolution.width} );
						}
						texture.magFilter = THREE.NearestFilter;
						texture.minFilter = THREE.NearestFilter;
						texture.type = THREE.FloatType;

						setting.map = texture;
					} else {
						tex_sizes.push( {width: 16, height: 16} );
					}
					setting.transparent = false;
					setting.alphaTest = 0.5;
				}
				this.materials.push(
					this.shadow[i] ? new THREE.MeshLambertMaterial( setting ): new THREE.MeshBasicMaterial( setting )
				);
			}

			////// Cube Loading
			this.elements = data.elements;
			let cubes = [];
			this.meshes = [];
			data.elements.forEach(element => {
				if (!this.only_visible || element.visibility != false) {
					let origin = [
						(element.origin ? element.origin[0] : 8),
						(element.origin ? element.origin[1] : 8),
						(element.origin ? element.origin[2] : 8),
					];

					let size = [
						Math.abs(element.from[0] - element.to[0]),
						Math.abs(element.from[1] - element.to[1]),
						Math.abs(element.from[2] - element.to[2])
					];

					let isPlane = false;
					{
						size.forEach(axis => {
							if(axis == 0){
								isPlane = true
							}
						});
					}

					let mesh = new THREE.Mesh(
						new THREE.MCBoxGeometryUV({size: size, resolution: this.resolution, faces: element.faces, tex_sizes: tex_sizes}),
						this.materials
					);
					mesh.userData.faces = element.faces;
					mesh.userData.size = size;
					mesh.name = element.name
					this.meshes.push(mesh);
					
					let cube = new THREE.Object3D();
					cube.add(mesh);
					cube.visible = element.visibility != false;
					cube.name = element.name;
					cube.userData.uuid = element.uuid;
					cube.userData.origin = origin;

					let center = [
						element.from[0] + size[0] / 2,
						element.from[1] + size[1] / 2,
						element.from[2] + size[2] / 2
					];

					cube.userData.center = center;

					let pos = [
						center[0] - origin[0],
						center[1] - origin[1],
						center[2] - origin[2]
					];

					mesh.position.set(pos[0], pos[1], pos[2]);
					if(element["inflate"]){
						mesh.scale.set(1 + element.inflate, 1 + element.inflate, 1 + element.inflate)
					}

					if (element["rotation"]) {
						let axis = new THREE.Vector3(1, 0, 0);
						cube.rotateOnWorldAxis(axis, deg2rad(element.rotation[0]));
						axis.set(0, 1, 0);
						cube.rotateOnWorldAxis(axis, deg2rad(element.rotation[1]));
						if (isPlane && this.diagonalStretch){
							let scale = ((element.rotation[1] % 90) / 45) * 1.41;
							if(size[0] == 0){
								mesh.scale.z = mesh.scale.z * scale;
							} else
							if(size[2] == 0){
								mesh.scale.x = mesh.scale.x * scale;
							}
						}
						axis.set(0, 0, 1);
						cube.rotateOnWorldAxis(axis, deg2rad(element.rotation[2]));
						cube.userData.rotation = element.rotation;
					}

					//cube.position.set(origin[0], origin[1], origin[2]);
					
					this.parts[cube.name] = cube;
					cubes.push(cube);
					this.object.add(cube);
				}
			});

			// append outliners
			data.outliner.forEach(outline => {
				appendChild.call(this, outline, this.object);

				function appendChild(json, owner){
					if (typeof json === "object" && (!this.only_visible || outline.visibility != false)) {
						// outliner
						let outliner = new THREE.Object3D();
						outliner.name = json.name;
						outliner.userData.uuid = json.uuid;

						let origin = [
							(json.origin ? json.origin[0] - 8 : 8),
							(json.origin ? json.origin[1] - 8 : 8),
							(json.origin ? json.origin[2] - 8 : 8),
						];
						outliner.userData.origin = origin;
						if (json["rotation"]) {
							let axis = new THREE.Vector3(1, 0, 0);
							outliner.rotateOnWorldAxis(axis, deg2rad(json.rotation[0]));
							axis.set(0, 1, 0);
							outliner.rotateOnWorldAxis(axis, deg2rad(json.rotation[1]));
							axis.set(0, 0, 1);
							outliner.rotateOnWorldAxis(axis, deg2rad(json.rotation[2]));
						}
						let pos = origin;
						if(owner && owner.userData.origin){
							pos = [
								origin[0] - owner.userData.origin[0],
								origin[1] - owner.userData.origin[1],
								origin[2] - owner.userData.origin[2]
							];
						}
						outliner.position.set(-pos[0], pos[1], -pos[2]);
						outliner.userData.center = pos;
						this.parts[outliner.name] = outliner;
						owner.add(outliner);
						
						if(!json.children) return;

						//append child
						json.children.forEach(child => {
							if(typeof child === "string"){
								let child_uuid = child;
								cubes.forEach( cube => {
									if(cube.userData.uuid == child_uuid){
										cube.position.set(
											cube.userData.origin[0],
											cube.userData.origin[1],
											cube.userData.origin[2]
										);
										outliner.add(cube);
									}
								});
							} else {
								appendChild.call(this, child, outliner);
							}
						});
					} else 
					if(typeof json === "string"){
						let child_uuid = json;
						cubes.forEach( cube => {
							if(cube.userData.uuid == child_uuid){
								cube.position.set(
									cube.userData.origin[0],
									cube.userData.origin[1],
									cube.userData.origin[2]
								);
								owner.add(cube);
							}
						});
					}
				}
			});

			this.object.children.forEach(child => {
				resetOrigin( child, [8, 8, 8] );
				function resetOrigin(member, origin){
					if(member.type == "Object3D"){
						let pos = member.position;
						member.position.set(pos.x - origin[0], pos.y - origin[1], pos.z - origin[1]);
						if(member.children){
							member.children.forEach( (child2) => resetOrigin(child2, member.userData.origin) );
						}
					}
				}
			});

		}

		if (typeof onload === "function") {
			onload.call(this, this.object, this.parts);
		}
	}

	if(typeof this.filename == "string"){
		let self = this;
		$.getJSON(this.filename, function(data){
			load.call(self, data)
		});
	} else if( this.file instanceof Blob ){
		let self = this;
		let reader = new FileReader();
		reader.onload = function() {
			load.call(self, JSON.parse(this.result));
		}
		reader.readAsText(this.file);
	}

	return this;
}

BBModelLoader.prototype.recalcUV = function(images){
	if(this.format != "java_block") throw "not a block model.";
	if(this.tex_length > images.length) throw "not enough textures.";
	
	let tex_sizes = []
	for(let i=0; i<this.tex_length; i++){
		let img = images[i] instanceof Image || images[i] instanceof HTMLCanvasElement ? images[i] : document.querySelector(images[i]);
		tex_sizes.push( {width: img.width, height: img.height} );
	}
	
	this.meshes.forEach(mesh => {
		mesh.geometry.dispose()
		mesh.geometry = new THREE.MCBoxGeometryUV({size: mesh.userData.size, resolution: this.resolution, faces: mesh.userData.faces, tex_sizes: tex_sizes})
	})
	return this;
}

BBModelLoader.prototype.recalcEntityUV = function(animate_count){
	this.meshes.forEach(mesh => {
		mesh.geometry.faceVertexUvs[0].forEach( uv => {
			uv.forEach( vector => {
				vector.y = vector.y / animate_count + (animate_count - 1) / animate_count;
			})
		})
	})
}

BBModelLoader.prototype.constructor = BBModelLoader;

//// MISC Utils /////////////////////////////////////////////////////////////

function createCanvas(width, height) {
	let canvas = document.createElement("canvas");
	canvas.setAttribute("width", width);
	canvas.setAttribute("height", height);
	canvas.width = width;
	canvas.height = height;
	let context = canvas.getContext('2d');
	context.imageSmoothingEnabled = false;
	return { canvas: canvas, context: context }
}

// IMG->Canvas converter
function imageToCanvas(element, isBlock) {
	var img = document.querySelector(element);
	return imageToCanvas2(img, isBlock);
}

// IMG->Canvas converter
function imageToCanvas2(img, isBlock) {
	var canvas = createCanvas(img.width, isBlock ? img.width: img.height);
	canvas.context.clearRect(0, 0, img.width, isBlock ? img.width: img.height);
	canvas.context.drawImage(img, 0, 0, img.width, isBlock ? img.width: img.height, 0, 0, img.width, isBlock ? img.width: img.height);
	return canvas.canvas;
}

// Create a monotone texture for an alpha map from a canvas with an alpha channel
async function createAlphaMap(canvas, opacity, alphaType, isBlock) {
	if(!canvas) return;
	let img;
	let img_ctx;
	let isImage;
	if(canvas.tagName == "IMG" || canvas.src){
		isImage = true;
		let tmp = createCanvas(canvas.width, isBlock ? canvas.width: canvas.height);
		img = tmp.canvas;
		img_ctx = tmp.context;
		tmp.context.clearRect(0, 0, img.width, img.height);
		tmp.context.drawImage(canvas, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
	} else {
		isImage = false;
		img = canvas;
		img_ctx = img.getContext('2d');
	}
	opacity = opacity? opacity: 1;
	let img_data = img_ctx.getImageData(0, 0, img.width, img.height);
	let texture_canvas = createCanvas(img.width, img.height);
	let crop = value => value < 256? value: 255;
	for (let x = 0; x < img.width; x++) {
		for (let y = 0; y < img.height; y++) {
			let d = (x + y * img_data.width) * 4;
			let data = img_data.data;
			if(alphaType == BBModelLoader.alphaByColor){
				if(data[d + 3] > 0){
					let alpha = ((data[d + 0] + data[d + 1] + data[d + 2]) / 3) / 255;
					let gamma = data[d + 3] / 255
					alpha = Math.pow(alpha, gamma) * 255
					data[d + 0] = Math.floor(crop(alpha * opacity));
					data[d + 1] = Math.floor(crop(alpha * opacity));
					data[d + 2] = Math.floor(crop(alpha * opacity));
				} else {
					data[d + 0] = 0;
					data[d + 1] = 0;
					data[d + 2] = 0;
				}
			} else if(alphaType == BBModelLoader.alphaByGamma){
				if(data[d + 3] > 0){
					let alpha = ((data[d + 0] + data[d + 1] + data[d + 2]) / 3) / 255;
					let gamma = data[d + 3] / 255
					alpha = Math.pow(alpha, gamma / 100) * 255
					data[d + 0] = Math.floor(crop(alpha * gamma * opacity));
					data[d + 1] = Math.floor(crop(alpha * gamma * opacity));
					data[d + 2] = Math.floor(crop(alpha * gamma * opacity));
				} else {
					data[d + 0] = 0;
					data[d + 1] = 0;
					data[d + 2] = 0;
				}
			} else if(alphaType == BBModelLoader.alphaByWhite){
				let min = Math.min(data[d + 0], data[d + 1], data[d + 2])
				let max = Math.max(data[d + 0], data[d + 1], data[d + 2])
				if(data[d + 3] > 0 && data[d + 0] > 0 && max - min < 4){
					let alpha = ((data[d + 0] + data[d + 1] + data[d + 2]) / 3) / 255;
					alpha = data[d + 0]
					data[d + 0] = Math.floor(crop(alpha * opacity));
					data[d + 1] = Math.floor(crop(alpha * opacity));
					data[d + 2] = Math.floor(crop(alpha * opacity));
				} else {
					data[d + 0] = 0;
					data[d + 1] = 0;
					data[d + 2] = 0;
					data[d + 3] = 0;
				}
			} else if(alphaType == BBModelLoader.alphaByAlpha2){
				let alpha = crop(data[d + 3] / (255 * opacity) * 255 + (255 * opacity - 255))
				data[d + 0] = Math.floor(alpha);
				data[d + 1] = Math.floor(alpha);
				data[d + 2] = Math.floor(alpha);
			} else if(alphaType == BBModelLoader.alphaByZero){
				let alpha = data[d + 3] > 0 ? 255 : 0;
				data[d + 0] = Math.floor(alpha);
				data[d + 1] = Math.floor(alpha);
				data[d + 2] = Math.floor(alpha);
			} else {
				data[d + 0] = Math.floor(crop(data[d + 3] * opacity));
				data[d + 1] = Math.floor(crop(data[d + 3] * opacity));
				data[d + 2] = Math.floor(crop(data[d + 3] * opacity));
			}
			data[d + 3] = 255;
		}
	}
	texture_canvas.context.putImageData(img_data, 0, 0);
	
	if(isImage){ img.remove() }
	let texture = new THREE.CanvasTexture(texture_canvas.canvas);
	texture.magFilter = THREE.NearestFilter;
	texture.minFilter = THREE.NearestFilter;
	texture.type = THREE.FloatType;
	return texture;
}

async function removeAlpha(canvas, isBlock) {
	if(!canvas) return;
	let img;
	let img_ctx;
	let isImage;
	if(canvas.tagName == "IMG" || canvas.src){
		canvas = await imageReLoader(canvas)
		isImage = true;
		let tmp = createCanvas(canvas.width, isBlock ? canvas.width: canvas.height);
		img = tmp.canvas;
		img_ctx = tmp.context;
		tmp.context.clearRect(0, 0, img.width, img.height);
		tmp.context.drawImage(canvas, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
	} else {
		isImage = false;
		img = canvas;
		img_ctx = img.getContext('2d');
	}
	let img_data = img_ctx.getImageData(0, 0, img.width, img.height);
	let texture_canvas = createCanvas(img.width, img.height);
	for (let x = 0; x < img.width; x++) {
		for (let y = 0; y < img.height; y++) {
			let d = (x + y * img_data.width) * 4;
			let data = img_data.data;
			if(data[d + 3] > 0) data[d + 3] = 255;
		}
	}
	texture_canvas.context.putImageData(img_data, 0, 0);
	
	if(isImage){ img.remove() }
	let texture = new THREE.CanvasTexture(texture_canvas.canvas);
	texture.magFilter = THREE.NearestFilter;
	texture.minFilter = THREE.NearestFilter;
	texture.type = THREE.FloatType;
	return texture;
}

async function removeAlpha2(canvas, isBlock) {
	if(!canvas) return;
	let img;
	let img_ctx;
	let isImage;
	if(canvas.tagName == "IMG" || canvas.src){
		canvas = await imageReLoader(canvas)
		isImage = true;
		let tmp = createCanvas(canvas.width, isBlock ? canvas.width: canvas.height);
		img = tmp.canvas;
		img_ctx = tmp.context;
		tmp.context.clearRect(0, 0, img.width, img.height);
		tmp.context.drawImage(canvas, 0, 0, img.width, img.height, 0, 0, img.width, img.height);
	} else {
		isImage = false;
		img = canvas;
		img_ctx = img.getContext('2d');
	}
	let img_data = img_ctx.getImageData(0, 0, img.width, img.height);
	let texture_canvas = createCanvas(img.width, img.height);
	for (let x = 0; x < img.width; x++) {
		for (let y = 0; y < img.height; y++) {
			let d = (x + y * img_data.width) * 4;
			let data = img_data.data;
			data[d + 3] = data[d + 3] > 128 ? 255: 0;
		}
	}
	texture_canvas.context.putImageData(img_data, 0, 0);
	
	if(isImage){ img.remove() }
	let texture = new THREE.CanvasTexture(texture_canvas.canvas);
	texture.magFilter = THREE.NearestFilter;
	texture.minFilter = THREE.NearestFilter;
	texture.type = THREE.FloatType;
	return texture;
}

async function imageReLoader(img, src){
	img = await (
		()=> new Promise(resolve => {
			img.bak = src ? src: img.src
			img.src = ""
			img.onload = () => resolve(img)
			img.src = img.bak
		})
	)()
	return img
}

// Returns radians from an angle
function deg2rad(deg) {
	return deg * (Math.PI / 180)
}

function rad2deg(rad) {
	return rad / (Math.PI / 180)
}

THREE.Euler.prototype.toDeg = function(){
	return {x: rad2deg(this.x), y: rad2deg(this.y), z: rad2deg(this.z) }
}

THREE.Object3D.prototype.lookAt2 = function(targetPosition) {
    var targetPos = this.worldToLocal(targetPosition.clone());
    var rotationAxis = new THREE.Vector3().crossVectors(
        new THREE.Vector3(0, 0, 1),
        targetPos
    ).normalize();
    var angle = new THREE.Vector3(0, 0, 1).angleTo(targetPos.normalize().clone());

	this.rotateOnAxis(rotationAxis, angle);
}

// For texture dyeing
function dye_color(dest_canvas, src_canvas, dye_color, opacity, isBlock) {
	opacity = opacity ? opacity : 1;
	let power = 1;
	let src_img = document.querySelector(src_canvas);
	let isNotCanvas = src_img.tagName == "IMG";
	if(isNotCanvas){
		src_img = imageToCanvas(src_canvas);
	}
	let temp_canvas = document.querySelector(dest_canvas);
	let w = src_img.width, h = (isBlock ? src_img.width: src_img.height);
	temp_canvas.setAttribute("width", w);
	temp_canvas.setAttribute("height", h);
	let temp_ctx = temp_canvas.getContext("2d");
	temp_ctx.clearRect(0, 0, w, h);
	let src_ctx = src_img.getContext("2d");
	let img_data = src_ctx.getImageData(0, 0, w, h);
	for (let x = 0; x < w; x++) {
		for (let y = 0; y < h; y++) {
			let d = (x + y * img_data.width) * 4;
			let data = img_data.data;
			if (data[d + 3] > 0) {
				let default_col = { r: dye_color >> 16, g: (dye_color >> 8) & 0xFF, b: dye_color & 0xFF };
				let color = { r: data[d], g: data[d + 1], b: data[d + 2] };
				data[d + 0] = default_col.r * power * (color.r / 255);
				data[d + 1] = default_col.g * power * (color.g / 255);
				data[d + 2] = default_col.b * power * (color.b / 255);

				let alpha = data[d + 3] * opacity;
				data[d + 3] = alpha < 255 ? alpha : 255;
			}
		}
	}
	temp_ctx.putImageData(img_data, 0, 0);
	if(isNotCanvas){
		src_img.remove();
	}
}

///////// Promise version ///////////////
BBModelLoader.InitPromise = function(option){
	this.loader = new BBModelLoader(option)
	return this;
}
BBModelLoader.InitPromise.prototype.loadEntity = function(){
	return new Promise(resolve => {
		this.loader.loadEntity(function(object, parts){
			resolve({loader: this, object: object, parts: parts})
		})
	})
}
BBModelLoader.InitPromise.prototype.loadBlock = function(){
	return new Promise(resolve => {
		this.loader.loadBlock(function(object, parts){
			resolve({loader: this, object: object, parts: parts})
		})
	})
}
BBModelLoader.InitPromise.prototype.constructor = BBModelLoader.InitPromise;

              
            
!
999px

Console