Demo entry 6344897

PWS

   

Submitted by anonymous on Jan 26, 2017 at 20:30
Language: HTML. Code size: 23.5 kB.

<html>
	<head>
		<title>Model</title>
		<style>

			body {
                            background:#000;
                            color:#fff;
                            padding:0;
                            margin:0;
                            overflow:hidden;
                            font-size: 12px;
                            font-family: -apple-system;
                            text-align: center;
			}
                        .newpresetform, .newsphereform {
                            display:none;
                            text-align: left !important;
                        }
                        #gui { position: absolute; top: 10px; right: 2px }
			canvas { width: 100%; height: 100% }
		</style>
	</head>
	<body>
            <p id="result"></p>
            <div id="gui">
                <div class="newsphereform">
                    Name:<input type="text" id="newSphereName"><br>
                    Template sphere<select id="templateSphere">
                    </select>
                <br>
                <button type="button" onclick="addSphere()">Create</button>
                <button type="button" onclick="showForm(1, 'newsphereform')">Close</button><br>
                </div>
                
                <div class="newpresetform">
                    Name:<input type="text" id="newPresetName"><br>
                    Template preset:<select id="templatePreset">
                    </select>
                <br>
                <button type="button" onclick="addPreset()">Create</button>
                <button type="button" onclick="showForm(1, 'newpresetform')">Close</button><br>
                </div>
                
                <select id="presetSelect" onChange="changePreset()">
                </select>
                <button type="button" onclick="showForm(0, 'newpresetform')">New Preset</button><br>
                <button type="button" onclick="showForm(0, 'newsphereform')">Add Sphere</button>
                <button type="button" onclick="Storage()">Save</button>
                <button type="button" onclick="resetLocalStorage()">Reset</button>
            </div>
                
		<script src="build/three.js"></script>
                <script src="build/stats.min.js"></script>
                <script src="build/dat.gui.min.js"></script>
                <script src="presets.js"></script>
		<script>
            //alle variabelen aanmaken die nodig zijn in meerdere functies
            var container, stats, camera, scene, renderer, interval, i, j, k, l, m, gui, option, test, cameraVector;
            var xx = 0;
            var p = 0;
            var doPhysics = false;
            var sphere = [];
            var light = [];
            var vector = [];
            var distanceValue = [];
            var distanceVector = [];
            var forceValue = [];
            var forceVector = [];
            var forceTotal = [];
            var velocity = [];
            var geometry = [];
            var material = [];
            var sf = [];
            var sfDynamic = [];
            var sfStatic = [];
            var sfPosition = [];
            var sfVelocity = [];
            init();
            InitGUI();
            function Storage() {
                // Check browser support
                if (typeof(Storage) !== "undefined") {
                    // Store
                    for(i = l; i < presets.length; i++){
                        for(j in presets[i]){
                            localStorage.setItem("presets[" + i + "]." + j, presets[i][j]);
                        }
                        for(j in presets[i].sphere){
                            for(k in presets[i].sphere[j]){
                                localStorage.setItem("presets[" + i + "].sphere[" + j + "]." + k, presets[i].sphere[j][k]);
                            }
                            for(k in presets[i].sphere[j].colour){
                                localStorage.setItem("presets[" + i + "].sphere[" + j + "].colour[" + k + "]", presets[i].sphere[j].colour[k]);
                            }
                            for(k in presets[i].sphere[j].velocity){
                                localStorage.setItem("presets[" + i + "].sphere[" + j + "].velocity." + k, presets[i].sphere[j].velocity[k]);
                            }
                        }
                        for(j in presets[i].camera){
                            localStorage.setItem("presets[" + i + "].camera." + j, presets[i].camera[j]);
                        }
                    }
                } else {
                    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
                }   
            }
            
            function resetLocalStorage() {
                if (confirm("Are you sure? All your created presets will be permanently be deleted!") === true) {
                    localStorage.clear();
                    sessionStorage.setItem("selectedPreset", 0);
                    location.reload();
                };
            }
            
            function changePreset() {
                // Check browser support
                if (typeof(Storage) !== "undefined") {
                    // Store
                    sessionStorage.setItem("selectedPreset", presetSelect.selectedIndex);
                    Storage();
                    location.reload();
                } else {
                    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
                }
            };
            
            function showForm(j, k) {
                var editStyle = document.querySelectorAll("." + k);
                for(i = 0; i < editStyle.length; i++ ){
                    switch(j){
                        case 0:
                            editStyle[i].style.display = "inline";
                            break;
                        case 1:
                            editStyle[i].style.display = "none";
                            break;
                    };        
                };
            }
            
            function addSphere() {
                i = presets[p].sphere.length;
                if(i === 0){
                    presets[p].sphere[i] = Object.assign({}, presets[0].sphere[0]);
                } else{
                    presets[p].sphere[i] = Object.assign({}, presets[p].sphere[templateSphere.selectedIndex]);
                }
                presets[p].sphere[i].name = document.getElementById('newSphereName').value;
                presets[p].sphere[i].x = 0;
                presets[p].sphere[i].y = 0;
                presets[p].sphere[i].z = 0;
                presets[p].sphere[i].velocity.x = 0;
                presets[p].sphere[i].velocity.y = 0;
                presets[p].sphere[i].velocity.z = 0;
                Storage();
                location.reload();
            };

            
            function addPreset() {
                i = presets.length;
                presets[i] = Object.assign({}, presets[templatePreset.selectedIndex]);
                localStorage.setItem("templatePreset", templatePreset.selectedIndex);
                presets[i].name = document.getElementById('newPresetName').value;
                option = document.createElement("option");
                option.text = presets[i].name;
                presetSelect.add(option);
                presetSelect.selectedIndex = presets.length -1;
                // Check browser support
                if (typeof(Storage) !== "undefined") {
                    // Store
                        localStorage.setItem("localPresetsAmount", parseFloat(localStorage.localPresetsAmount) + 1);
                    for(j in presets[i]){
                        localStorage.setItem("presets[" + i + "]." + j, presets[i][j]);
                    }
                    for(j in presets[i].sphere){
                        for(k in presets[i].sphere[j]){
                            localStorage.setItem("presets[" + i + "].sphere[" + j + "]." + k, presets[i].sphere[j][k]);
                        }
                        for(k in presets[i].sphere[j].colour){
                            localStorage.setItem("presets[" + i + "].sphere[" + j + "].colour[" + k + "]", presets[i].sphere[j].colour[k]);
                        }
                        for(k in presets[i].sphere[j].velocity){
                            localStorage.setItem("presets[" + i + "].sphere[" + j + "].velocity." + k, presets[i].sphere[j].velocity[k]);
                        }
                    }
                    for(j in presets[i].camera){
                        localStorage.setItem("presets[" + i + "].camera." + j, presets[i].camera[j]);
                    }
                    changePreset();
                } else {
                    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
                }
            }
            
            function cameraUpdate() {
                if( presets[p].look >= 0 ) {
                    //camera mee laten bewegen met object op afstand
                    camera.position.x = sphere[presets[p].look].position.x - 20 * presets[p].sphere[presets[p].look].radius;
                    camera.position.y = sphere[presets[p].look].position.y + 10 * presets[p].sphere[presets[p].look].radius ;
                    camera.position.z = sphere[presets[p].look].position.z - 20 * presets[p].sphere[presets[p].look].radius ;
                    camera.lookAt(sphere[presets[p].look].position); //camera gericht houden op object
                } else {
                    camera.position.x = presets[p].camera.x;
                    camera.position.y = presets[p].camera.y;
                    camera.position.z = presets[p].camera.z;
                    camera.lookAt(scene.position);
                }
            }
            
            function init( ) {
                
                //localstorage presets toevoegen
                i = l = presets.length;
                while( localStorage.hasOwnProperty("presets[" + i + "].name") ){
                    presets[i] = {};
                    for(j in presets[0]){
                        if(j === "name"){
                            presets[i][j] = localStorage["presets[" + i + "]." + j];
                        } else {
                            presets[i][j] = parseFloat(localStorage["presets[" + i + "]." + j]);
                        }
                    }
                    presets[i].sphere = [];
                    j = 0;
                    while( localStorage.hasOwnProperty("presets[" + i + "].sphere[" + j + "].name") ){
                        presets[i].sphere[j] = {};
                        for(k in presets[0].sphere[0]){
                            if(k === "name"){
                                presets[i].sphere[j][k] = localStorage["presets[" + i + "].sphere[" + j + "]." + k];
                            }else{
                                presets[i].sphere[j][k] = parseFloat(localStorage["presets[" + i + "].sphere[" + j + "]." + k]);
                            }
                        }
                        presets[i].sphere[j].colour = [];
                        for(k in presets[0].sphere[0].colour){
                            presets[i].sphere[j].colour[k] = parseFloat(localStorage["presets[" + i + "].sphere[" + j + "].colour[" + k + "]"]);
                        }
                        presets[i].sphere[j].velocity = {};
                        for(k in presets[0].sphere[0].velocity){
                            presets[i].sphere[j].velocity[k] = parseFloat(localStorage["presets[" + i + "].sphere[" + j + "].velocity." + k]);
                        }
                        j += 1;
                    }
                    presets[i].camera = {};
                    for(j in presets[0].camera){
                        presets[i].camera[j] = parseFloat(localStorage["presets[" + i + "].camera." + j]);
                    }
                    i += 1;
                }
                document.getElementById("newPresetName").value = "Preset " + presets.length;
                
                for(i = 0; i < presets.length; i++){
                    option = document.createElement("option");
                    option.text = presets[i].name;
                    presetSelect.add(option);
                }
                if(!sessionStorage.hasOwnProperty("selectedPreset")){
                    sessionStorage.setItem("selectedPreset", 3);
                }
                p = presetSelect.selectedIndex = parseFloat(sessionStorage.selectedPreset);
               
                //opties aan select template preset toevoegen
                for(i = 0; i < presets.length; i++){
                    option = document.createElement("option");
                    option.text = presets[i].name;
                    templatePreset.add(option);
                }
                //opties aan select template sphere toevoegen
                for(i = 0; i < presets[p].sphere.length; i++){
                    option = document.createElement("option");
                    option.text = presets[p].sphere[i].name;
                    templateSphere.add(option);
                }
                window.addEventListener("keydown",  function (e) {
                    if (e.keyCode === 32) {
                        if ( doPhysics === true ) {               
                            doPhysics = false;
                       } else {
                           doPhysics = true;
                       }
                    }
                });

                //scene toevoegen
                scene = new THREE.Scene();
                
                //camera toevoegen
                camera = new THREE.PerspectiveCamera( 75 , window.innerWidth/window.innerHeight, 1, Math.pow(10, 15) );
                camera.position.x = presets[p].camera.x;
                camera.position.y = presets[p].camera.y;
                camera.position.z = presets[p].camera.z;
                cameraVector = new THREE.Vector3(camera.position.x, camera.position.y, camera.position.z);
                camera.lookAt(scene.position);
                
                //renderer toevoegen
                renderer = new THREE.WebGLRenderer( { antialias: true , logarithmicDepthBuffer: true } );
                renderer.setPixelRatio( window.devicePixelRatio );
                renderer.setSize( window.innerWidth, window.innerHeight );

                //fps counter toevoegen
                container = document.createElement( 'div' );
                document.body.appendChild( container );
                container.appendChild( renderer.domElement );
                stats = new Stats();
                container.appendChild( stats.dom );

                //objecten aanmaken en toevoegen aan scene
                for ( i = 0; i < presets[p].sphere.length; i++) {
                    var colour = new THREE.Color("rgb(" + presets[p].sphere[i].colour[0] + "," + presets[p].sphere[i].colour[1] + "," + presets[p].sphere[i].colour[2] + ")" );
                    if ( presets[p].sphere[i].type > 0 ) {
                        light[i] = new THREE.PointLight( 0xffffff, 1, 0 );
                        scene.add( light[i] );
                        material[i] = new THREE.MeshBasicMaterial( { color: colour } );
                    } else {
                        material[i] = new THREE.MeshLambertMaterial( { color: colour } );
                    }
                    geometry[i] = new THREE.SphereBufferGeometry( presets[p].sphere[i].radius, 60, 60);
                    sphere[i] = new THREE.Mesh(geometry[i], material[i] );
                    scene.add(sphere[i]);
                    sphere[i].position.x = presets[p].sphere[i].x;
                    sphere[i].position.y = presets[p].sphere[i].y;
                    sphere[i].position.z = presets[p].sphere[i].z;
                    if(presets[p].sphere[i].type > 0) {
                        light[i].position.copy( sphere[i].position );
                    }
                    //vectoren aanmaken voor alle objecten
                    distanceValue[i] = [];
                    distanceVector[i] = [];
                    forceValue[i] = [];
                    forceVector[i] = [];
                    forceTotal[i] = new THREE.Vector3();
                    velocity[i] = new THREE.Vector3(presets[p].sphere[i].velocity.x, presets[p].sphere[i].velocity.y, presets[p].sphere[i].velocity.z);

                    for(j = 0; j < presets[p].sphere.length; j++) {
                        if( j !== i ) {
                            distanceVector[i][j] = new THREE.Vector3();
                            forceVector[i][j] = new THREE.Vector3();
                        }
                    }
                }
                
                //interval tussen renders en dt berekenen
                interval = Math.pow(10, presets[p].c) / presets[p].fps;
                
                cameraUpdate();
                
                //de loop die het programma runt
                setInterval( render , 1000 / presets[p].fps );
                
            }
            function InitGUI() {
                gui = new dat.GUI( { autoPlace: false } );
                var guiContainer = document.getElementById('gui');
                guiContainer.appendChild(gui.domElement);
                dynamic = gui.addFolder('Dynamic');
                dynamic.open();
                static = gui.addFolder('Static');
                static.open();

                for(i = 0; i < presets[p].sphere.length; i++) {
                    sf[i] = gui.addFolder(presets[p].sphere[i].name);
                    sfDynamic[i] = sf[i].addFolder('Dynamic');
                    sfDynamic[i].open();
                    sfStatic[i] = sf[i].addFolder('Static');
                    sfStatic[i].open();
                    sfDynamic[i].add(presets[p].sphere[i], 'mass', 0, 10*presets[p].sphere[i].mass);
                    sfStatic[i].add(presets[p].sphere[i], 'radius');
                    sfStatic[i].addColor(presets[p].sphere[i], 'colour');
                    sfStatic[i].add(presets[p].sphere[i], 'type');
                    
                    sfPosition[i] = sfStatic[i].addFolder('Starting position');
                    sfPosition[i].add(presets[p].sphere[i], 'x');
                    sfPosition[i].add(presets[p].sphere[i], 'y');
                    sfPosition[i].add(presets[p].sphere[i], 'z');
                    
                    sfVelocity[i] = sfStatic[i].addFolder('Velocity');
                    sfVelocity[i].add(presets[p].sphere[i].velocity, 'x');
                    sfVelocity[i].add(presets[p].sphere[i].velocity, 'y');
                    sfVelocity[i].add(presets[p].sphere[i].velocity, 'z');
                };
                
                var lookGUI = {
                    Scene: '-1'
                };
                
                for(i = 0; i < presets[p].sphere.length; i++) {
                    lookGUI[presets[p].sphere[i].name] = i;
                }
                dynamic.add(presets[p], 'look', lookGUI);
                static.add(presets[p], 'fps', 0).step(0.01);
                static.add(presets[p], 'c', 1).step(0.01).name("c in 10log");
                sfCamera = dynamic.addFolder('Camera');
                sfCamera.add(presets[p].camera, 'x');
                sfCamera.add(presets[p].camera, 'y');
                sfCamera.add(presets[p].camera, 'z');
                
            }
            
            function physics() {
                //vectoren aanmaken op posities van objecten
                for (i = 0; i < presets[p].sphere.length; i++) {
                    vector[i] = new THREE.Vector3( sphere[i].position.x, sphere[i].position.y, sphere[i].position.z );
                }
                
                for (i = 0; i < presets[p].sphere.length; i++) {
                    for ( j = 0; j < presets[p].sphere.length; j++ ) {
                        if(j !== i) {
                            //afstand tussen objecten i en j als waarde
                            distanceValue[i][j] = vector[i].distanceTo(vector[j]);
                            
                            //afstand tussen objecten i en j als vector door vector van object j van de vector van object i af te trekken
                            distanceVector[i][j].subVectors(vector[j] , vector[i]);
                            
                            //kracht tussen objecten i en j als waarde met formule Fg = G * m1 * m2 / r ^ 2
                            forceValue[i][j] = G * presets[p].sphere[i].mass * presets[p].sphere[j].mass /  Math.pow( distanceValue[i][j], 2 );
                            
                            //kracht tussen objecten i en j als waarde omrekenen tot vector
                            forceVector[i][j].copy(distanceVector[i][j].divideScalar(distanceValue[i][j]/forceValue[i][j]));
                            
                            //krachtsvectoren optellen
                            forceTotal[i].add(forceVector[i][j]);
                        }
                    }
                    
                    //snelheid object berekenen met formules a = F / m en dv = v + a * dt
                    velocity[i].add(forceTotal[i].multiplyScalar(interval / presets[p].sphere[i].mass ));
                }
                
                //positie van objecten berekenen met formule dx = x + v * dt 
                for ( i = 0; i < presets[p].sphere.length; i ++ ) {
                    sphere[i].position.x += velocity[i].x*interval;
                    sphere[i].position.y += velocity[i].y*interval;
                    sphere[i].position.z += velocity[i].z*interval;
                    
                };

                cameraUpdate();
            }
            function render() {
                if (doPhysics === true) {
                    xx += 1;
                    if(xx === 5){
                        xx = 0;
                        for( i = 0; i < presets[p].sphere.length; i++){
                            var yMaterial = new THREE.PointsMaterial( {color: 0xffffff, size: cameraVector.distanceTo(vector[i])/100 });
                            var yGeometry = new THREE.Geometry();
                            yGeometry.vertices[i] = (new THREE.Vector3(sphere[i].position.x, sphere[i].position.y, sphere[i].position.z) );
                            var y = new THREE.Points( yGeometry, yMaterial );
                            scene.add(y);
                        }  
                    }
                                        physics();
                }

                //fps-counter updaten en scene en camera renderen
                stats.update();
                
                renderer.render(scene, camera);
			}
        </script>
	</body>
</html>

This snippet took 0.05 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).