Related
I am creating a game where players can move around from first-person perspective, where the ground is generated with Perlin noise and therefore uneven. I would like to simulate gravity in the game. Hence, a raycasting thing has been implemented, which is supposed to find the player's distance from the ground and stop them from falling when they hit the ground. Here is my code (if the snipper is unclear visit https://3d.211368e.repl.co):
const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000000000000), renderer = new THREE.WebGLRenderer(), canvas = renderer.domElement;
camera.rotation.order = "YXZ";
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
document.body.appendChild(canvas);
const light = new THREE.DirectionalLight( 0xffffff, 1);
light.position.set(0, 10000, 0);
light.castShadow = true;
light.shadow.camera.top = 10000;
light.shadow.camera.right = 10000;
light.shadow.camera.bottom = -10000;
light.shadow.camera.left = -10000;
light.shadow.camera.far = 100000;
wwwww
scene.add(light);
var sky = new THREE.Mesh(new THREE.SphereGeometry(100000, 3, 3, 0, Math.PI, 0, Math.PI), new THREE.MeshBasicMaterial({color: 0x579ebb}));
sky.material.side = THREE.BackSide;
sky.rotateX(-Math.PI / 2);
scene.add(sky);
class Vector2{
constructor(x, y){
this.x = x;
this.y = y;
}
dot(other){
return this.x * other.x + this.y * other.y;
}
}
function Shuffle(tab){
for(let e = tab.length-1; e > 0; e--){
let index = Math.round(Math.random() * (e-1)),
temp = tab[e];
tab[e] = tab[index];
tab[index] = temp;
}
}
function MakePermutation(){
let P = [];
for(let i = 0; i < 256; i++){
P.push(i);
}
Shuffle(P);
for(let i = 0; i < 256; i++){
P.push(P[i]);
}
return P;
}
let P = MakePermutation();
function GetConstantVector(v){
let h = v & 3;
if(h == 0) return new Vector2(1.0, 1.0);
if(h == 1) return new Vector2(-1.0, 1.0);
if(h == 2) return new Vector2(-1.0, -1.0);
return new Vector2(1.0, -1.0);
}
function Fade(t){
return ((6 * t - 15) * t + 10) * t ** 3;
}
function Lerp(t, a1, a2){
return a1 + t*(a2-a1);
}
function Noise2D(x, y){
let X = Math.floor(x) & 255;
let Y = Math.floor(y) & 255;
let xf = x - Math.floor(x);
let yf = y - Math.floor(y);
let topRight = new Vector2(xf - 1, yf - 1);
let topLeft = new Vector2(xf, yf - 1);
let bottomRight = new Vector2(xf - 1, yf);
let bottomLeft = new Vector2(xf, yf);
let valueTopRight = P[P[X+1]+Y+1];
let valueTopLeft = P[P[X]+Y+1];
let valueBottomRight = P[P[X+1]+Y];
let valueBottomLeft = P[P[X]+Y];
let dotTopRight = topRight.dot(GetConstantVector(valueTopRight));
let dotTopLeft = topLeft.dot(GetConstantVector(valueTopLeft));
let dotBottomRight = bottomRight.dot(GetConstantVector(valueBottomRight));
let dotBottomLeft = bottomLeft.dot(GetConstantVector(valueBottomLeft));
let u = Fade(xf);
let v = Fade(yf);
return Lerp(u, Lerp(v, dotBottomLeft, dotTopLeft), Lerp(v, dotBottomRight, dotTopRight));
}
const plane = new THREE.Mesh(new THREE.PlaneGeometry(10000, 10000, 500, 500), new THREE.MeshPhongMaterial({color: 0x00aa00}));
plane.rotateX(-Math.PI / 2 + 0.00001);
plane.receiveShadow = true;
for (let y = 0, i = 0; y < 501; y++){
for(let x = 0; x < 501; x++, i++){
let n = 0.0, a = 1.0, f = 0.005;
for (let o = 0; o < 3; o++){
let v = a*Noise2D(x*f, y*f);
n += v;
a *= 0.5;
f *= 2.0;
}
n += 1;
n /= 2;
plane.geometry.vertices[i].z = n * 1000;
}
}
scene.add(plane);
const point = plane.geometry.vertices[Math.floor(Math.random() * 1000)];
camera.position.set(point.x, point.z + 2, point.y);
const geo = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshBasicMaterial({color: 0xff0000}));
geo.castShadow = true;
scene.add(geo);
const render = () => {
requestAnimationFrame(render);
const below = new THREE.Vector3(camera.position.x, -1000000, camera.position.y), cast = new THREE.Raycaster(camera.position, below), intersect = cast.intersectObject(plane);
if (intersect.length > 0){
if (intersect[0].distance < 3) camera.translateY(-1);
}else{
camera.translateY(-1);
}
renderer.render(scene, camera);
}
render();
onmousemove = () => {
if (camera.rotation._x > -0.8 || camera.rotation._y > -0.8){
camera.rotateX(-Math.atan(event.movementY / 300));
camera.rotateY(-Math.atan(event.movementX / 300));
}else{
if (Math.atan(event.movementY / 300) < 0) camera.rotateX(-Math.atan(event.movementY / 300));
if (Math.atan(event.movementX / 300) < 0) camera.rotateY(-Math.atan(event.movementX / 300));
}
camera.rotation.z = 0;
}
onresize = () => {
renderer.setSize(window.innerWidth, window.innerHeight);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
onkeydown = (event) => {
if (event.key == "w") camera.translateZ(-10);
if (event.key == "a") camera.translateX(-1);
if (event.key == "s") camera.translateZ(1);
if (event.key == "d") camera.translateX(1);
if (event.key == "ArrowUp") camera.translateY(1);
if (event.key == "ArrowDown") camera.translateY(-1);
}
body{
margin: 0;
background-color: black;
overflow: hidden;
}
canvas{
border: none;
}
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/utils/SceneUtils.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/libs/dat.gui.min.js"></script>
If the ground is not detected at least 3 units below the camera, the player will continue falling. However, sometimes nothing is spotted below the camera, while the player is clearly hovering over the ground. This is extremely frustrating. Is there any reliable alternative method to solve this problem, such as using something other than raycasting? Or is there a bug in the code? TIA
See the Raycaster documentation. The constructor takes the origin, the direction and near and far parameters. So you could do:
const gravityDirection = new THREE.Vector3(0, -1, 0);
cast = new THREE.Raycaster(camera.position, gravityDirection, 0, 3);
and this also makes the distance check redundant, as the far parameter already filters out hits further away than 3 units.
Im trying to clone this website : https://art4globalgoals.com/
Well, I've implement scratch card as below, but I can't figure out how to automatically
trigger dragging event on screen, and erase it. I've read Pixi document about renderer or sprite, but couldn't find idea about it....
I'll be very grateful if you guys give any hint or suggestion or examples about it..
Also, I want to rotate my brush depending of my movement of mouse.
The idea was to create a vector of my mouse movement, and make a dot product with vector of (1,0) then get the angle, then apply rotation by angle. but whenever I apply angle to it, result seems chaotic.
below , is my code, and results(without rotation applied , with rotation applied)
import * as PIXI from 'pixi.js';
import { Point } from '#pixi/math';
let currentVector = new Point(1, 0);
currentVector = currentVector.set(1, 0);
const screenSize = {
width: window.innerWidth,
height: window.innerHeight
};
let brushWidth = (window.innerHeight / window.innerWidth) * 150;
let brushHeight = (window.innerHeight / window.innerWidth) * 200;
const app = new PIXI.Application({
width: window.innerWidth,
height: window.innerHeight,
resolution: window.devicePixelRatio,
autoDensity: true
});
document.body.appendChild(app.view);
app.loader
.add('background', '/jpeg/mask.jpeg')
.add('mask', '/png/effel-gray.png')
.add('bristle1', '/png/brush6.png')
.add('bristle2', '/png/bristle2.png')
.load(() => {
setup();
});
const setup = () => {
const brushTexture = app.loader.resources.bristle1.texture;
// const brushTexture2 = app.loader.resources.bristle2.texture;
const brush = new PIXI.Sprite(brushTexture);
// const brush2 = new PIXI.Sprite(brushTexture2);
brush.width = brushWidth;
brush.height = brushHeight;
brush.anchor.set(0.5, 0.5);
// brush2.width = brushWidth;
// brush2.height = brushHeight;
const backgroundTexture = app.loader.resources.background.texture;
const maskTexture = app.loader.resources.mask.texture;
const background = new PIXI.Sprite(backgroundTexture);
background.x = app.renderer.screen.width / 2;
background.y = app.renderer.screen.height / 2;
background.anchor.x = 0.5;
background.anchor.y = 0.5;
background.width = window.innerWidth;
background.height = window.innerHeight;
const mask = new PIXI.Sprite(maskTexture);
mask.width = app.renderer.screen.width;
mask.height = app.renderer.screen.height;
mask.x = app.renderer.screen.width / 2;
mask.y = app.renderer.screen.height / 2;
mask.anchor.x = 0.5;
mask.anchor.y = 0.5;
mask.width = window.innerWidth;
mask.height = window.innerHeight;
app.stage.addChild(mask);
app.stage.addChild(background);
const renderTexture = PIXI.RenderTexture.create(app.screen.width, app.screen.height);
const renderTextureSprite = new PIXI.Sprite(renderTexture);
app.stage.addChild(renderTextureSprite);
background.mask = renderTextureSprite;
app.stage.interactive = true;
app.stage.on('pointerdown', pointerDown);
app.stage.on('pointerup', pointerUp);
app.stage.on('pointermove', pointerMove);
let dragging = false;
let bristle2Render = false;
let vector;
function pointerMove(event) {
if (dragging) {
brush.position.copyFrom(event.data.global);
brush.width += 1;
const vx = event.data.global.x - currentVector.x;
const vy = event.data.global.y - currentVector.y;
vector = new Point(vx, vy);
vector = vector.set(vx, vy);
const dotProd = vector.x;
const magnitude = Math.sqrt(vector.x * vector.x + vector.y * vector.y);
const angle = Math.acos(dotProd / magnitude);
currentVector = currentVector.set(event.data.global.x, event.data.global.y);
app.renderer.render(
brush,
{
renderTexture,
transform: new PIXI.Matrix().rotate(angle),
clear: false
},
false,
null,
false
);
// if (bristle2Render) {
// brush2.position.copyFrom(event.data.global);
// app.renderer.render(brush2, renderTexture, false, null, false);
// }
// if (brush.width === 100) {
// dragging = false;
// brushWidth = 0;
// }
}
}
function pointerDown(event) {
dragging = true;
pointerMove(event);
}
function pointerUp(event) {
dragging = false;
bristle2Render = false;
brush.width = brushWidth;
}
window.addEventListener('resize', () => {
screenSize.width = window.innerWidth;
screenSize.height = window.innerHeight;
app.renderer.resize(window.innerWidth, window.innerHeight);
app.renderer.stage.width = window.innerWidth;
app.renderer.stage.height = window.innerHeight;
});
};
You can switch between data visualization in the web application. It first loads the map in this case is that still and image, when you join the page for the first time. As an user you have the option to choose between subject map still an image and the three.js data visualization. But when I run the code of the three.js somehow the <select> with <option> elements are not responding any more. but the <input class="form-check-input" type="checkbox" value="comp_exercise" id=""> still works and is select able. it happened after I used orbit control from the three.js library.
So far I have tried to remove all the event.preventDefault(); but it made no difference. also I have looked in the console if the canvas was overlapping the select element what it was not. the console is not returning any errors and changing the css or position on the web page of the select element does not make a difference either.
the expected is that the <select> still works after the three.js codes get runs so that you can change metric but it is not clickable anymore and left click does not work either
the html code thats not working anymore after the three.js codes get runs:
<div class="form-group">
<label for="exampleFormControlSelect1">Main metric</label>
<select class="form-control" id="exampleFormControlSelect1">
<optgroup label = "Environmental factors">
<option value="air">Air pollution</option>
<option value="noise">Noise pollution</option>
</optgroup>
</select>
</div>
how the three.js code get activated
<div class="float-left"><button class="btn btn-success btn-sm button_toggle_dataviz" onclick="toggle_toDataviz()">Dataviz</button></div>
var displayMap = false;
var display3dData = false;
var displayStory = false;
function toggle_toDataviz() {
document.getElementById("dataviz_charts").style.display = "block";
document.getElementById("dataviz_map").style.display = "none";
document.getElementById("form-container-share-story").style.display =
"none";
displayMap = false;
display3dData = true;
displayStory = false;
start3DdataViz();
}
I am importing these links:
Tweenmax.min.js
orbitcontrol.js
three.js
the three.js full code:
var booleanCentrum = false;
var booleanZuid = false;
var booleanWest = false;
var booleanOost = false;
var booleanNoord = false;
var booleanNieuwWest = false;
var booleanZuidOost = false;
var booleanWestpoort = false;
function start3DdataViz() {
if(display3dData) {
document.getElementById('data_viz_cubes_update').innerHTML = '';
document.getElementById('data_viz_cubes_update').setAttribute("style", "height:500px");
let a = window.getComputedStyle(document.getElementById("data_viz_cubes_update"), null);
var canvasHeight = parseInt(a.getPropertyValue("height").substring(0, a.getPropertyValue("height").length - 2));
var canvasWidth = parseInt(a.getPropertyValue("width").substring(0, a.getPropertyValue("width").length - 2));
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, canvasWidth / canvasHeight, 0.1, 1000);
var controls = new THREE.OrbitControls(camera);
camera.position.z = 20;
controls.update();
$("#data_viz_cubes_update").hover(
function () {
noscroll()
}
);
var noscroll_var;
function noscroll() {
if (noscroll_var) {
document.getElementsByTagName("html")[0].style.overflowY = "";
document.body.style.paddingRight = "0";
controls.enableZoom = false;
controls.enablePan = false;
controls.enableRotate = false;
noscroll_var = false
} else {
document.getElementsByTagName("html")[0].setAttribute('style', 'overflow-y: hidden !important');
document.body.style.paddingRight = "17px";
controls.enableZoom = true;
controls.enablePan = true;
controls.enableRotate = true;
noscroll_var = true
}
}
var renderer = new THREE.WebGLRenderer();
renderer.setClearColor("#e3e0e5");
renderer.setSize(canvasWidth, canvasHeight);
var canvas = document.getElementById('data_viz_cubes_update');
renderer.setSize($(canvas).width(), $(canvas).height());
canvas.appendChild(renderer.domElement);
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var geometry = new THREE.BoxGeometry(1, 1, 1);
var material = new THREE.MeshLambertMaterial({color: "red", transparent: true});
for (let i = 0; i < 8; i++) {
let b = "";
0 === i ? b = "Centrum" : 1 === i ? b = "Zuid" : 2 === i ? b = "West" : 3 === i ? b = "Oost" : 4 === i ? b = "Noord" : 5 === i ? b = "NieuwWest" : 6 === i ? b = "ZuidOost" : 7 === i && (b = "Westpoort");
var mesh = new THREE.Mesh(geometry, material);
mesh.material.opacity = 1;
mesh.name = b;
mesh.position.x = (Math.random() - 0.5) * 20;
mesh.position.y = (Math.random() - 0.5) * 20;
mesh.position.z = (Math.random() - 0.5) * 20;
scene.add(mesh);
}
var light = new THREE.PointLight('white', 1, 1000);
light.position.set(0, 0, 0);
scene.add(light);
var render = function () {
requestAnimationFrame(render);
controls.update();
renderer.render(scene, camera);
};
render();
function onMouseMove(event) {
event.preventDefault();
var rect = event.target.getBoundingClientRect();
mouse.x = ((event.clientX - rect.left) / canvasWidth) * 2 - 1;
mouse.y = -((event.clientY - rect.top) / canvasHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children, true);
for (var i = 0; i < intersects.length; i++) {
booleanCentrum = false;
booleanZuid = false;
booleanWest = false;
booleanOost = false;
booleanNoord = false;
booleanNieuwWest = false;
booleanZuidOost = false;
booleanWestpoort = false;
switch(intersects[i].object.name){
case "Centrum":
booleanCentrum = true;
break;
case "Zuid":
booleanZuid = true;
break;
case "West":
booleanWest = true;
break;
case "Oost":
booleanOost = true;
break;
case "Noord":
booleanNoord = true;
break;
case "NieuwWest":
booleanNieuwWest = true;
break;
case "ZuidOost":
booleanZuidOost = true;
break;
case "Westpoort":
booleanWestpoort = true;
break;
default:
console.log('not on object');
}
this.tl = new TimelineMax();
this.tl.to(intersects[i].object.scale, 1, {x: 2, ease: Expo.easeOut});
this.tl.to(intersects[i].object.scale, .5, {x: 1, ease: Expo.easeOut});
}
}
window.addEventListener('mousemove', onMouseMove);
}
}
I am creating a THREEjs animation which I eventually want to sync with audio. (Can't accomplish this currently) I would like to add and remove shaders at specific points. How can I accomplish this most efficiently?
The way I have it set up now, is that I have a mirror shader inside of a function called turnOnMirror and in my render function, I have a conditional statement,
if (audioSrc.context.currentTime > 32.0) { turnOnMirror(); }
The shader looks like this:
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = true;
composer.addPass(mirror);
(I am doing this for 2 reasons!
A: The renderer is the only place I can grab the actual time to make this call. And B: because for whatever reason, my frequencyData array comes back as 0s.
However, when the scene reaches this point, everything slows down extremely. How can I keep the same frame rate and accomplish what I am attempting to at the same time?
A piece of information for you is that the scene works fine at the same constant speed if I just apply the shader without making the call in the render function.
You can view the site here!
And the source code for the main.js is below!
/* ==================== [ Global Variables ] ==================== */
var scene, camera, renderer, aspectRatio;
var stats;
var composer, effect, clock;
var backMesh;
/* ==================== [ Audio Context ] ==================== */
var ctx = new AudioContext();
var audio = document.getElementById('player');
audio.play();
audio.volume = 1;
// audio.crossOrigin = "anonymous";
var audioSrc = ctx.createMediaElementSource(audio);
var analyser = ctx.createAnalyser();
audioSrc.connect(analyser);
audioSrc.connect(ctx.destination);
// frequencyBinCount tells you how many values you'll receive from the analyser
var frequencyData = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(frequencyData);
console.log(audioSrc);
console.log(audioSrc.context.currentTime);
console.log(frequencyData);
console.log(analyser.fftSize); // 2048 by default
console.log(analyser.frequencyBinCount); // will give us 1024 data points
analyser.fftSize = 64;
console.log(analyser.frequencyBinCount); // fftSize/2 = 32 data points
/* ==================== [ Set Scene & Camera ] ==================== */
scene = new THREE.Scene();
// scene.fog = new THREE.Fog(0x000000, 0, 1200);
aspectRatio = window.innerWidth / window.innerHeight;
camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 100);
// camera.target = new THREE.Vector3( 10, 10, 10 );
// Set the DOM
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor("#000000");
document.body.appendChild(renderer.domElement);
/* ==================== [ Camera Position ] ==================== */
camera.position.z = 15;
camera.position.y = 0;
/* ==================== [ Point Lights ] ==================== */
var pointLightBlue = new THREE.PointLight("#00ccff", 5, 100, 2);
pointLightBlue.position.set(-10, -40, -10);
scene.add(pointLightBlue);
// var pointLightWhite = new THREE.PointLight( "#ffffff", 1, 0, 1 );
// // pointLightWhite.position.set( -10, 160, -10 );
// pointLightWhite.position.set( 0, 0, 1 );
// scene.add(pointLightWhite);
// camera.add(pointLightWhite);
// var pointLightPink = new THREE.PointLight( "#EE567C", 5, 100, 10 );
// pointLightPink.position.set( 1, 0, -5 );
// scene.add(pointLightPink);
var pointLight = new THREE.PointLight("#A805FA", 2, 100, 40);
pointLight.position.set(40, 0, 40);
scene.add(pointLight);
var light2 = new THREE.PointLight( 0xFFFFFF, 1, 100 );
scene.add( light2 );
light2.position.z = 1000;
var pointLight2 = new THREE.PointLight("#07FAA0", 2, 100, 30);
pointLight2.position.set(-40, 0, -40);
scene.add(pointLight2);
/* ==================== [ Particles ] ==================== */
var getCamera = function() {
return camera;
}
// var texture = new Image();
// texture.src = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/82015/snowflake.png';
// texture.src = './images/particle.png';
//var material = new THREE.ParticleBasicMaterial( { map: new THREE.Texture(texture) } );
var particleCount = 0, particleSystem, particles;
THREE.ImageUtils.crossOrigin = '';
var texture = THREE.ImageUtils.loadTexture('./images/particle.png');
//console.log(texture);
particleCount = 20000,
particles = new THREE.Geometry();
var pMaterial = new THREE.PointCloudMaterial({
color: 0xFFFFFF,
map: texture,
blending: THREE.AdditiveBlending,
depthTest: false,
depthWrite: false,
transparent: true,
opacity: 0.3,
side: THREE.DoubleSide,
size: 1.2
});
for (var i = 0; i < particleCount; i++) {
var pX = Math.random() * 500 - 250,
pY = Math.random() * 500 - 250,
pZ = Math.random() * 500 - 250,
particle = new THREE.Vector3(pX, pY, pZ);
particles.vertices.push(particle);
}
particleSystem = new THREE.ParticleSystem(particles, pMaterial);
particleSystem.sortParticles = false;
particleSystem.frustumCulled = false;
scene.add(particleSystem);
/* ==================== [ Light Beams ] ==================== */
var BEAM_ROT_SPEED = 0.003;
var BEAM_COUNT = 360;
var beamGeometry = new THREE.PlaneBufferGeometry(1, 500, 10, 1);
beamGroup = new THREE.Object3D();
beamMaterial = new THREE.MeshBasicMaterial({
opacity: 0.02,
transparent: true,
});
for (var i = 0; i <= BEAM_COUNT; ++i) {
var beam = new THREE.Mesh(beamGeometry, beamMaterial);
beam.doubleSided = true;
beam.rotation.x = Math.random() * Math.PI;
beam.rotation.y = Math.random() * Math.PI;
beam.rotation.z = Math.random() * Math.PI;
beamGroup.add(beam);
}
scene.add(beamGroup);
beamGroup.translateZ( -5 );
/* ==================== [ Cubes ] ==================== */
var doStrobe = false;
var doShake = false;
var strobeOn = false;
var beatTime = 30;
THREE.ImageUtils.crossOrigin = '';
var imgTextureStripes2 = THREE.ImageUtils.loadTexture( "./images/stripes2.jpg" );
imgTextureStripes2.wrapS = imgTextureStripes2.wrapT = THREE.RepeatWrapping;
imgTextureStripes2.repeat.set( 100, 100 );
backMaterial2 = new THREE.MeshBasicMaterial( {
map:imgTextureStripes2
} );
backMesh2 = new THREE.Mesh( new THREE.SphereGeometry( 1900, 30, 20 ), backMaterial2 );
backMesh2.scale.x = -1;
scene.add( backMesh2 );
backMesh2.visible = false;
function Box() {
this.posn = new THREE.Vector3();
this.rotation = new THREE.Vector3();
this.speed = getRand(3, 20);
this.init();
}
Box.ORIGIN = new THREE.Vector3();
Box.MAX_DISTANCE = 1000;
Box.INIT_POSN_RANGE = 500;
Box.FRONT_PLANE_Z = 1000;
Box.BACK_PLANE_Z = -1000;
Box.prototype.init = function() {
this.posn.copy(Box.ORIGIN);
this.posn.x = getRand(-Box.INIT_POSN_RANGE,Box.INIT_POSN_RANGE);
this.posn.y = getRand(-Box.INIT_POSN_RANGE,Box.INIT_POSN_RANGE);
this.posn.z = Box.BACK_PLANE_Z;
this.rotation.x = (Math.random() * 360 ) * Math.PI / 180;
this.rotation.y = (Math.random() * 360 ) * Math.PI / 180;
this.rotation.z = (Math.random() * 360 ) * Math.PI / 180;
};
Box.prototype.update = function() {
this.posn.z += this.speed * sketchParams.cubeSpeed ;
this.rotation.x += 0.03;
this.rotation.y += 0.01;
if(this.posn.z > Box.FRONT_PLANE_Z) {
this.init();
}
};
// returns random number within a range
function getRand(minVal, maxVal) {
return minVal + (Math.random() * (maxVal - minVal));
}
var cubesize = 100;
var BOX_COUNT;
var geometry = new THREE.CubeGeometry(cubesize, cubesize, cubesize);
cubeHolder = new THREE.Object3D();
THREE.ImageUtils.crossOrigin = '';
imgTextureStripes = THREE.ImageUtils.loadTexture( "./images/stripes2.jpg" );
cubeMaterial = new THREE.MeshPhongMaterial( {
ambient: 0x111111,
color: 0x666666,
specular: 0x999999,
shininess: 30,
shading: THREE.FlatShading,
map:imgTextureStripes
});
for(i = 0; i < BOX_COUNT; i++) {
var box = new Box();
console.log(box);
boxes.push(box);
var cube = new THREE.Mesh(geometry,cubeMaterial );
cube.position = box.posn;
cube.rotation = box.rotation;
cube.ox = cube.scale.x = Math.random() * 1 + 1;
cube.oy = cube.scale.y = Math.random() * 1 + 1;
cube.oz = cube.scale.z = Math.random() * 1 + 1;
cubeHolder.add(cube);
}
scene.add(cubeHolder);
/* ==================== [ Mini Geometries ] ==================== */
/* ==================== [ Post Processing ] ==================== */
composer = new THREE.EffectComposer(renderer);
composer.addPass(new THREE.RenderPass(scene, camera));
effect = new THREE.ShaderPass(THREE.FilmShader);
effect.uniforms['time'].value = 2.0;
effect.uniforms['nIntensity'].value = 0.4;
effect.uniforms['sIntensity'].value = 0.9;
effect.uniforms['sCount'].value = 1800;
effect.uniforms['grayscale'].value = 0.8;
composer.addPass(effect);
// var dot = new THREE.ShaderPass( THREE.DotScreenShader );
// dot.uniforms[ 'scale' ].value = 400;
// dot.uniforms[ 'tDiffuse' ].value = 40;
// dot.uniforms[ 'tSize' ].value = new THREE.Vector2( 256, 256 );
// composer.addPass(dot);
// var kaleidoPass = new THREE.ShaderPass(THREE.KaleidoShader);
// kaleidoPass.uniforms['sides'].value = 3;
// kaleidoPass.uniforms['angle'].value = 45 * Math.PI / 180;
// composer.addPass(kaleidoPass);
// var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
// // mirror.uniforms[ "tDiffuse" ].value = 1.0;
// // mirror.uniforms[ "side" ].value = 3;
// composer.addPass(mirror);
var glitch = new THREE.GlitchPass(64);
glitch.uniforms[ "tDiffuse" ].value = 1.0;
glitch.uniforms[ 'seed' ].value = Math.random() * 5;
glitch.uniforms[ 'byp' ].value = 0;
// glitch.goWild = true;
composer.addPass(glitch);
var superPass = new THREE.ShaderPass(THREE.SuperShader);
superPass.uniforms.vigDarkness.value = 1;
superPass.uniforms.vigOffset.value = 1.3;
superPass.uniforms.glowSize.value = 2;
superPass.uniforms.glowAmount.value = 1;
composer.addPass( superPass );
var tv = new THREE.ShaderPass( THREE.BadTVShader );
tv.uniforms[ "distortion" ].value = 1;
tv.uniforms[ "distortion2" ].value = .01;
// tv.uniforms[ "time" ].value = 1.5;
tv.uniforms[ "speed" ].value = 8.8;
tv.uniforms[ "rollSpeed" ].value = 0.8;
composer.addPass(tv);
var staticPass = new THREE.ShaderPass( THREE.StaticShader );
staticPass.uniforms[ "amount" ].value = 0.15;
staticPass.uniforms[ "size" ].value = 1.0;
staticPass.uniforms[ "time" ].value = 4.5;
composer.addPass(staticPass);
var effect1 = new THREE.ShaderPass(THREE.RGBShiftShader);
effect1.uniforms['amount'].value = 0.003;
effect1.renderToScreen = true;
composer.addPass(effect1);
function turnOnMirror() {
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = true;
composer.addPass(mirror);
}
function turnOffMirror() {
var mirror = mirrorPass = new THREE.ShaderPass( THREE.MirrorShader );
mirror.renderToScreen = false;
composer.addPass(mirror);
}
// add a timer
clock = new THREE.Clock;
/* ==================== [ Stats ] ==================== */
// stats = new Stats();
// stats.domElement.style.position = 'absolute';
// stats.domElement.style.left = '0px';
// stats.domElement.style.top = '0px';
// document.body.appendChild(stats.domElement);
// document.body.appendChild( renderer.domElement );
/* ==================== [ Shapes ] ==================== */
var quantity = 40;
var shapes = [];
for (var i = 0; i < quantity; i++) {
if (Math.random() < 0.5) {
var geometry = new THREE.RingGeometry(4, 40, 3);
// geometry.position = 0;
// var geometry = new THREE.RingGeometry( 30, 30, 18);
// camera.position.z = 60;
// var geometry = new THREE.RingGeometry( 20, 150, 18);
// var geometry = new THREE.RingGeometry( 20, 150, 18);
// var geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
}
else {
//var geometry = new THREE.RingGeometry( 4, 40, 3);
// var geometry = new THREE.RingGeometry( 30, 30, 18);
// var geometry = new THREE.RingGeometry( 1, 5, 6 );
// var material = new THREE.MeshBasicMaterial( { color: 0xffff00,
// side: THREE.DoubleSide } );
// var mesh = new THREE.Mesh( geometry, material );
// scene.add( mesh );
}
if (i % 7 === 0) {
var material = new THREE.MeshPhongMaterial({
color: "#ffffff"
});
} else if (i % 2 === 0) {
var material = new THREE.MeshPhongMaterial({
color: "#666666"
});
} else {
var material = new THREE.MeshPhongMaterial({
color: "#333333"
});
}
var mesh = new THREE.Mesh(geometry, material);
mesh.position.z = -i * 3;
// mesh.rotation.z = i;
shapes.push(mesh);
scene.add(mesh);
}
// function refRate() {
// curTime = Date.now();
// delta = curTime - oldTime;
//
// if (delta > interval) {
// oldTime = curTime - (delta % interval);
// updateSize();
// }
//
// }
// Variables
var u_time = 0;
/* ==================== [ Render Function ] ==================== */
var render = function () {
requestAnimationFrame(render);
// var timer = Date.now() * 0.0010;
// camera.lookAt(scene.position);
u_time++;
for (var i = 0; i < quantity; i++) {
// Set rotation change of shapes
shapes[i].position.z += 0.2;
shapes[i].rotation.z += 0;
shapes[i].scale.x = 1 + Math.sin(i + u_time * 0.1) * 0.05;
shapes[i].scale.y = 1 + Math.sin(i + u_time * 0.1) * 0.05;
// shapes[i].scale.y = 120 + Math.tan(i + u_time * 5.0) * 0.5;
// shapes[i].scale.x = 120 + Math.tan(i + u_time * 5.0) * 0.5;
var change = 1.5 + Math.sin(u_time * 0.5) * 0.5;
// Set wireframe & width
if (Math.random() < change) {
shapes[i].material.wireframe = false;
shapes[i].material.wireframeLinewidth = Math.random() * 2;
// if (shapes[i] / 2 === 0) {
// turnOnMirror();
// }
}
else {
shapes[i].material.wireframe = false;
}
if (shapes[i].position.z > 10) {
shapes[i].position.z = -70;
shapes[i].rotation.z = i;
}
}
// Set Point light Intensity & Position
pointLight.intensity = Math.abs(Math.sin(u_time * 0.2) * 2);
pointLight2.intensity = Math.abs(Math.cos(u_time * 0.2) * 2);
pointLight.position.z = Math.abs(Math.sin(u_time * 0.02) * 30);
pointLight2.position.z = Math.abs(Math.cos(u_time * 0.02) * 30);
renderer.render(scene, camera);
composer.render();
var pCount = particleCount;
while (pCount--) {
var camz = getCamera().position.z;
var particle = particles.vertices[pCount];
particle.y = Math.random() * 500 - 250;
//particleSystem.vertices[i].z = camz + Math.random()*600 + 200 ;
particleSystem.geometry.vertices.needsUpdate = true;
}
particleSystem.rotation.y += -0.001;
particleSystem.rotation.z += 0.005;
var normLevel = 0.2;
beamGroup.rotation.x += BEAM_ROT_SPEED;
beamGroup.rotation.y += BEAM_ROT_SPEED;
beamMaterial.opacity = Math.min(normLevel * 0.4, 0.6);
camera.rotation.z += 0.003;
if (doShake) {
var maxshake = 60;
var shake = normLevel * maxshake ;
camera.position.x = Math.random()*shake - shake/2;
camera.position.y = Math.random()*shake - shake/2;
}
camera.rotation.z += 0.003;
// camera.rotation.y += 0.005;
// camera.rotation.x -= 0.003;
//camera.rotation.z += 0.03;
if (doStrobe){
strobeOn = !strobeOn;
if (strobeOn){
light2.intensity = 2;
}
else {
light2.intensity = 0.5;
}
}
else {
light2.intensity = 0.2;
}
// flash background on level threshold
if (normLevel > 0.5 ){
renderer.setClearColor ( 0xFFFFFF );
backMesh2.visible = true;
}
else{
renderer.setClearColor ( 0x000000 );
backMesh2.visible = false;
}
// show stripes for 6 frames on beat
backMesh2.visible = beatTime < 6;
for(var i = 0; i < BOX_COUNT; i++) {
boxes[i].update();
}
if (audioSrc.context.currentTime > 32) {
turnOnMirror();
}
// console.log(audioSrc.context.currentTime);
}
render();
var lc_relationship= null;
var container, nSize = 100;
var camera, scene, renderer;
var scale = 10, scale1 = 100; N=50, cubeRotSpd=0;
var arr= [];
var width = window.innerWidth, height = window.innerHeight;
function generateData()
{
var aSensor1 = [],
aSensor2 = [],
aSensor3 = [];
lc_relationship = {
"sensor1":[],
"sensor2":[],
"sensor3":[]
}
for(i=1; i<=nSize; i++)
{
aSensor1.push(i);
aSensor2.push(i);
aSensor3.push(i);
}
for(n=0; n<nSize; n++)
{
var pos1 = Math.floor(Math.random() * (nSize-n));
var pos2 = Math.floor(Math.random() * (nSize-n));
var pos3 = Math.floor(Math.random() * (nSize-n));
var int1 = aSensor1[pos1]; aSensor1.splice(pos1,1);
var int2 = aSensor2[pos2]; aSensor2.splice(pos2,1);
var int3 = aSensor3[pos3]; aSensor3.splice(pos3,1);
lc_relationship.sensor1[int1-1] =
{
"ObjectID" : "sens1_" + rightPad(int1),
"Geometry" : getGeometry(),
"Parent":null,
"child": "sens2_" + rightPad(int2),
"z_cordinate": -5
}
lc_relationship.sensor2[int2-1] =
{
"ObjectID" : "sens2_" + rightPad(int2),
"Geometry" : getGeometry(),
"Parent":"sens1_" + rightPad(int1),
"child": "sens3_" + rightPad(int3),
"z_cordinate": 0
}
lc_relationship.sensor3[int3-1] =
{
"ObjectID" : "sens3_" + rightPad(int3),
"Geometry" : getGeometry(),
"Parent":"sens2_" + rightPad(int2),
"child": null,
"z_cordinate": 5
}
}
}
function rightPad(number)
{
var tmpStr = number.toString();
return ("000" + tmpStr).substring(tmpStr.length, tmpStr.length+3);
}
function getGeometry()
{
var geo = new THREE.Geometry();
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( 0, 0, 0)));
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( -0.5, 0.5, 1)));
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( 0.5, 0.5, 1)));
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( -0.5, -0.5, 1)));
geo.vertices.push(new THREE.Vertex(
new THREE.Vector3( 0.5,-0.5, 1)));
geo.faces.push( new THREE.Face3(0,1,2));
geo.faces.push( new THREE.Face3(2,1,4));
geo.faces.push( new THREE.Face3(1,3,4));
geo.faces.push( new THREE.Face3(4,3,0));
geo.faces.push( new THREE.Face3(3,1,0));
geo.faces.push( new THREE.Face3(0,2,4));
geo.computeFaceNormals();
/* cone = new THREE.Mesh(geo, meshMaterial);
cone.doubleSided = true;
cone.overdraw = true;*/
return geo;
}
function posgeo()
{ generateData();
//var jsonText = JSON.stringify(lc_relationship);
//document.getElementById("output").innerHTML=jsonText;
//document.getElementById("test").innerHTML=lc_relationship.sensor1[0].z_cordinate;
init();
animate();
}
function init()
{
container = document.getElementById("output");
camera = new THREE.PerspectiveCamera( 45, width / height, 0.1, 1000 );
camera.position.y = 0;
camera.position.z = 45;
camera.lookAt(new THREE.Vector3(0, 0, 0));
scene = new THREE.Scene();
scene.add(camera);
renderer = new THREE.WebGLRenderer(/*{antialias:true}*/);
renderer.setClearColorHex(0xffffff, 1);
renderer.setSize( width, height );
var meshmaterial = new THREE.MeshLambertMaterial( { color: 0x0000CC, opacity: 0.3, depthWrite: false, depthTest: false });
I'm having whole problem at this loop, Can someone help me to fix this? The Loop is here:
for ( var i = 0; i <nSize; i++)
for ( var j = -5; j < 5; j++)
for ( var k = -5; k < 5; k++)
{
var cone1 = new THREE.MESH(lc_relationship.sensor1[i].Geometry,meshMaterial);
cone1.doubleSided = true;
cone1.overdraw = true;
scene.add(cone1);
var cone2 = new THREE.MESH(lc_relationship.sensor2[i].Geometry,meshMaterial);
cone2.doubleSided = true;
cone2.overdraw = true;
scene.add(cone2);
var cone3 = new THREE.MESH(lc_relationship.sensor3[i].Geometry,meshMaterial);
cone3.doubleSided = true;
cone3.overdraw = true;
scene.add(cone3);
cone1.position.set(2*k, 2*j,lc_relationship.sensor1[i].z_cordinate);
cone2.position.set(2*k, 2*j,lc_relationship.sensor2[i].z_cordinate);
cone3.position.set(2*k, 2*j,lc_relationship.sensor3[i].z_cordinate);
}
All I want to dispay cones like image below :
and the remaining Code:
var light = new THREE.DirectionalLight(0xffffff, 0.6);
light.position.y = 1;
light.position.x = 1;
light.position.z = 1;
scene.add(light);
light = new THREE.DirectionalLight(0xffffff, 0.6);
light.position.y = -1;
light.position.x = -1;
light.position.z = -1;
scene.add(light);
light = new THREE.DirectionalLight(0xffffff, 0.6);
light.position.y = 1;
light.position.x = 0;
light.position.z = 0;
scene.add(light);
container.appendChild( renderer.domElement );
}
function animate()
{
requestAnimationFrame( animate );
render();
}
function render()
{
renderer.render(scene, camera);
}
Can Some help to solve this issue. This task is really sitting on head all the time :(
You can do it with a single loop, by calculating j and k from j instead of adding two more loops:
for ( var i = 0; i <nSize; i++)
{
var k = i%10,
j = (i-k)/10;
j = j*2 - 10; // You may need to adjust this "10",
k = k*2 - 10; // may be "9", so the layers get centered.
//console.log(j,k)
var cone1 = new THREE.MESH(lc_relationship.sensor1[i].Geometry,meshMaterial);
cone1.doubleSided = true;
cone1.overdraw = true;
scene.add(cone1);
var cone2 = new THREE.MESH(lc_relationship.sensor2[i].Geometry,meshMaterial);
cone2.doubleSided = true;
cone2.overdraw = true;
scene.add(cone2);
var cone3 = new THREE.MESH(lc_relationship.sensor3[i].Geometry,meshMaterial);
cone3.doubleSided = true;
cone3.overdraw = true;
scene.add(cone3);
cone1.position.set(j, k, lc_relationship.sensor1[i].z_cordinate);
cone2.position.set(j, k, lc_relationship.sensor2[i].z_cordinate);
cone3.position.set(j, k, lc_relationship.sensor3[i].z_cordinate);
}