Code viewer for World: Cool light

// Cloned by Mathias Bazin on 20 Jun 2018 from World "First Person Night" by Mathias Bazin 
// Please leave this clone trail here.
 


// Cloned by Mathias Bazin on 19 Jun 2018 from World "First Person Controls" by Mathias Bazin 
// Please leave this clone trail here.
 


// Customise AB run parameters (optional).
// The following parameters can be customised. (They have default values.)

AB.clockTick       = 20;    

	// Speed of run: Step every n milliseconds. Default 100.
	
AB.maxSteps        = 65545;    

	// Length of run: Maximum length of run in steps. Default 1000.

AB.screenshotStep  = 1000;   
  
	// For automatic generation of World images.
	// Take screenshot on this step. (All resources should have finished loading.) Default 50.


const skyboxConst = 1000;

const MOVESPEED = 3;

const boxtexturefile = "/uploads/mathias/wood.png"
const floorTextureFile = "/uploads/mathias/grassLowPoly1.png"
const skytexturefile = "/uploads/mathias/nightSky2.jpg"

//==============================================================================
//  Define the THREE.PointerLockControls class, source at https://threejs.org/
//==============================================================================

THREE.PointerLockControls = function ( camera ) {

	var scope = this;

	camera.rotation.set( 0, 0, 0 );

	var pitchObject = new THREE.Object3D();
	pitchObject.add( camera );

	var yawObject = new THREE.Object3D();
	yawObject.position.y = 10;
	yawObject.add( pitchObject );

	var PI_2 = Math.PI / 2;

	var onMouseMove = function ( event ) {

		if ( scope.enabled === false ) return;

		var movementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
		var movementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;

		yawObject.rotation.y -= movementX * 0.002;
		pitchObject.rotation.x -= movementY * 0.002;

		pitchObject.rotation.x = Math.max( - PI_2, Math.min( PI_2, pitchObject.rotation.x ) );

	};

	this.dispose = function () {

		document.removeEventListener( 'mousemove', onMouseMove, false );

	};

	document.addEventListener( 'mousemove', onMouseMove, false );

	this.enabled = false;

	this.getObject = function () {

		return yawObject;

	};

	this.getDirection = function () {

		// assumes the camera itself is not rotated

		var direction = new THREE.Vector3( 0, 0, - 1 );
		var rotation = new THREE.Euler( 0, 0, 0, 'YXZ' );

		return function ( v ) {

			rotation.set( pitchObject.rotation.x, yawObject.rotation.y, 0 );

			v.copy( direction ).applyEuler( rotation );

			return v;

		};

	}();

};
//=====================================================================



function World() { 

    var camera, controls;

	var objects = [];

	var raycaster;
	
	var controlsEnabled = true;

    var moveForward = false;
	var moveBackward = false;
	var moveLeft = false;
	var moveRight = false;
	var canJump = false;

	var prevTime = performance.now();
	var velocity = new THREE.Vector3();
	var direction = new THREE.Vector3();
	var vertex = new THREE.Vector3();
	var color = new THREE.Color();
	
	var angle = 0;
	
	this.newRun = function()
	{
	    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 100000 );
        threeworld.camera = camera;
	    threeworld.init3d ( 0,0, 0x000000  ); 

	   // threehandler.initMouseDrag     = function(){};
	   // threehandler.mouseDrag     = function(){};
	   // threehandler.mouseZoom     = function(){};
	    
	    var light = new THREE.PointLight(0xffffff, 1.5, 1000);
	   // light.position.set(0,60,0);
        camera.add(light);
		
        controls = new THREE.PointerLockControls( camera );
        threeworld.scene.add( controls.getObject() );
        
        var onKeyDown = function ( event ) {
            
            console.log("velocity ", velocity.x, " ", velocity.z)
	    	switch ( event.keyCode ) {

				case 38: // up
				case 87: // w
					moveForward = true;
					break;

				case 37: // left
				case 65: // a
					moveLeft = true; break;

				case 40: // down
				case 83: // s
					moveBackward = true;
					break;

				case 39: // right
				case 68: // d
					moveRight = true;
					break;

				case 32: // space
					if ( canJump === true ) velocity.y += 350;
					canJump = false;
					break;

			}

		};

		var onKeyUp = function ( event ) {

			switch( event.keyCode ) {

				case 38: // up
				case 87: // w
					moveForward = false;
					break;

				case 37: // left
				case 65: // a
					moveLeft = false;
					break;

				case 40: // down
				case 83: // s
					moveBackward = false;
                    break;

				case 39: // right
				case 68: // d
					moveRight = false;
					break;

			}

		};

		document.addEventListener( 'keydown', onKeyDown, false );
		document.addEventListener( 'keyup', onKeyUp, false );
		
		raycaster = new THREE.Raycaster( new THREE.Vector3(), new THREE.Vector3( 0, - 1, 0 ), 0, 10 );


        //Scene
        
        
	    //floor
	    
	    var floorGeometry = new THREE.PlaneBufferGeometry( 6000, 6000, 200, 200 );
        floorGeometry.rotateX( - Math.PI / 2 );
        var floorTexture = new THREE.ImageUtils.loadTexture ( floorTextureFile );
        floorTexture.minFilter = THREE.LinearFilter;
        floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
        floorTexture.offset.set( 0, 0 );
        floorTexture.repeat.set( 100, 100 );
        var floor = new THREE.Mesh(floorGeometry, new THREE.MeshStandardMaterial({map : floorTexture}));
        floor.position.set(0,-20,0);
        threeworld.scene.add(floor);

        //Background (sky)
        
        var loader = new THREE.TextureLoader();
        loader.load( skytexturefile, function ( texture ) {

            var geometry = new THREE.SphereGeometry( 30000, 32, 32 );
            var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
            var mesh = new THREE.Mesh( geometry, material );
            mesh.material.side = THREE.BackSide;
            
            threeworld.scene.add( mesh );
            

        } );


        
        //Objects
        
        //box
        var boxGeometry = new THREE.BoxBufferGeometry( 20, 20, 20 );
        var boxTexture = new THREE.ImageUtils.loadTexture ( boxtexturefile );
        var boxMaterial = new THREE.MeshStandardMaterial ( { map: boxTexture } );   
        var box = new THREE.Mesh ( boxGeometry, boxMaterial);
        box.metalness = 0.0;
        box.position.set(0,50,0);
        box.name = "Box";
        
        threeworld.scene.add(box);
        objects.push(box);
        
        
        //Sun
        
        var sun =  new THREE.PointLight(0xffffff, 100, Infinity);
        sun.position.set(0, Math.cos(angle)*10, Math.sin(angle)*10);
        threeworld.scene.add(sun);
        var pointLightHelper = new THREE.PointLightHelper( sun, 1000 );
        threeworld.scene.add( pointLightHelper );
        
	    $("#user_span1").html(" Use WASD or Arrows to move, mouse to look around and space to jump.");
	    
	    var blocker = $("#user_span2");
	    blocker.html("<p><b>Click screen to enable mouse controls</b></p>");

	    
	    //lock pointer
	    var havePointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
        console.log(havePointerLock);
        if ( havePointerLock ) {

			var element = document.body;

			var pointerlockchange = function ( event ) {

				if ( document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element ) {

					controlsEnabled = true;
					controls.enabled = true;
					blocker.html("");

				} else
				    
				{
					controls.enabled = false;
					blocker.html("<p><b>Click screen to enable mouse controls</b></p>");

				}

			};

			var pointerlockerror = function ( event ) {

				console.error("pointerlockerror");

			};

			// Hook pointer lock state change events
			document.addEventListener( 'pointerlockchange', pointerlockchange, false );
			document.addEventListener( 'mozpointerlockchange', pointerlockchange, false );
			document.addEventListener( 'webkitpointerlockchange', pointerlockchange, false );

			document.addEventListener( 'pointerlockerror', pointerlockerror, false );
			document.addEventListener( 'mozpointerlockerror', pointerlockerror, false );
			document.addEventListener( 'webkitpointerlockerror', pointerlockerror, false );

			document.addEventListener( 'click', function ( event ) {

				// Ask the browser to lock the pointer
				element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
				element.requestPointerLock();

			}, false );

		} else {

			$("#user_span1").html('<p>Your browser doesn\'t seem to support Pointer Lock API</p>');

		}
		

	};


	this.nextStep = function()		 
	{
	    
// 	    console.log("camera pos : ", camera.getWorldPosition().x, camera.getWorldPosition().y, camera.getWorldPosition().z);
// 		for (let o of objects)
// 		{
// 		    console.log(o.name, " pos :", o.getWorldPosition().x,o.getWorldPosition().y,o.getWorldPosition().z);
// 		}
		
		previousPosition = controls.getObject().position;
		
		if ( controlsEnabled === true ) {

			raycaster.ray.origin.copy( controls.getObject().position );
			raycaster.ray.origin.y -= 10;

			var intersections = raycaster.intersectObjects( objects );

			var onObject = intersections.length > 0;

			var time = performance.now();
			var delta = ( time - prevTime ) / 1000;

			velocity.x -= velocity.x * 10.0 * delta;
	    	velocity.z -= velocity.z * 10.0 * delta;

			velocity.y -= 9.8 * 100.0 * delta; // 100.0 = mass

			direction.z = Number( moveForward ) - Number( moveBackward );
			direction.x = Number( moveLeft ) - Number( moveRight );
			direction.normalize(); // this ensures consistent movements in all directions

			if ( moveForward || moveBackward ) velocity.z -= direction.z * 400.0 * MOVESPEED * delta;
			if ( moveLeft || moveRight ) velocity.x -= direction.x * 400.0 * MOVESPEED * delta;

			if ( onObject === true ) {

				velocity.y = Math.max( 0, velocity.y );
				canJump = true;

			}
            
            // console.log("velocity ", velocity.x, " ", velocity.z)
            
			controls.getObject().translateX( velocity.x * delta );
			controls.getObject().translateY( velocity.y * delta );
			controls.getObject().translateZ( velocity.z * delta );

			if ( controls.getObject().position.y < 10 ) {

				velocity.y = 0;
				controls.getObject().position.y = 10;

				canJump = true;

			}

			prevTime = time;
			
			if (previousPosition.distanceTo(controls.getObject().position) > 30)
			{
			    console.error("Teleport occured");
			}

		}
	
	};


	this.endRun = function()
	{
	};

}