Script: Save image files in different subfolders - photoshop-script

I am trying to write a script for Photoshop.
It has to turn an existing image file, into 7 different sized (resolution) images.
So far that works.
And now it saves them with 7 different file-names (I can controll the suffix).
But what I want is that it saves the files all with the same filenames in different (correspondent) folders, (instead of different suffix in the filename).
That last part I cant get to work.
Can anyone help me so that the script will save the files in subfolders, one for every resolution/sized file? (and perhaps even create them if they do not exist).
Edit:
If I add this part in the code, this will create a subfolder for me.
But it will not save any file into it.
Please help :)
//try{
var f = new Folder( folder+'/50x50' );
if( !f.exists ) f.create();
return f; }catch(e){};
Thanks a lot.
#target photoshop
// Setup
doc = app.activeDocument;
function saveForWeb(f, width, height, fileSuffix) {
var originalRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var basename = doc.name.match(/(.*)\.[^\.]+$/)[1];
var thePercentage = width / doc.width * 100;
var theFile = basename + f + fileSuffix + ".jpg";
// =======================================================
var idExpr = charIDToTypeID( "Expr" );
var desc2 = new ActionDescriptor();
var idUsng = charIDToTypeID( "Usng" );
var desc3 = new ActionDescriptor();
var idOp = charIDToTypeID( "Op " );
var idSWOp = charIDToTypeID( "SWOp" );
var idOpSa = charIDToTypeID( "OpSa" );
desc3.putEnumerated( idOp, idSWOp, idOpSa );
var idDIDr = charIDToTypeID( "DIDr" );
desc3.putBoolean( idDIDr, true );
var idIn = charIDToTypeID( "In " );
desc3.putPath( idIn, new File( doc.path ) );
var idovFN = charIDToTypeID( "ovFN" );
desc3.putString( idovFN, theFile );
var idFmt = charIDToTypeID( "Fmt " );
var idIRFm = charIDToTypeID( "IRFm" );
var idPNtwofour = charIDToTypeID( "PN24" );
desc3.putEnumerated( idFmt, idIRFm, idPNtwofour );
var idIntr = charIDToTypeID( "Intr" );
desc3.putBoolean( idIntr, false );
var idTrns = charIDToTypeID( "Trns" );
desc3.putBoolean( idTrns, true );
var idMtt = charIDToTypeID( "Mtt " );
desc3.putBoolean( idMtt, false );
var idMttR = charIDToTypeID( "MttR" );
desc3.putInteger( idMttR, 255 );
var idMttG = charIDToTypeID( "MttG" );
desc3.putInteger( idMttG, 255 );
var idMttB = charIDToTypeID( "MttB" );
desc3.putInteger( idMttB, 255 );
var idHScl = charIDToTypeID( "HScl" );
var idPrc = charIDToTypeID( "#Prc" );
desc3.putUnitDouble( idHScl, idPrc, thePercentage );
var idVScl = charIDToTypeID( "VScl" );
var idPrc = charIDToTypeID( "#Prc" );
desc3.putUnitDouble( idVScl, idPrc, thePercentage );
var idSHTM = charIDToTypeID( "SHTM" );
desc3.putBoolean( idSHTM, false );
var idSImg = charIDToTypeID( "SImg" );
desc3.putBoolean( idSImg, true );
var idSWsl = charIDToTypeID( "SWsl" );
var idSTsl = charIDToTypeID( "STsl" );
var idSLAl = charIDToTypeID( "SLAl" );
desc3.putEnumerated( idSWsl, idSTsl, idSLAl );
var idSWch = charIDToTypeID( "SWch" );
var idSTch = charIDToTypeID( "STch" );
var idCHsR = charIDToTypeID( "CHsR" );
desc3.putEnumerated( idSWch, idSTch, idCHsR );
var idSWmd = charIDToTypeID( "SWmd" );
var idSTmd = charIDToTypeID( "STmd" );
var idMDCC = charIDToTypeID( "MDCC" );
desc3.putEnumerated( idSWmd, idSTmd, idMDCC );
var idohXH = charIDToTypeID( "ohXH" );
desc3.putBoolean( idohXH, false );
var idohIC = charIDToTypeID( "ohIC" );
desc3.putBoolean( idohIC, true );
var idohAA = charIDToTypeID( "ohAA" );
desc3.putBoolean( idohAA, true );
var idohQA = charIDToTypeID( "ohQA" );
desc3.putBoolean( idohQA, true );
var idohCA = charIDToTypeID( "ohCA" );
desc3.putBoolean( idohCA, false );
var idohIZ = charIDToTypeID( "ohIZ" );
desc3.putBoolean( idohIZ, true );
var idohTC = charIDToTypeID( "ohTC" );
var idSToc = charIDToTypeID( "SToc" );
var idOCzerothree = charIDToTypeID( "OC03" );
desc3.putEnumerated( idohTC, idSToc, idOCzerothree );
var idohAC = charIDToTypeID( "ohAC" );
var idSToc = charIDToTypeID( "SToc" );
var idOCzerothree = charIDToTypeID( "OC03" );
desc3.putEnumerated( idohAC, idSToc, idOCzerothree );
var idohIn = charIDToTypeID( "ohIn" );
desc3.putInteger( idohIn, -1 );
var idohLE = charIDToTypeID( "ohLE" );
var idSTle = charIDToTypeID( "STle" );
var idLEzerothree = charIDToTypeID( "LE03" );
desc3.putEnumerated( idohLE, idSTle, idLEzerothree );
var idohEn = charIDToTypeID( "ohEn" );
var idSTen = charIDToTypeID( "STen" );
var idENzerozero = charIDToTypeID( "EN00" );
desc3.putEnumerated( idohEn, idSTen, idENzerozero );
var idolCS = charIDToTypeID( "olCS" );
desc3.putBoolean( idolCS, false );
var idolEC = charIDToTypeID( "olEC" );
var idSTst = charIDToTypeID( "STst" );
var idSTzerozero = charIDToTypeID( "ST00" );
desc3.putEnumerated( idolEC, idSTst, idSTzerozero );
var idolWH = charIDToTypeID( "olWH" );
var idSTwh = charIDToTypeID( "STwh" );
var idWHzeroone = charIDToTypeID( "WH01" );
desc3.putEnumerated( idolWH, idSTwh, idWHzeroone );
var idolSV = charIDToTypeID( "olSV" );
var idSTsp = charIDToTypeID( "STsp" );
var idSPzerofour = charIDToTypeID( "SP04" );
desc3.putEnumerated( idolSV, idSTsp, idSPzerofour );
var idolSH = charIDToTypeID( "olSH" );
var idSTsp = charIDToTypeID( "STsp" );
var idSPzerofour = charIDToTypeID( "SP04" );
desc3.putEnumerated( idolSH, idSTsp, idSPzerofour );
var idolNC = charIDToTypeID( "olNC" );
var list1 = new ActionList();
var desc4 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCzerozero = charIDToTypeID( "NC00" );
desc4.putEnumerated( idncTp, idSTnc, idNCzerozero );
var idSCnc = charIDToTypeID( "SCnc" );
list1.putObject( idSCnc, desc4 );
var desc5 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNConenine = charIDToTypeID( "NC19" );
desc5.putEnumerated( idncTp, idSTnc, idNConenine );
var idSCnc = charIDToTypeID( "SCnc" );
list1.putObject( idSCnc, desc5 );
var desc6 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwoeight = charIDToTypeID( "NC28" );
desc6.putEnumerated( idncTp, idSTnc, idNCtwoeight );
var idSCnc = charIDToTypeID( "SCnc" );
list1.putObject( idSCnc, desc6 );
var desc7 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwofour = charIDToTypeID( "NC24" );
desc7.putEnumerated( idncTp, idSTnc, idNCtwofour );
var idSCnc = charIDToTypeID( "SCnc" );
list1.putObject( idSCnc, desc7 );
var desc8 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwofour = charIDToTypeID( "NC24" );
desc8.putEnumerated( idncTp, idSTnc, idNCtwofour );
var idSCnc = charIDToTypeID( "SCnc" );
list1.putObject( idSCnc, desc8 );
var desc9 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwofour = charIDToTypeID( "NC24" );
desc9.putEnumerated( idncTp, idSTnc, idNCtwofour );
var idSCnc = charIDToTypeID( "SCnc" );
list1.putObject( idSCnc, desc9 );
desc3.putList( idolNC, list1 );
var idobIA = charIDToTypeID( "obIA" );
desc3.putBoolean( idobIA, false );
var idobIP = charIDToTypeID( "obIP" );
desc3.putString( idobIP, "\"\"\"\"" );
var idobCS = charIDToTypeID( "obCS" );
var idSTcs = charIDToTypeID( "STcs" );
var idCSzeroone = charIDToTypeID( "CS01" );
desc3.putEnumerated( idobCS, idSTcs, idCSzeroone );
var idovNC = charIDToTypeID( "ovNC" );
var list2 = new ActionList();
var desc10 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCzeroone = charIDToTypeID( "NC01" );
desc10.putEnumerated( idncTp, idSTnc, idNCzeroone );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc10 );
var desc11 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwozero = charIDToTypeID( "NC20" );
desc11.putEnumerated( idncTp, idSTnc, idNCtwozero );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc11 );
var desc12 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCzerotwo = charIDToTypeID( "NC02" );
desc12.putEnumerated( idncTp, idSTnc, idNCzerotwo );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc12 );
var desc13 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNConenine = charIDToTypeID( "NC19" );
desc13.putEnumerated( idncTp, idSTnc, idNConenine );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc13 );
var desc14 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCzerosix = charIDToTypeID( "NC06" );
desc14.putEnumerated( idncTp, idSTnc, idNCzerosix );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc14 );
var desc15 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwofour = charIDToTypeID( "NC24" );
desc15.putEnumerated( idncTp, idSTnc, idNCtwofour );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc15 );
var desc16 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwofour = charIDToTypeID( "NC24" );
desc16.putEnumerated( idncTp, idSTnc, idNCtwofour );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc16 );
var desc17 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwofour = charIDToTypeID( "NC24" );
desc17.putEnumerated( idncTp, idSTnc, idNCtwofour );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc17 );
var desc18 = new ActionDescriptor();
var idncTp = charIDToTypeID( "ncTp" );
var idSTnc = charIDToTypeID( "STnc" );
var idNCtwotwo = charIDToTypeID( "NC22" );
desc18.putEnumerated( idncTp, idSTnc, idNCtwotwo );
var idSCnc = charIDToTypeID( "SCnc" );
list2.putObject( idSCnc, desc18 );
desc3.putList( idovNC, list2 );
var idovCM = charIDToTypeID( "ovCM" );
desc3.putBoolean( idovCM, false );
var idovCW = charIDToTypeID( "ovCW" );
desc3.putBoolean( idovCW, false );
var idovCU = charIDToTypeID( "ovCU" );
desc3.putBoolean( idovCU, true );
var idovSF = charIDToTypeID( "ovSF" );
desc3.putBoolean( idovSF, true );
var idovCB = charIDToTypeID( "ovCB" );
desc3.putBoolean( idovCB, true );
var idovSN = charIDToTypeID( "ovSN" );
desc3.putString( idovSN, """images""" );
var idSaveForWeb = stringIDToTypeID( "SaveForWeb" );
desc2.putObject( idUsng, idSaveForWeb, desc3 );
executeAction( idExpr, desc2, DialogModes.NO );
// =======================================================
app.preferences.rulerUnits = originalRulerUnits;
};
saveForWeb(960, 960, "_380x380")
saveForWeb(380, 380, "_380x380")
saveForWeb(300, 300, "_300x300")
saveForWeb(210, 210, "_210x210")
saveForWeb(150, 150, "_150x150")
saveForWeb(100, 100, "_100x100")
saveForWeb(50, 50, "_50x50")

I have no idea what all your complicated script is trying to achieve, but it is pretty simple to save a file for web like this:
// Set up our web export options
var options = new ExportOptionsSaveForWeb();
options.quality = 100;
options.format = SaveDocumentType.JPEG;
options.includeprofile=true;
activeDocument.exportDocument(tmpFile,ExportType.SAVEFORWEB,options);
Or, if you want multiple resolutions, put the above in a loop. There is an example here.

I have done it totally different now.
Got it exactly as I want.
// List of sizes:
// 2362x2362x300DPI
// 960x960x72DPI
// 380x380x72DPI
// 300x300x72DPI
// 210x210x72DPI
// 150x150x72DPI
// 100x100x72DPI
// 50x50x72DPI
#target photoshop
main();
function main(){
if(!documents.length) return;
var startRulerUnits = app.preferences.rulerUnits;
app.preferences.rulerUnits = Units.PIXELS;
var doc = app.activeDocument;
var Name = doc.name.replace(/\.[^\.]+$/, '');
var Path = decodeURI(doc.path);
createNamedSnapshot("Snap 1");
doc.resizeImage(960, undefined, 72, ResampleMethod.BICUBIC);
var outFolder = Folder(Path +"/960x960");
if(!outFolder.exists) outFolder.create();
var saveFile = File(outFolder +"/"+Name+".jpg");
SaveJPEG(saveFile,8);
revertNamedSnapshot("Snap 1");
doc.resizeImage(380, undefined, 72, ResampleMethod.BICUBIC);
outFolder = Folder(Path +"/380x380");
if(!outFolder.exists) outFolder.create();
var saveFile = File(outFolder +"/"+Name+".jpg");
SaveJPEG(saveFile,8);
revertNamedSnapshot("Snap 1");
doc.resizeImage(300, undefined, 72, ResampleMethod.BICUBIC);
outFolder = Folder(Path +"/300x300");
if(!outFolder.exists) outFolder.create();
var saveFile = File(outFolder +"/"+Name+".jpg");
SaveJPEG(saveFile,8);
revertNamedSnapshot("Snap 1");
doc.resizeImage(210, undefined, 72, ResampleMethod.BICUBIC);
outFolder = Folder(Path +"/210x210");
if(!outFolder.exists) outFolder.create();
var saveFile = File(outFolder +"/"+Name+".jpg");
SaveJPEG(saveFile,8);
revertNamedSnapshot("Snap 1");
doc.resizeImage(150, undefined, 72, ResampleMethod.BICUBIC);
outFolder = Folder(Path +"/150x150");
if(!outFolder.exists) outFolder.create();
var saveFile = File(outFolder +"/"+Name+".jpg");
SaveJPEG(saveFile,8);
revertNamedSnapshot("Snap 1");
doc.resizeImage(100, undefined, 72, ResampleMethod.BICUBIC);
outFolder = Folder(Path +"/100x100");
if(!outFolder.exists) outFolder.create();
var saveFile = File(outFolder +"/"+Name+".jpg");
SaveJPEG(saveFile,8);
revertNamedSnapshot("Snap 1");
doc.resizeImage(50, undefined, 72, ResampleMethod.BICUBIC);
outFolder = Folder(Path +"/50x50");
if(!outFolder.exists) outFolder.create();
var saveFile = File(outFolder +"/"+Name+".jpg");
SaveJPEG(saveFile,8);
revertNamedSnapshot("Snap 1");
doc.resizeImage(2362, undefined, 300, ResampleMethod.BICUBIC);
outFolder = Folder(Path +"/2362x2362");
if(!outFolder.exists) outFolder.create();
var saveFile = File(outFolder +"/"+Name+".jpg");
SaveJPEG(saveFile,12);
app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
app.preferences.rulerUnits = startRulerUnits;
}
function SaveJPEG(saveFile, jpegQuality){
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = jpegQuality; //1-12
activeDocument.saveAs(saveFile, jpgSaveOptions, true,Extension.LOWERCASE);
}
function createNamedSnapshot(name) {
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putClass( charIDToTypeID('SnpS') );
desc.putReference( charIDToTypeID('null'), ref );
var ref1 = new ActionReference();
ref1.putProperty( charIDToTypeID('HstS'), charIDToTypeID('CrnH') );
desc.putReference( charIDToTypeID('From'), ref1 );
desc.putString( charIDToTypeID('Nm '), name );
desc.putEnumerated( charIDToTypeID('Usng'), charIDToTypeID('HstS'), charIDToTypeID('FllD') );
executeAction( charIDToTypeID('Mk '), desc, DialogModes.NO );
}
function revertNamedSnapshot(name) {
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putName( charIDToTypeID('SnpS'), name );
desc.putReference( charIDToTypeID('null'), ref );
executeAction( charIDToTypeID('slct'), desc, DialogModes.NO );
}

Related

three.js camera tween with switch statement

I am trying to tween a camera in three.js.
I have the following code in my init function.
A switch statement i am passing through an iFrame.
window.onmessage = function(evt) {
switch (evt.data.cameraYpos) {
case 'Ypos01':
var from01 = {
y: camera.position.y
};
var to01 = {
y: yPos01
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
case 'Ypos02':
var from02 = {
y: camera.position.y
};
var to02 = {
y: yPos02
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from02)
.to(to02, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
case 'Ypos03':
var from03 = {
y: camera.position.y
};
var to03 = {
y: yPos03
};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from03)
.to(to03, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function() {
camera.position.set(this.y);
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.onComplete(function() {
camera.lookAt(new THREE.Vector3(0, 0, 0));
})
.start();
break;
}
}
In my main website where the iFrame is, I have 3 buttons.
Once one of them is pressed I want the camera to animate to the new Y position.
export function button03_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos03'});
console.log("cameraPos = -300");
}
export function button02_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos02'});
console.log("cameraPos = 0");
}
export function button01_click(event, $w) {
$w("#html2").postMessage({cameraYpos: 'Ypos01'});
console.log("cameraPos = 300");
}
This is my animate function
function animate() {
TWEEN.update();
requestAnimationFrame(animate);
render();
}
and this is my render function
function render() {
camera.lookAt(scene.position);
camera.position.x += ( - mouseX - camera.position.x ) * 0.05;
camera.lookAt( scene.position );
webglRenderer.render(scene, camera);
}
I manged to get it working with out a tween but now with the tween set
as soon as I press one of the buttons the model disappears from view.
I am sorry for not having a live version I am under strict NDA and switching the models just for this is allot of work. hope you understand.
Any help is most appreciated.
Thanks
You can see the full code here
<script>
/* Global vars
---------------------------------------------------
*/
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var camera, scene;
var canvasRenderer, webglRenderer;
var models_loaded = false;
var textures_loaded = false;
var container, mesh, geometry, loader, preloader;
var cameraPos
var yPos01 = 300;
var yPos02 = 0;
var yPos03 = -300;
var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;
var light;
var mouseX = 0, mouseY = 0;
/*
---------------------------------------------------
*/
/* Global materials and lighting controls
---------------------------------------------------
*/
//material
var roughness = 0.83;
var metal = 0.8;
var diffuse = 0x675f00;
//lights
var environmentInt = 0.5;
var ambiLightInt = 0.2;
var dirLightInt = 1.2;
var dirLightScalar = 1;
var hemiLightInt = 1;
/*
---------------------------------------------------
*/
/* Page Preloader
---------------------------------------------------
*/
preloader = document.createElement('img');
preloader.onload = function(){
window.addEventListener("mousemove", onmousemove, false);
init();
animate();
}
preloader.src = "https://assets.parastorage.com/marketingstudio/jessica_walsh/06/textures_512/preloader.gif";
preloader.className = "preloader";
document.body.appendChild(preloader);
/*
---------------------------------------------------
*/
/* init start
-----------------------------------------------------------------------------------------------------------------------------
*/
function init() {
/* 3D Json Loader
---------------------------------------------------
*/
container = document.createElement('div');
container.className = 'container';
container.style.visibility = 'hidden';
document.body.appendChild(container);
var manager = new THREE.LoadingManager();
manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
function onComplete(){
if(models_loaded && textures_loaded){
document.body.removeChild(preloader);
container.style.visibility = 'visible';
container.style.opacity =1;
SITE_BACKGROUNDcurrentVideovideo.play();
console.log( 'Loading completed');
}
}
manager.onLoad = function ( ) {
models_loaded = true;
onComplete();
};
manager.onProgress = function ( url, itemsLoaded, itemsTotal ) {
//console.log( 'Loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
manager.onError = function ( url ) {
//console.log( 'There was an error loading ' + url );
};
loader = new THREE.JSONLoader(manager);
/*
---------------------------------------------------
*/
/* Creating the camera
---------------------------------------------------
*/
camera = new THREE.PerspectiveCamera(20, window.innerWidth / window.innerHeight, 10, 1500);
camera.position.z = 340;
/* Passing event through the iframe
---------------------------------------------------
*/
window.onmessage = function (evt) {
switch (evt.data.cameraYpos) {
case 'Ypos01':
var from01 = {y: camera.position.y};
var to01 = {y: yPos01};
TWEEN.removeAll();
var tween01 = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
case 'Ypos02':
var from02 = {y: camera.position.y};
var to02 = {y: yPos02};
TWEEN.removeAll();
var tween02 = new TWEEN.Tween(from02)
.to(to02, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
case 'Ypos03':
var from03 = {y: camera.position.y};
var to03 = {y: yPos03};
TWEEN.removeAll();
var tween03 = new TWEEN.Tween(from03)
.to(to03, 600)
.easing(TWEEN.Easing.Linear.None)
.onUpdate(function () {
camera.position.set(this.y);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
break;
}
};
/* Bulding the scene
---------------------------------------------------
*/
scene = new THREE.Scene();
//Lights
scene.add(new THREE.AmbientLight(0xffffff, ambiLightInt));
/* Main light
---------------------------------------------------
*/
light = new THREE.DirectionalLight(0xffffff, dirLightInt);
//light.position.set(100, -350, 0);
light.position.multiplyScalar(dirLightScalar);
//light.position.x = 100;
light.position.y = 100;
light.position.z = 100;
//Shadow parameters
light.castShadow = true;
light.shadowCameraVisible = true;
//light.shadowBias = 0.001;
light.shadowMapWidth = 1024;
light.shadowMapHeight = 1024;
//Shadow camera fov and position
var d = 50;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d;
light.shadowCameraBottom = -d;
light.shadowcameranear = 0.1;
light.shadowCameraFar = 2000;
light.shadowcamerafov = 30;
light.shadowDarkness = 0;
scene.add(light);
/*
---------------------------------------------------
*/
//Skylight
var skylight = new THREE.HemisphereLight( 0xffffff, 0x080820, hemiLightInt );
scene.add( skylight );
/* Texture Loader
---------------------------------------------------
*/
var tx_manager = new THREE.LoadingManager();
tx_manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
//console.log(itemsTotal);
//console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
};
var total_textures = 0
tx_manager.itemEnd=function (url){
total_textures++;
if(total_textures == 20){
textures_loaded = true;
onComplete();
}
//console.log(++total_textures);
}
tx_manager.onLoad = function ( x) {
console.log(textureLoader);
//console.log( 'tx_manager complete!');
};
var textureLoader = new THREE.TextureLoader(tx_manager);
/*
---------------------------------------------------
*/
/* Environment map images
---------------------------------------------------
*/
var envUrls = [
'textures/env/02/px.jpg',
'textures/env/02/nx.jpg',
'textures/env/02/py.jpg',
'textures/env/02/ny.jpg',
'textures/env/02/pz.jpg',
'textures/env/02/nz.jpg'
],
// wrap it up into the object that we need
cubemap = THREE.ImageUtils.loadTextureCube(envUrls);
// set the format, likely RGB unless you've gone crazy
cubemap.format = THREE.RGBFormat;
/*
---------------------------------------------------
*/
/* 3D Json files loading
---------------------------------------------------
*/
// TRUNK 01
loader.load( "models/trunk_01.json", function( geometry, mat ) {
//var trunk_color = 0x0061ff;
//var trunk_01_color = textureLoader.load( "textures/trunk_01_curvature.jpg" );
var trunk_01_normal = textureLoader.load( "textures_512/trunk_01_normal.jpeg" );
var trunk_01_roughness = textureLoader.load( "textures_512/trunk_01_roughness.jpeg" );
trunk_01_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: trunk_01_roughness,
normalMap: trunk_01_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var trunk_01 = new THREE.Mesh( geometry, mat );
trunk_01.material = trunk_01_Material;
trunk_01.scale.set( 1, 1, 1 );
trunk_01.position.x = 0;
trunk_01.position.z = 0;
trunk_01.position.x = 0;
trunk_01.castShadow = true;
trunk_01.receiveShadow = true;
trunk_one = trunk_01;
scene.add( trunk_01 );
//controls_01 = new THREE.DeviceOrientationControls(trunk_one, true);
} );
// TRUNK 02
loader.load( "models/trunk_02.json", function( geometry, mat ) {
//var trunk_02_color = textureLoader.load( "textures/trunk_02_curvature.jpg" );
var trunk_02_normal = textureLoader.load( "textures_512/trunk_02_normal.jpeg" );
var trunk_02_roughness = textureLoader.load( "textures_512/trunk_02_roughness.jpg" );
trunk_02_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: trunk_02_roughness,
normalMap: trunk_02_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var trunk_02 = new THREE.Mesh( geometry, mat );
trunk_02.material = trunk_02_Material;
trunk_02.scale.set( 1, 1, 1 );
trunk_02.position.x = 0;
trunk_02.position.z = 0;
trunk_02.position.x = 0;
trunk_02.castShadow = true;
trunk_02.receiveShadow = true;
trunk_two = trunk_02;
scene.add( trunk_02 );
//controls_02 = new THREE.DeviceOrientationControls(trunk_two, true);
} );
// LEAFS
loader.load( "models/leafs.json", function( geometry, mat ) {
//var leafs_color = textureLoader.load( "textures/leafs_curvature.jpg" );
var leafs_normal = textureLoader.load( "textures_512/leafs_normal.jpeg" );
var leafs_roughness = textureLoader.load( "textures_512/leafs_roughness.jpeg" );
leafs_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: leafs_roughness,
normalMap: leafs_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var leafs = new THREE.Mesh( geometry, mat );
leafs.material = leafs_Material;
leafs.scale.set( 1, 1, 1 );
leafs.position.x = 0;
leafs.position.z = 0;
leafs.position.x = 0;
leafs.castShadow = true;
leafs.receiveShadow = true;
all_leafs = leafs;
scene.add( leafs );
//controls_03 = new THREE.DeviceOrientationControls(all_leafs, true);
} );
// ROSES
loader.load( "models/roses.json", function( geometry, mat ) {
//var roses_color = textureLoader.load( "textures/roses_curvature.jpg" );
var roses_normal = textureLoader.load( "textures_512/roses_normal.jpeg" );
var roses_roughness = textureLoader.load( "textures_512/roses_roughness.jpeg" );
roses_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: roses_roughness,
normalMap: roses_normal,
normalScale: new THREE.Vector2( 0.7, 0.7 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var roses = new THREE.Mesh( geometry, mat );
roses.material = roses_Material;
roses.scale.set( 1, 1, 1 );
roses.position.x = 0;
roses.position.z = 0;
roses.position.x = 0;
roses.castShadow = true;
roses.receiveShadow = true;
all_roses = roses;
scene.add( roses );
//controls_04 = new THREE.DeviceOrientationControls(all_roses, true);
} );
// TOPS
loader.load( "models/tops.json", function( geometry, mat ) {
//var tops_color = textureLoader.load( "textures/tops_curvature.jpg" );
var tops_normal = textureLoader.load( "textures_512/tops_normal.jpeg" );
var tops_roughness = textureLoader.load( "textures_512/tops_roughness.jpeg" );
tops_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: tops_roughness,
normalMap: tops_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var tops = new THREE.Mesh( geometry, mat );
tops.material = tops_Material;
tops.scale.set( 1, 1, 1 );
tops.position.x = 0;
tops.position.z = 0;
tops.position.x = 0;
tops.castShadow = true;
tops.receiveShadow = true;
all_tops = tops;
scene.add( tops );
//controls_05 = new THREE.DeviceOrientationControls(all_tops, true);
} );
// STEMS
loader.load( "jessica_walsh/06/models/stems.json", function( geometry, mat ) {
//var stems_color = textureLoader.load( "textures/stems_curvature.jpg" );
var stems_normal = textureLoader.load( "textures_512/stems_normal.jpeg" );
var stems_roughness = textureLoader.load( "textures_512/stems_roughness.jpeg" );
stems_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: stems_roughness,
normalMap: stems_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var stems = new THREE.Mesh( geometry, mat );
stems.material = stems_Material;
stems.scale.set( 1, 1, 1 );
stems.position.x = 0;
stems.position.z = 0;
stems.position.x = 0;
stems.castShadow = true;
stems.receiveShadow = true;
all_stems = stems;
scene.add( stems );
//controls_06 = new THREE.DeviceOrientationControls(all_stems, true);
} );
// THORNES 01
loader.load( "models/thornes_01.json", function( geometry, mat ) {
//var thornes_01_color = textureLoader.load( "textures/thornes_01_curvature.jpg" );
var thornes_01_normal = textureLoader.load( "textures_512/thornes_01_normal.jpeg" );
var thornes_01_roughness = textureLoader.load( "textures_512/thornes_01_roughness.jpeg" );
thornes_01_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: thornes_01_roughness,
normalMap: thornes_01_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var thornes_01 = new THREE.Mesh( geometry, mat );
thornes_01.material = thornes_01_Material;
thornes_01.scale.set( 1, 1, 1 );
thornes_01.position.x = 0;
thornes_01.position.z = 0;
thornes_01.position.x = 0;
thornes_01.castShadow = true;
thornes_01.receiveShadow = true;
thornes_one = thornes_01;
scene.add( thornes_01 );
//controls_07 = new THREE.DeviceOrientationControls(thornes_one, true);
} );
// THORNES 02
loader.load( "models/thornes_02.json", function( geometry, mat ) {
//var thornes_02_color = textureLoader.load( "textures/thornes_02_curvature.jpg" );
var thornes_02_normal = textureLoader.load( "textures_512/thornes_02_normal.jpeg" );
var thornes_02_roughness = textureLoader.load( "textures_512/thornes_02_roughness.jpeg" );
thornes_02_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: thornes_02_roughness,
normalMap: thornes_02_normal,
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var thornes_02 = new THREE.Mesh( geometry, mat );
thornes_02.material = thornes_02_Material;
thornes_02.scale.set( 1, 1, 1 );
thornes_02.position.x = 0;
thornes_02.position.z = 0;
thornes_02.position.x = 0;
thornes_02.castShadow = true;
thornes_02.receiveShadow = true;
thornes_two = thornes_02;
scene.add( thornes_02 );
//controls_08 = new THREE.DeviceOrientationControls(thornes_two, true);
} );
// SNAKE BOSY
loader.load( "models/snake_body.json", function( geometry, mat ) {
//var snake_body_color = textureLoader.load( "textures/snake_body_curvature.jpg" );
var snake_body_normal = textureLoader.load( "textures_512/snake_body_normal.jpeg" );
var snake_body_roughness = textureLoader.load( "textures_512/snake_body_roughness.jpg" );
snake_body_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: snake_body_roughness,
normalMap: snake_body_normal,
normalScale: new THREE.Vector2( 1.5, 1.5 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var snake_body = new THREE.Mesh( geometry, mat );
snake_body.material = snake_body_Material;
snake_body.scale.set( 1, 1, 1 );
snake_body.position.x = 0;
snake_body.position.z = 0;
snake_body.position.x = 0;
snake_body.castShadow = true;
snake_body.receiveShadow = true;
snake_b = snake_body;
scene.add( snake_body );
//controls_09 = new THREE.DeviceOrientationControls(snake_b, true);
} );
// SNAKE HEAD
loader.load( "models/snake_head.json", function( geometry, mat ) {
//var snake_head_color = textureLoader.load( "textures/snake_head_curvature.jpg" );
var snake_head_normal = textureLoader.load( "textures_512/snake_head_normal.jpeg" );
var snake_head_roughness = textureLoader.load( "textures_512/snake_head_roughness.jpeg" );
snake_head_Material = new THREE.MeshPhysicalMaterial( {
roughnessMap: snake_head_roughness,
normalMap: snake_head_normal,
normalScale: new THREE.Vector2( 2, 2 ),
map: null,
color: diffuse,
metalness: metal,
roughness: roughness,
envMap: cubemap,
envMapIntensity: environmentInt
} );
var snake_head = new THREE.Mesh( geometry, mat );
snake_head.material = snake_head_Material;
snake_head.scale.set( 1, 1, 1 );
snake_head.position.x = 0;
snake_head.position.z = 0;
snake_head.position.x = 0;
snake_head.castShadow = true;
snake_head.receiveShadow = true;
snake_h = snake_head;
scene.add( snake_head );
//controls_10 = new THREE.DeviceOrientationControls(snake_h, true);
} );
/* 3D Json files end
---------------------------------------------------
*/
// RENDERER
webglRenderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
webglRenderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
webglRenderer.domElement.style.position = "relative";
webglRenderer.shadowMapEnabled = true;
//webglRenderer.shadowMapSoft = true;
webglRenderer.shadowMapType = THREE.PCFSoftShadowMap; // options are THREE.BasicShadowMap | THREE.PCFShadowMap | THREE.PCFSoftShadowMap
container.appendChild(webglRenderer.domElement);
window.addEventListener('resize', onWindowResize, false);
}
/* init end
-----------------------------------------------------------------------------------------------------------------------------
*/
/* Mouse mapping
---------------------------------------------------
*/
function onmousemove(event) {
//mouseX = (event.clientX / window.innerWidth) * 2 - 1;
//mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
mouseX = ( event.clientX - windowHalfX ) / 6;
mouseY = ( event.clientY - windowHalfY ) / 4;
}
/*
---------------------------------------------------
*/
/* Window resize
---------------------------------------------------
*/
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
var f = (camera.aspect/1.583);
if(f < 1){
camera.position.z = 340 /(camera.aspect/1.583);
}else{
camera.position.z = 340;
}
camera.updateProjectionMatrix();
webglRenderer.setSize(window.innerWidth, window.innerHeight);
}
/*
---------------------------------------------------
*/
/* Animate
---------------------------------------------------
*/
function animate() {
TWEEN.update();
requestAnimationFrame(animate);
render();
}
/*
---------------------------------------------------
*/
/* Render
---------------------------------------------------
*/
function render() {
camera.lookAt(scene.position);
camera.position.x += ( - mouseX - camera.position.x ) * 0.05;
camera.lookAt( scene.position );
//Light Position
light.position.x += ( - mouseX - camera.position.x ) * 0.03;
light.lookAt( scene.position );
webglRenderer.render(scene, camera);
}
/*
---------------------------------------------------
*/
</script>
As seeinvisible said the tween is passing an object
with all 3 parameters and I tried to pass only the Y.
This is my updated tween
var from01 = {y: camera.position.y, z: camera.position.z};
var to01 = {y: yPos01, z: zPos01};
TWEEN.removeAll();
var tween = new TWEEN.Tween(from01)
.to(to01, 600)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(function () {
camera.position.set(camera.position.x, this.y, this.z);
camera.lookAt(0, 0, 0);
})
.onComplete(function () {
camera.lookAt(0, 0, 0);
})
.start();
In your onUpdate function you have camera.position.set(this.y). However that seems to take 3 parameters x, y, z. Try camera.position.setY(this.y) to only set the y value.

Object loaded with ObjLoader does not receive shadows in three.js

The model casts shadows on a ground-plane but it does NOT receive shadows from another small plane in front (which does cast shadows on the ground-plane), let alone from itself. Any ideas ???
var light = new THREE.DirectionalLight( 0xffefee, 1.2 );
light.position.set( 0, 40, 100 );
light.shadow.camera.left = -100;
light.shadow.camera.right = 100;
light.shadow.camera.top = 100;
light.shadow.camera.bottom = -100;
light.shadow.camera.far = 1000;
light.shadow.camera.near = 1;
light.shadow.mapSize.width = 512;
light.shadow.mapSize.height = 512;
light.castShadow = true;
light.shadowDarkness = 0.5;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
var femModel = null;
mtlLoader.setMaterialOptions({ side:THREE.DoubleSide });
mtlLoader.load( 'female02.mtl', function( materials ) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials( materials );
objLoader.setPath( 'female02/' );
objLoader.load( 'female02.obj', function ( object ) {
femModel = object;
femModel.position.set( 0, -80, 0 );
sceneRTTA.add( femModel );
}, onProgress, onError );
});
The setup function is called after it has loaded completely:
function setupmodel(){
femModel.traverse( function ( child ) {
if ( child instanceof THREE.Mesh ) {
child.castShadow = true;
child.receiveShadow = true;
}
} );
}
three.js 0.91.0

Threejs WebGLRenderTarget return different texture result with render to screen

The code
var renderTargetParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat, stencilBuffer: false,depthBuffer:false },
renderTargetOcl = new THREE.WebGLRenderTarget( SCREEN_WIDTH/4, SCREEN_HEIGHT/4, renderTargetParameters );
var effectFXAA = new THREE.ShaderPass( THREE.ShaderExtras[ "fxaa" ] );
effectFXAA.uniforms[ 'resolution' ].value.set( 1 / SCREEN_WIDTH, 1 / SCREEN_HEIGHT );
let hblur = new THREE.ShaderPass( THREE.ShaderExtras[ "horizontalBlur" ] );
let vblur = new THREE.ShaderPass( THREE.ShaderExtras[ "verticalBlur" ] );
var bluriness = 2;
hblur.uniforms[ 'h' ].value = bluriness / SCREEN_WIDTH*2;
vblur.uniforms[ 'v' ].value = bluriness / SCREEN_HEIGHT*2;
var renderModel = new THREE.RenderPass( this.scene, this.camera );
var renderModelOcl = new THREE.RenderPass( this.oclscene, this.oclcamera );
let grPass = new THREE.ShaderPass( THREE.ShaderExtras['Godrays'] );
grPass.needsSwap = true;
grPass.renderToScreen = false;
var finalPass = new THREE.ShaderPass( THREE.ShaderExtras['Additive'] );
finalPass.needsSwap = true;
finalPass.renderToScreen = true;
let oclcomposer = new THREE.EffectComposer( this.renderer, renderTargetOcl );
oclcomposer.addPass( renderModelOcl );
oclcomposer.addPass( hblur );
oclcomposer.addPass( vblur );
oclcomposer.addPass( hblur );
oclcomposer.addPass( vblur );
oclcomposer.addPass( grPass );
let renderTarget = new THREE.WebGLRenderTarget( SCREEN_WIDTH, SCREEN_HEIGHT, renderTargetParameters );
let finalcomposer = new THREE.EffectComposer( this.renderer, renderTarget );
finalcomposer.addPass( renderModel );
// finalcomposer.addPass( effectFXAA );
finalcomposer.addPass( finalPass );
finalPass.uniforms[ 'tAdd' ].value = oclcomposer.renderTarget1.texture;
I'm trying to make light scrattring.
When set grPass.renderToScreen = true; and finalPass.renderToScreen = false; i got right result.That means the first composer works well.
While i use the oclcomposer as texture to a plane material ,it get wrong result:the light keeps shinning and has green and yellow ring aroud it.
The result i want is like:,not shinning all the time and only has blue color.The wrong result disappears once i cut the screen.
From above,i think that's from the rendertarget which get wrong result,has no idea what it changes the texture
Oh,when i set grPass.needsSwap = false it works.Seem like an version change.

THREE js : Simplify a mesh to optimize performance

I have a mesh (image 1) and a parallelepipede, I add the intersection result of this 2 objects in a scene and I move the parallelepipede along my mesh repeating the same process to "cut" my mesh and get an exploded view of my mesh (image 2).
Problem is that the process time is more than 2 mins... I have tryed to reduce the mesh with meshmixxer but it's not enough... Does someone has another idea ?
function FirstCut() {
var scene, camera, renderer, controls;
//stl loader from https://threejs.org/examples/webgl_loader_stl.html
// cf example https://stemkoski.github.io/Three.js/CSG.html
//with obj
init();
animate();
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
camera = new THREE.PerspectiveCamera(75, 800 / 500, 1, 2000);
//camera.position.set(50, 500, 0);
camera.position.x = 50;
camera.position.y = 500;
camera.position.z = 0;
//var axeX = new THREE.Vector3(1, 0, 0);
//camera.rotateOnAxis(axeX, -1);
camera.lookAt(new THREE.Vector3(0, 500, 0));
controls = new THREE.OrbitControls(camera);
//les valeurs de min and max distance sont choisies pour que le filet ne disparaisse pas quand on le fait tourner
controls.minDistance = 0;
controls.maxDistance = 1000;
//scene
//var ambient = new THREE.AmbientLight(0x101030);
//scene.add(ambient);
//scene.add(new THREE.GridHelper(1000, 20));
//var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
//directionalLight.position.set(0, 1, 0);
//scene.add(directionalLight);
var widthH = parseInt(document.getElementById("wdthH").value) || 0; // H for Head
var widthT = parseInt(document.getElementById("wdthT").value) || 0; // T for tail
var height = parseInt(document.getElementById("hght").value) || 0; // flank
//création du pavé
var EmportePieceH = new THREE.BoxGeometry(300, 60, widthH);
var EmportePieceT = new THREE.BoxGeometry(300, 60, widthT);
var EmportePieceB = new THREE.BoxGeometry(height, 60, 520);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage et material
var EmportePieceMeshH = new THREE.Mesh(EmportePieceH, paveMaterial);
var EmportePieceMeshT = new THREE.Mesh(EmportePieceT, paveMaterial);
var paveMeshB = new THREE.Mesh(EmportePieceB, paveMaterial);
var zH = 247 - widthH / 2;
var zT = -247 + widthT / 2;
EmportePieceMeshH.position.set(0, 30, zH);
EmportePieceMeshT.position.set(0, 30, zT);
paveMeshB.position.set(-95 + height / 2, 30, 0);
var EmportePieceBSPH = new ThreeBSP(EmportePieceMeshH);
var EmportePieceBSPT = new ThreeBSP(EmportePieceMeshT);
var paveBSPB = new ThreeBSP(paveMeshB);
//scene.add(EmportePieceMeshH);
//scene.add(EmportePieceMeshT);
//scene.add(paveMeshB);
// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
var texture = new THREE.Texture();
var onProgress = function (xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
}
};
var onError = function (xhr) {
};
var loader = new THREE.ImageLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit_material_0.jpg', function (image) {
texture.image = image;
texture.needsUpdate = true;
});
var width = parseInt(document.getElementById("wdth").value) || 0;
//création du pavé
var paveGeom = new THREE.BoxGeometry(250, 250, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage parallélépipède avec material
var paveMesh = new THREE.Mesh(paveGeom, paveMaterial);
var z0 = -247 + widthH;
paveMesh.position.set(0, 0, z0);
var paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
//tableau des volumes
var tabVolumes = new Array();
// model
var loader = new THREE.OBJLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit.obj', function (object) {
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
var geo = new THREE.Geometry().fromBufferGeometry(child.geometry);
var filetMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
var filetMesh = new THREE.Mesh(geo, filetMaterial);
//scene.add(filetMesh);
var newBSPH, newBSPT, newBSPB, newBSP2, newBSP1, filletBSP
var filetBSP = new ThreeBSP(filetMesh);
newBSPH = filetBSP.intersect(EmportePieceBSPH);
newBSPT = filetBSP.intersect(EmportePieceBSPT);
newBSPB = filetBSP.intersect(paveBSPB);
newBSP2 = filetBSP.subtract(EmportePieceBSPH);
newBSP1 = newBSP2.subtract(paveBSPB);
filletBSP = newBSP1.subtract(EmportePieceBSPT);
////////////////////subtract//////////////////////////////
var newFilet = new THREE.Geometry();
newFilet = filletBSP.toGeometry();
var newFilletMesh = new THREE.Mesh(newFilet, new THREE.MeshBasicMaterial({ map: texture }));
newFilletMesh.position.set(0, 0, 0);
///////////////////////////////////création morceaux découpés///////////////////////////////////////////
var HeadFillet = new THREE.Geometry();
var TailFillet = new THREE.Geometry();
var degraissageFillet = new THREE.Geometry();
HeadFillet = newBSPH.toGeometry();
TailFillet = newBSPT.toGeometry();
degraissageFillet = newBSPB.toGeometry();
/////////////////////////////////calcul des volumes des 1ers morceaux/////////////////////////////////////////
if (widthH != 0) {
tabVolumes[0] = calculateVolume2(HeadFillet);
} else { tabVolumes[0] = 0;}
if (widthT != 0) {
//alert(tabVolumes[0]);
tabVolumes[1] = calculateVolume2(TailFillet);
} else { tabVolumes[1] = 0; }
if (height != 0) {
tabVolumes[2] = calculateVolume2(degraissageFillet);
} else { tabVolumes[2] = 0; }
var ind = 3;
var HeadFilletMesh = new THREE.Mesh(HeadFillet, new THREE.MeshBasicMaterial({ map: texture }));
var TailFilletMesh = new THREE.Mesh(TailFillet, new THREE.MeshBasicMaterial({ map: texture }));
var degraissageFilletMesh = new THREE.Mesh(degraissageFillet, new THREE.MeshBasicMaterial({ map: texture }));
HeadFilletMesh.position.set(0, 0, 20);
degraissageFilletMesh.position.set(-20, 0, 0);
TailFilletMesh.position.set(0, 0, -20);
scene.add(HeadFilletMesh);
scene.add(TailFilletMesh);
scene.add(degraissageFilletMesh);
//scene.add(newFilletMesh);
var cloneHeadFilletMesh = HeadFilletMesh.clone();
var cloneTailFilletMesh = TailFilletMesh.clone();
var clonedegraissageFilletMesh = degraissageFilletMesh.clone();
var mesh_decoupe = new THREE.Object3D;
mesh_decoupe.add(cloneHeadFilletMesh);
mesh_decoupe.add(cloneTailFilletMesh);
mesh_decoupe.add(clonedegraissageFilletMesh);
if (width != 0) {
var paveGeom = new THREE.BoxGeometry(300, 300, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
var fillet2BSP = new ThreeBSP(newFilletMesh);
var intersectionPave = new THREE.Geometry();
intersectionPave = fillet2BSP.intersect(paveBSP);
var geometryPave = new THREE.Geometry();
geometryPave = intersectionPave.toGeometry();
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
//alert(geometryPave.faces.length);
while (geometryPave.faces.length != 0) {
var z = paveMesh.position.z + width + 5;
paveMesh.position.set(0, 0, z);
paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
fillet2BSP = new ThreeBSP(newFilletMesh);
intersectionPave = filletBSP.intersect(paveBSP);
geometryPave = intersectionPave.toGeometry();
tabVolumes[ind] = calculateVolume2(geometryPave);
ind = ind + 1;
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
newMesh.position.set(0, 0, newMesh.position.z);
scene.add(newMesh);
var meshSave = newMesh.clone();
mesh_decoupe.add(meshSave);
}
document.body.style.cursor = '';
} else {
scene.add(newFilletMesh);
document.body.style.cursor = '';
tabVolumes[3] = 0;
tabVolumes[4] = calculateVolume2(newFilet);
}
// }
//}
//else {
// scene.add(newFilletMesh);
// tabVolumes[ind] = calculateVolume2(newFilet);
//}
//alert(calculateVolume2(newBSP.toGeometry()));
//afficher les volumes dans la textarea
var txtVolume = document.getElementById("txtVolume");
txtVolume.value = tabVolumes.join("\n");
//var exporter = new THREE.OBJExporter();
//var result = exporter.parse(mesh_decoupe);
//var blob = new Blob([result], { type: 'text/plain' });
//saveAs(blob, 'dechets.obj');
}
});
//scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 500, false);
document.getElementById('canvas3D').innerHTML = "";
document.getElementById('canvas3D').appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
camin();
renderer.render(scene, camera);
}
function camin() {
camera.position.y -= .1;
}
function volumeOfT(p1, p2, p3) {
var v321 = p3.x * p2.y * p1.z;
var v231 = p2.x * p3.y * p1.z;
var v312 = p3.x * p1.y * p2.z;
var v132 = p1.x * p3.y * p2.z;
var v213 = p2.x * p1.y * p3.z;
var v123 = p1.x * p2.y * p3.z;
return (-v321 + v231 + v312 - v132 - v213 + v123) / 6.0;
}
function calculateVolume2(object) {
var volumes = 0.0;
for (var i = 0; i < object.faces.length; i++) {
var Pi = object.faces[i].a;
var Qi = object.faces[i].b;
var Ri = object.faces[i].c;
//alert (Pi);
var P = new THREE.Vector3(object.vertices[Pi].x, object.vertices[Pi].y, object.vertices[Pi].z);
//alert(object.vertices[Pi].x);
var Q = new THREE.Vector3(object.vertices[Qi].x, object.vertices[Qi].y, object.vertices[Qi].z);
var R = new THREE.Vector3(object.vertices[Ri].x, object.vertices[Ri].y, object.vertices[Ri].z);
volumes += volumeOfT(P, Q, R);
}
return Math.abs(volumes);
}
}
function FirstCut() {
var scene, camera, renderer, controls;
//stl loader from https://threejs.org/examples/webgl_loader_stl.html
// cf example https://stemkoski.github.io/Three.js/CSG.html
//with obj
init();
animate();
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color(0xeeeeee);
camera = new THREE.PerspectiveCamera(75, 800 / 500, 1, 2000);
//camera.position.set(50, 500, 0);
camera.position.x = 50;
camera.position.y = 500;
camera.position.z = 0;
//var axeX = new THREE.Vector3(1, 0, 0);
//camera.rotateOnAxis(axeX, -1);
camera.lookAt(new THREE.Vector3(0, 500, 0));
controls = new THREE.OrbitControls(camera);
//les valeurs de min and max distance sont choisies pour que le filet ne disparaisse pas quand on le fait tourner
controls.minDistance = 0;
controls.maxDistance = 1000;
//scene
//var ambient = new THREE.AmbientLight(0x101030);
//scene.add(ambient);
//scene.add(new THREE.GridHelper(1000, 20));
//var directionalLight = new THREE.DirectionalLight(0xffffff, 1);
//directionalLight.position.set(0, 1, 0);
//scene.add(directionalLight);
var widthH = parseInt(document.getElementById("wdthH").value) || 0; // H for Head
var widthT = parseInt(document.getElementById("wdthT").value) || 0; // T for tail
var height = parseInt(document.getElementById("hght").value) || 0; // flank
//création du pavé
var EmportePieceH = new THREE.BoxGeometry(300, 60, widthH);
var EmportePieceT = new THREE.BoxGeometry(300, 60, widthT);
var EmportePieceB = new THREE.BoxGeometry(height, 60, 520);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage et material
var EmportePieceMeshH = new THREE.Mesh(EmportePieceH, paveMaterial);
var EmportePieceMeshT = new THREE.Mesh(EmportePieceT, paveMaterial);
var paveMeshB = new THREE.Mesh(EmportePieceB, paveMaterial);
var zH = 247 - widthH / 2;
var zT = -247 + widthT / 2;
EmportePieceMeshH.position.set(0, 30, zH);
EmportePieceMeshT.position.set(0, 30, zT);
paveMeshB.position.set(-95 + height / 2, 30, 0);
var EmportePieceBSPH = new ThreeBSP(EmportePieceMeshH);
var EmportePieceBSPT = new ThreeBSP(EmportePieceMeshT);
var paveBSPB = new ThreeBSP(paveMeshB);
//scene.add(EmportePieceMeshH);
//scene.add(EmportePieceMeshT);
//scene.add(paveMeshB);
// texture
var manager = new THREE.LoadingManager();
manager.onProgress = function (item, loaded, total) {
console.log(item, loaded, total);
};
var texture = new THREE.Texture();
var onProgress = function (xhr) {
if (xhr.lengthComputable) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log(Math.round(percentComplete, 2) + '% downloaded');
}
};
var onError = function (xhr) {
};
var loader = new THREE.ImageLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit_material_0.jpg', function (image) {
texture.image = image;
texture.needsUpdate = true;
});
var width = parseInt(document.getElementById("wdth").value) || 0;
//création du pavé
var paveGeom = new THREE.BoxGeometry(250, 250, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
// création du meshage parallélépipède avec material
var paveMesh = new THREE.Mesh(paveGeom, paveMaterial);
var z0 = -247 + widthH;
paveMesh.position.set(0, 0, z0);
var paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
//tableau des volumes
var tabVolumes = new Array();
// model
var loader = new THREE.OBJLoader(manager);
loader.load('/Scan/filet_1kg500-reposition-reduit.obj', function (object) {
object.traverse(function (child) {
if (child instanceof THREE.Mesh) {
child.material.map = texture;
var geo = new THREE.Geometry().fromBufferGeometry(child.geometry);
var filetMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true });
var filetMesh = new THREE.Mesh(geo, filetMaterial);
//scene.add(filetMesh);
var newBSPH, newBSPT, newBSPB, newBSP2, newBSP1, filletBSP
var filetBSP = new ThreeBSP(filetMesh);
newBSPH = filetBSP.intersect(EmportePieceBSPH);
newBSPT = filetBSP.intersect(EmportePieceBSPT);
newBSPB = filetBSP.intersect(paveBSPB);
newBSP2 = filetBSP.subtract(EmportePieceBSPH);
newBSP1 = newBSP2.subtract(paveBSPB);
filletBSP = newBSP1.subtract(EmportePieceBSPT);
////////////////////subtract//////////////////////////////
var newFilet = new THREE.Geometry();
newFilet = filletBSP.toGeometry();
var newFilletMesh = new THREE.Mesh(newFilet, new THREE.MeshBasicMaterial({ map: texture }));
newFilletMesh.position.set(0, 0, 0);
///////////////////////////////////création morceaux découpés///////////////////////////////////////////
var HeadFillet = new THREE.Geometry();
var TailFillet = new THREE.Geometry();
var degraissageFillet = new THREE.Geometry();
HeadFillet = newBSPH.toGeometry();
TailFillet = newBSPT.toGeometry();
degraissageFillet = newBSPB.toGeometry();
/////////////////////////////////calcul des volumes des 1ers morceaux/////////////////////////////////////////
if (widthH != 0) {
tabVolumes[0] = calculateVolume2(HeadFillet);
} else { tabVolumes[0] = 0;}
if (widthT != 0) {
//alert(tabVolumes[0]);
tabVolumes[1] = calculateVolume2(TailFillet);
} else { tabVolumes[1] = 0; }
if (height != 0) {
tabVolumes[2] = calculateVolume2(degraissageFillet);
} else { tabVolumes[2] = 0; }
var ind = 3;
var HeadFilletMesh = new THREE.Mesh(HeadFillet, new THREE.MeshBasicMaterial({ map: texture }));
var TailFilletMesh = new THREE.Mesh(TailFillet, new THREE.MeshBasicMaterial({ map: texture }));
var degraissageFilletMesh = new THREE.Mesh(degraissageFillet, new THREE.MeshBasicMaterial({ map: texture }));
HeadFilletMesh.position.set(0, 0, 20);
degraissageFilletMesh.position.set(-20, 0, 0);
TailFilletMesh.position.set(0, 0, -20);
scene.add(HeadFilletMesh);
scene.add(TailFilletMesh);
scene.add(degraissageFilletMesh);
//scene.add(newFilletMesh);
var cloneHeadFilletMesh = HeadFilletMesh.clone();
var cloneTailFilletMesh = TailFilletMesh.clone();
var clonedegraissageFilletMesh = degraissageFilletMesh.clone();
var mesh_decoupe = new THREE.Object3D;
mesh_decoupe.add(cloneHeadFilletMesh);
mesh_decoupe.add(cloneTailFilletMesh);
mesh_decoupe.add(clonedegraissageFilletMesh);
if (width != 0) {
var paveGeom = new THREE.BoxGeometry(300, 300, width);
var paveMaterial = new THREE.MeshBasicMaterial({ wireframe: true });
var fillet2BSP = new ThreeBSP(newFilletMesh);
var intersectionPave = new THREE.Geometry();
intersectionPave = fillet2BSP.intersect(paveBSP);
var geometryPave = new THREE.Geometry();
geometryPave = intersectionPave.toGeometry();
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
//alert(geometryPave.faces.length);
while (geometryPave.faces.length != 0) {
var z = paveMesh.position.z + width + 5;
paveMesh.position.set(0, 0, z);
paveBSP = new ThreeBSP(paveMesh);
//scene.add(paveMesh);
fillet2BSP = new ThreeBSP(newFilletMesh);
intersectionPave = filletBSP.intersect(paveBSP);
geometryPave = intersectionPave.toGeometry();
tabVolumes[ind] = calculateVolume2(geometryPave);
ind = ind + 1;
var newMesh = new THREE.Mesh(geometryPave, new THREE.MeshBasicMaterial({ map: texture }));
newMesh.position.set(0, 0, newMesh.position.z);
scene.add(newMesh);
var meshSave = newMesh.clone();
mesh_decoupe.add(meshSave);
}
document.body.style.cursor = '';
} else {
scene.add(newFilletMesh);
document.body.style.cursor = '';
tabVolumes[3] = 0;
tabVolumes[4] = calculateVolume2(newFilet);
}
// }
//}
//else {
// scene.add(newFilletMesh);
// tabVolumes[ind] = calculateVolume2(newFilet);
//}
//alert(calculateVolume2(newBSP.toGeometry()));
//afficher les volumes dans la textarea
var txtVolume = document.getElementById("txtVolume");
txtVolume.value = tabVolumes.join("\n");
//var exporter = new THREE.OBJExporter();
//var result = exporter.parse(mesh_decoupe);
//var blob = new Blob([result], { type: 'text/plain' });
//saveAs(blob, 'dechets.obj');
}
});
//scene.add(object);
}, onProgress, onError);
renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 500, false);
document.getElementById('canvas3D').innerHTML = "";
document.getElementById('canvas3D').appendChild(renderer.domElement);
}
function animate() {
requestAnimationFrame(animate);
camin();
renderer.render(scene, camera);
}
function camin() {
camera.position.y -= .1;
}
function volumeOfT(p1, p2, p3) {
var v321 = p3.x * p2.y * p1.z;
var v231 = p2.x * p3.y * p1.z;
var v312 = p3.x * p1.y * p2.z;
var v132 = p1.x * p3.y * p2.z;
var v213 = p2.x * p1.y * p3.z;
var v123 = p1.x * p2.y * p3.z;
return (-v321 + v231 + v312 - v132 - v213 + v123) / 6.0;
}
function calculateVolume2(object) {
var volumes = 0.0;
for (var i = 0; i < object.faces.length; i++) {
var Pi = object.faces[i].a;
var Qi = object.faces[i].b;
var Ri = object.faces[i].c;
//alert (Pi);
var P = new THREE.Vector3(object.vertices[Pi].x, object.vertices[Pi].y, object.vertices[Pi].z);
//alert(object.vertices[Pi].x);
var Q = new THREE.Vector3(object.vertices[Qi].x, object.vertices[Qi].y, object.vertices[Qi].z);
var R = new THREE.Vector3(object.vertices[Ri].x, object.vertices[Ri].y, object.vertices[Ri].z);
volumes += volumeOfT(P, Q, R);
}
return Math.abs(volumes);
}
}

How can I use Physi.js with a complex group geometry?

I create a modle car use three.js,and now , I need use Physi.js to add physical effect . But my modle car is too complex, many examples do this work like following:
var geometry = new THREE.CubeGeometry(4, 4, 4);
var material = new Physijs.createMaterial(new THREE.MeshPhongMaterial({
color: 0x4d6dad
}));
var mesh = new Physijs.BoxMesh(geometry, material, 1);
mesh.position.set(1.5, 10, 15);
mesh.rotation.y = Math.PI / 4;
scene.add(mesh);
As you can see, we can just create shapes like cube,sphere...But my car is too complex, how can I make it has physical effect?
My car just like this:
Click here to show my car picture
And these are a part of the codes:
function ModleCar(){
var carMain = new THREE.Object3D();
var meshGray = new THREE.MeshPhongMaterial({
color:0x4F4F4F,
side:THREE.DoubleSide
});
var meshYellow = new THREE.MeshPhongMaterial({
color:new THREE.Color('#FAF808'),
side:THREE.DoubleSide
});
var meshBlue = new THREE.MeshLambertMaterial({
color:new THREE.Color('#000042')
});
var meshWhite = new THREE.MeshPhongMaterial({
color:new THREE.Color('#E8E8E8'),
side:THREE.DoubleSide
});
var meshTest = new THREE.MeshPhongMaterial({
color:0x000000,
wireframe:true
});
var meshLightFront = new THREE.MeshBasicMaterial({
color:0xffffff
});
var meshBackLight = new THREE.MeshLambertMaterial({
color:new THREE.Color('#840000')
});
var meshLicencePlate = new THREE.MeshBasicMaterial({
color:new THREE.Color('#DCBA20'),
side:THREE.DoubleSide
});
var meshBlackLine = new THREE.MeshBasicMaterial({
color:0x000000,
wireframe:true
});
var meshRed = new THREE.MeshStandardMaterial({
color:0xff0000
});
function drawCarBody(){
var shape = new THREE.Shape();
shape.moveTo(10,10);
shape.splineThru([
new THREE.Vector2(10.2,11.8),
new THREE.Vector2(12,12)
])
shape.lineTo(18,12);
shape.splineThru([
new THREE.Vector2(19.8,11.8),
new THREE.Vector2(20,10)
])
shape.lineTo(20,4);
shape.lineTo(10,4);
shape.lineTo(10,10);
return shape;
}
var optionsCarBody = {
amount:25,
bevelThickness:1,
bevelSize:1,
beveSegments:20,
steps:20,
curveSegments:20
}
var carBodyOutside = setExtMaterial(drawCarBody,optionsCarBody,meshYellow);
carBodyOutside.position.set(-10,-3,15);
carBodyOutside.rotation.y = Math.PI/2;
//carMain.add(carBodyOutside);
var carBodyInside = new THREE.Mesh(new THREE.CubeGeometry(25,6.8,11.6),meshYellow);
//carMain.add(carBodyInside);
carBodyInside.position.set(3,5.18,0)
var meshFloor = new THREE.MeshLambertMaterial({
color:new THREE.Color('#840000')
});
var carFloor = new THREE.Object3D;
var carFloor1 = new THREE.Mesh(new THREE.CubeGeometry(17.6,0.5,11.6),meshFloor);
var carFloor2 = new THREE.Mesh(new THREE.CubeGeometry(3.6,0.5,11.6),meshFloor);
var carFloor3 = new THREE.Mesh(new THREE.CubeGeometry(5,0.5,9.3),meshFloor);
carFloor.add(carFloor1);
carFloor1.translateX(-3.1);
carFloor.add(carFloor2);
carFloor2.translateX(11.3);
carFloor.add(carFloor3);
carFloor3.translateX(7.4);
carFloor3.translateZ(-1.14);
var footstep = new THREE.Mesh(new THREE.CubeGeometry(4,1,1),meshYellow);
carFloor.add(footstep);
footstep.translateX(7.6);
footstep.translateZ(4);
footstep.translateY(-1.3);
var meshChair = new THREE.MeshPhongMaterial({
color:new THREE.Color('#198DE9')
})
var meshChairHandrail = new THREE.MeshPhongMaterial({
color:new THREE.Color('#EE890C')
})
function addChair(direction){
var chairTrestle = new THREE.Mesh(new THREE.CubeGeometry(4.2,1,0.5),meshGray);
chairTrestle.translateY(0.8);
//chair座椅,单个座椅
var chair = new THREE.Object3D();
chairTrestle.add(chair);
var chairBackrest = new THREE.Mesh(new THREE.CubeGeometry(1.8,2.3,0.2),meshChair);
chair.add(chairBackrest);
chairBackrest.translateY(1.8);
chairBackrest.rotation.x = -Math.PI/15;
chairBackrest.translateZ(-1);
var chairCushion = new THREE.Mesh(new THREE.CubeGeometry(1.8,1.5,0.2),meshChair);
chair.add(chairCushion);
chairCushion.rotation.x = Math.PI/2;
chairCushion.translateZ(-0.5);
var chairBackrestTop = new THREE.Mesh(new THREE.CylinderGeometry(0.2,0.2,1.8,15,1),meshChair);
chairBackrest.add(chairBackrestTop);
chairBackrestTop.translateY(1);
chairBackrestTop.rotation.z = Math.PI/2;
chair.translateX(-1)
var chairHandrail = new THREE.Mesh(new THREE.CubeGeometry(0.26,1.5,0.2),meshChairHandrail);
chairHandrail.translateY(1.1)
chairHandrail.rotation.x = Math.PI/2;
var chairHandrailLeft = chairHandrail.clone();
chairHandrailLeft.translateX(-1.95);
var chairHandrailRight = chairHandrail.clone();
chairHandrailRight.translateX(1.95);
switch(direction){
case "l": chairTrestle.add(chairHandrailLeft);break;
default : chairTrestle.add(chairHandrailRight);
}
chairTrestle.add(chairHandrail);
var chair2 = chair.clone();
chairTrestle.add(chair2);
chair2.translateX(2);
carFloor.add(chairTrestle);
chairTrestle.rotation.y = Math.PI/2;
return chairTrestle;
}
var chairRight1 = addChair();
chairRight1.translateX(-3.6);
chairRight1.translateZ(-10);
var chairDriver = new THREE.Mesh(new THREE.CubeGeometry(1.6,1.3,1.6),meshGray)
carFloor.add(chairDriver);
chairDriver.translateX(9.3);
chairDriver.translateZ(-4);
chairDriver.translateY(1);
chairDriver.rotation.y = Math.PI/2;
var chairDriverCushion = new THREE.Mesh(new THREE.CubeGeometry(2.5,2.5,0.3),meshChair);
chairDriver.add(chairDriverCushion);
chairDriverCushion.translateY(0.52);
chairDriverCushion.rotation.x = Math.PI/2;
var chairDriverBackrest = new THREE.Mesh(new THREE.CubeGeometry(2.5,2.7,0.3),meshChair);
chairDriver.add(chairDriverBackrest);
chairDriverBackrest.translateY(1.8);
chairDriverBackrest.translateZ(-1.3);
chairDriverBackrest.rotation.x = -Math.PI/18;
var chairDriverBackrestTop = new THREE.Mesh(new THREE.CylinderGeometry(0.3,0.3,2.3,15,1),meshChair);
chairDriverBackrest.add(chairDriverBackrestTop);
chairDriverBackrestTop.translateY(1.2);
chairDriverBackrestTop.rotation.z = Math.PI/2;
var steeringWheel = new THREE.Mesh(new THREE.TorusGeometry(0.6,0.1,20,30),meshGray);
carFloor.add(steeringWheel);
steeringWheel.translateX(11.5);
steeringWheel.translateY(3);
steeringWheel.translateZ(-4);
steeringWheel.rotation.x = Math.PI/2;
steeringWheel.rotation.z = Math.PI;
steeringWheel.rotation.y = Math.PI/4;
var steeringWheelInsidBar1 = new THREE.Mesh(new THREE.CylinderGeometry(0.1,-0.1,1.2,15,1),meshGray);
steeringWheel.add(steeringWheelInsidBar1);
var steeringWheelInsidBar2 = new THREE.Mesh(new THREE.CylinderGeometry(0,0.1,0.6,30,30),meshGray);
steeringWheel.add(steeringWheelInsidBar2);
steeringWheelInsidBar2.translateX(0.2);
steeringWheelInsidBar2.rotation.z = Math.PI/2;
var steeringWheelPole = new THREE.Mesh(new THREE.CylinderGeometry(0.1,0.1,2,15,1),meshGray);
steeringWheel.add(steeringWheelPole);
steeringWheelPole.rotation.x = Math.PI/2;
steeringWheelPole.translateY(1);
carMain.add(carFloor);
carFloor.position.set(2.7,2,0);
function drawCarHeadTopHead(){
var shape = new THREE.Shape();
shape.moveTo(10,10);
shape.splineThru([
new THREE.Vector2(10.2,11.8),
new THREE.Vector2(12,12)
])
shape.lineTo(18,12);
shape.splineThru([
new THREE.Vector2(19.8,11.8),
new THREE.Vector2(20,10)
])
shape.lineTo(20,10);
shape.lineTo(10,10);
return shape;
}
var optionsCarHeadTopHead = {
amount:2,
bevelThickness:0.1,
bevelSize:1,
beveSegments:20,
steps:20,
curveSegments:20
}
var carHeadTopHead = setExtMaterial(drawCarHeadTopHead,optionsCarHeadTopHead,meshYellow);
carHeadTopHead.rotation.y = Math.PI/2;
carHeadTopHead.translateX(-15);
carHeadTopHead.translateY(-3);
carHeadTopHead.translateZ(15);
var carHeadTopHeadDel = new THREE.Mesh(new THREE.CubeGeometry(3,3,15),meshGray);
carHeadTopHeadDel.translateZ(0);
carHeadTopHeadDel.translateY(6.8);
carHeadTopHeadDel.translateX(16.3);
carHeadTopHead = subtract(carHeadTopHead,carHeadTopHeadDel,meshYellow);
//carMain.add(carHeadTopHeadDel)
carMain.add(carHeadTopHead);
function drawCarHeadBottom(){
var shape = new THREE.Shape();
shape.moveTo(10,12);
shape.bezierCurveTo(10,16,20,16,20,12);
shape.lineTo(10,12);
return shape;
}
var optionsCarHeadBottom = {
amount:2.1,
bevelThickness:0.3,
bevelSize:1,
beveSegments:60,
steps:20,
curveSegments:60
}
var wheelOutsideBR = new THREE.Object3D();
carMain.add(wheelOutsideBR);
wheelOutsideBR.add(wheelOut);
wheelOutsideBR.position.set(15,-0.2,6);
var wheelOutsideAR = wheelOutsideBR.clone();
carMain.add(wheelOutsideAR);
wheelOutsideAR.translateX(-21.1);
var wheelOutsideAL = wheelOutsideAR.clone();
carMain.add(wheelOutsideAL);
wheelOutsideAL.translateZ(-12);
wheelOutsideAL.rotation.y = Math.PI;
var wheelOutsideBL = wheelOutsideAL.clone();
carMain.add(wheelOutsideBL);
wheelOutsideBL.translateX(-21.1);
var loader = new THREE.STLLoader();
loader.load("../model/Ban.stl",function(obj){
objectSTL = new THREE.Mesh(obj,meshWheel);
objectSTL.scale.set(0.03,0.03,0.03);
var o1 = objectSTL.clone();
var o2 = o1.clone();
var o3 = o2.clone();
wheelOutsideBR.add(objectSTL);
wheelOutsideAR.add(o1);
wheelOutsideAL.add(o2);
wheelOutsideBL.add(o3);
objectSTL.translateZ(-0.3);
o1.translateZ(-0.3);
o2.translateZ(-0.3);
o3.translateZ(-0.3);
});
console.log(3);
//门窗
var meshGlass = new THREE.MeshStandardMaterial({
color:new THREE.Color('#0CF5F7'),
transparent:true,
opacity:0.4,
side:THREE.FrontSide
});
//汽车前窗户
var windowFront = new THREE.Mesh(new THREE.CubeGeometry(1,5,9),meshTest);
windowFront.position.set(16,6,0);
//添加前窗玻璃
function drawFrontGlass(){
var shape = new THREE.Shape();
shape.moveTo(20,20);
shape.quadraticCurveTo(30,30.1,40,20);
shape.moveTo(40,19.1);
shape.quadraticCurveTo(30,30.1,20,19.9);
shape.moveTo(20,20);
return shape;
}
var optionsFrontGlass = {
amount:10,
bevelThickness:0,
bevelSize:1,
beveSegments:60,
steps:1,
curveSegments:60
}
var frontGlass = setExtMaterial(drawFrontGlass,optionsFrontGlass,meshGlass);
frontGlass.scale.set(0.41,0.1,0.6);
frontGlass.translateX(14);
frontGlass.translateY(8.5);
frontGlass.translateZ(12.3);
frontGlass.rotation.x = Math.PI/2;
frontGlass.rotation.z = -Math.PI/2;
carMain.add(frontGlass);
var windowRight = new THREE.Mesh(new THREE.CubeGeometry(23,4,1),meshGray);
//carMain.add(windowRight);
windowRight.position.set(2.5,6,6);
var rightGlass = new THREE.Mesh(new THREE.CubeGeometry(17.4,4,0.1),meshGlass);
carMain.add(rightGlass);
rightGlass.translateZ(5.8);
rightGlass.translateY(6);
rightGlass.translateX(-0.5);
var rightGlassSmall = new THREE.Mesh(new THREE.CubeGeometry(1.8,4,0.1),meshGlass);
carMain.add(rightGlassSmall);
rightGlassSmall.translateZ(5.8);
rightGlassSmall.translateY(6);
rightGlassSmall.translateX(13.3);
var windowRightBar1 = new THREE.Mesh(new THREE.CubeGeometry(0.5,4,0.2),meshYellow);
carMain.add(windowRightBar1);
windowRightBar1.position.set(-3.3,6,5.9);
var windowRightBar2 = windowRightBar1.clone();
windowRightBar2.translateX(5.8);
carMain.add(windowRightBar2);
var windowRightBar3 = windowRightBar2.clone();
windowRightBar3.translateX(5.6);
carMain.add(windowRightBar3);
var windowRightBar4 = windowRightBar3.clone();
windowRightBar4.translateX(4.4);
carMain.add(windowRightBar4);
var doorRight = new THREE.Mesh(new THREE.CubeGeometry(4,7.5,3),meshGray);
//carMain.add(doorRight);
doorRight.position.set(10.3,4.28,5);
var doorcaseBody = new THREE.Object3D();
carMain.add(doorcaseBody);
doorcaseBody.position.set(10.2,7.75,5.8)
//门框
var doorcaseTop = new THREE.Mesh(new THREE.CubeGeometry(4,0.5,0.2),meshYellow);
doorcaseBody.add(doorcaseTop);
var doorcaseBottom = doorcaseTop.clone();
doorcaseBody.add(doorcaseBottom);
doorcaseBottom.translateY(-7);
var doorcaseLeft = new THREE.Mesh(new THREE.CubeGeometry(0.5,7,0.2),meshYellow);
doorcaseBody.add(doorcaseLeft);
doorcaseLeft.translateX(-1.75);
doorcaseLeft.translateY(-3.5);
var doorcaseRight = doorcaseLeft.clone();
doorcaseBody.add(doorcaseRight);
doorcaseRight.translateX(3.5);
//门玻璃
var doorGlass = new THREE.Mesh(new THREE.CubeGeometry(4,7.5,0.1),meshGlass);
doorcaseBody.add(doorGlass);
doorGlass.translateY(-3.5);
//门滑道抓手
var doorSlidewayHandTop = new THREE.Mesh(new THREE.CubeGeometry(0.1,0.1,0.8),meshWhite);
doorcaseBody.add(doorSlidewayHandTop);
doorSlidewayHandTop.translateY(0.35);
doorSlidewayHandTop.translateZ(-0.3)
var doorSlidewayHandTop2 = new THREE.Mesh(new THREE.CubeGeometry(0.1,0.1,0.1),meshWhite);
doorSlidewayHandTop.add(doorSlidewayHandTop2);
doorSlidewayHandTop2.translateZ(0.35);
doorSlidewayHandTop2.translateY(-0.05)
var doorSlidewayHandBottom = doorSlidewayHandTop.clone();
doorcaseBody.add(doorSlidewayHandBottom);
doorSlidewayHandBottom.rotation.z = Math.PI;
doorSlidewayHandBottom.translateY(7.7);
//门滑道
var doorSlidewayTop = new THREE.Mesh(new THREE.CubeGeometry(4.6,0.2,0.1),meshBlue);
carMain.add(doorSlidewayTop);
doorSlidewayTop.translateZ(6);
doorSlidewayTop.translateY(8.1);
doorSlidewayTop.translateX(8.2);
var doorSlidewayBottom = doorSlidewayTop.clone();
carMain.add(doorSlidewayBottom);
doorSlidewayBottom.translateY(-7.65);
var windowLeft = new THREE.Mesh(new THREE.CubeGeometry(18,4,1),meshGray);
//carMain.add(windowLeft);
windowLeft.position.set(0,6,6)
windowLeft.translateZ(-12);
var leftGlass = new THREE.Mesh(new THREE.CubeGeometry(18,4,0.1),meshGlass);
carMain.add(leftGlass);
leftGlass.translateZ(-5.8);
leftGlass.translateY(6);
leftGlass.translateX(0);
var windowLeftBar1 = windowRightBar1.clone();
windowLeftBar1.translateZ(-11.8);
carMain.add(windowLeftBar1);
var windowLeftBar2 = windowRightBar2.clone();
windowLeftBar2.translateZ(-11.8);
carMain.add(windowLeftBar2);
var windowLeftBar3 = windowRightBar3.clone();
windowLeftBar3.translateZ(-11.8);
windowLeftBar3.scale.x = 3.7;
carMain.add(windowLeftBar3);
function drawDoorLeft(){
var shape = new THREE.Shape();
shape.moveTo(10,7);
shape.lineTo(13,7);
shape.lineTo(13,3.2);
shape.lineTo(12,2.5)
shape.lineTo(11.7,2);
shape.lineTo(10,2);
shape.lineTo(10,7);
return shape;
}
var optionsDoorLeft = {
amount:1,
bevelThickness:0,
bevelSize:1,
beveSegments:1,
steps:1,
curveSegments:30
}
var doorLeftHole = setExtMaterial(drawDoorLeft,optionsDoorLeft,meshTest);
//carMain.add(doorLeftHole);
doorLeftHole.translateZ(-6.9);
//司机门窗户
var dirverDoorWindow = new THREE.Mesh(new THREE.CubeGeometry(4,4,1),meshChair);
//carMain.add(dirverDoorWindow);
dirverDoorWindow.position.set(11.5,5.5,-5.8)
var driverGlass = new THREE.Mesh(new THREE.CubeGeometry(4,4,0.1),meshGlass);
carMain.add(driverGlass);
driverGlass.position.set(11.5,5.5,-5.7)
//后面窗户
var windowBack = new THREE.Mesh(new THREE.CubeGeometry(3,4,9),meshTest);
//carMain.add(windowBack);
windowBack.translateX(-10);
windowBack.translateY(6.5);
var backGlass = new THREE.Mesh(new THREE.CubeGeometry(0.1,4,9),meshGlass);
carMain.add(backGlass);
backGlass.position.set(-10.8,6.5,0)
//停车指示牌
var stopIndicatePlate = new THREE.Mesh(new THREE.CylinderGeometry(0.2,0.2,1,15,1),meshWhite);
carMain.add(stopIndicatePlate);
stopIndicatePlate.translateZ(-6.2);
stopIndicatePlate.translateY(3);
stopIndicatePlate.translateX(8);
var PlatePoint = new THREE.Object3D();
stopIndicatePlate.add(PlatePoint);
var plate1 = new THREE.Mesh(new THREE.CubeGeometry(1,0.5,0.1),meshWhite);
PlatePoint.add(plate1);
plate1.translateX(-0.5);
var plate2 = new THREE.Mesh(new THREE.CircleGeometry(1,6),createImageMesh("../image/stopplatepic.png"));
var plate3 = plate2.clone();
PlatePoint.add(plate3);
PlatePoint.add(plate2);
plate3.rotation.y = Math.PI;
plate3.translateX(1.8);
plate2.translateX(-1.8);
//前面车灯
var carLightFront = new THREE.Mesh(new THREE.CylinderGeometry(1,1,2,15,1,true),meshYellow);
carMain.add(carLightFront);
carLightFront.rotation.z = Math.PI/2;
carLightFront.translateY(-17);
carLightFront.translateZ(-5);
carLightFront.translateX(1.2);
var carLightFrontInside = new THREE.Mesh(new THREE.CylinderGeometry(1,1,1.6,15,1),meshLightFront);
carLightFront.add(carLightFrontInside);
carLightFrontInside.translateZ(0.1);
//添加车灯光线
var carFrontLight = new THREE.SpotLight(new THREE.Color("#FFFF7D"));
carMain.add(carFrontLight);
carFrontLight.position.set(17.5,1,-5.5);
carFrontLight.angle = Math.PI/6;
carFrontLight.decay = 1;
carFrontLight.distance = 100;
carFrontLight.penumbra = 1;
carFrontLight.power = 10;
var carLightTarget = new THREE.Object3D();
carMain.add(carLightTarget);
carLightTarget.position.set(50,-1.8,-5.4)
carFrontLight.target = carLightTarget;
var carLightFrontRight = carLightFront.clone();
carMain.add(carLightFrontRight);
carLightFrontRight.translateZ(10);
carLightFrontRight.rotation.x = Math.PI;
var carFrontLightRight = carFrontLight.clone();
carMain.add(carFrontLightRight);
carFrontLightRight.translateZ(11);
var carLightTargetRight = carLightTarget.clone();
carMain.add(carLightTargetRight);
carFrontLightRight.target = carLightTargetRight;
carLightTargetRight.position.set(50,-1.8,5.4);
//汽车尾灯
var lightBackPoint = new THREE.Object3D();
carMain.add(lightBackPoint);
addPoint(lightBackPoint);
lightBackPoint.position.set(-9.8,2,3.8);
function drawLightBack(){
var shape = new THREE.Shape();
shape.moveTo(0,0);
//shape.quadraticCurveTo(1,1,2,2);
shape.lineTo(2,0);
shape.lineTo(2,1);
shape.lineTo(0,1);
return shape;
}
var optionsLightBack = {
amount:1,
bevelThickness:2,
bevelSize:1,
beveSegments:60,
steps:2,
curveSegments:60
}
var lightBack = setExtMaterial(drawLightBack,optionsLightBack,meshBackLight);
lightBackPoint.add(lightBack);
lightBack.scale.set(0.7,0.7,0.5);
lightBack.rotation.y = -Math.PI/2;
var lightBackLeft = lightBack.clone();
carMain.add(lightBackLeft);
lightBackLeft.translateZ(9.8);
lightBackLeft.translateX(-5);
lightBackLeft.translateY(2);
lightBack.normalsNeedUpdate = true;
//后视镜
var rearviewMirrorPoint = new THREE.Object3D();
carMain.add(rearviewMirrorPoint);
rearviewMirrorPoint.translateX(15);
rearviewMirrorPoint.translateY(6);
rearviewMirrorPoint.translateZ(-5.8);
var rearviewPointsArray = [];
rearviewPointsArray.push(new THREE.Vector3(10,3.8,0));
rearviewPointsArray.push(new THREE.Vector3(12,3.8,0));
rearviewPointsArray.push(new THREE.Vector3(12,1.5,0));
rearviewPointsArray.push(new THREE.Vector3(12,0,0));
rearviewPointsArray.push(new THREE.Vector3(10,0,0));
var rearviewTrestle = new THREE.TubeGeometry(
new THREE.SplineCurve3(rearviewPointsArray),80,0.1
)
var rearviewMesh = new THREE.Mesh(rearviewTrestle,meshGray);
rearviewMirrorPoint.add(rearviewMesh);
rearviewMesh.scale.set(1,1,1);
rearviewMesh.rotation.y = Math.PI/6;
rearviewMesh.position.set(-8.5,-2,5);
var rearviewMirror = new THREE.Mesh(new THREE.SphereGeometry(1.6,30,30,0,Math.PI*2,0,Math.PI/5),meshGray);
rearviewMirrorPoint.add(rearviewMirror);
rearviewMirror.rotation.z = -Math.PI/2;
rearviewMirror.rotation.y = Math.PI/6;
rearviewMirror.translateY(0.4);
rearviewMirror.translateZ(0);
var rearviewMirrorRight = rearviewMirrorPoint.clone();
carMain.add(rearviewMirrorRight);
rearviewMirrorRight.rotation.z = Math.PI;
rearviewMirrorRight.rotation.y = Math.PI;
rearviewMirrorRight.translateZ(-11.6);
rearviewMirrorRight.translateX(0);
rearviewMirrorRight.translateY(0.2);
//添加车头文字标识
var fontLoader = new THREE.FontLoader();
fontLoader.load('../fonts/gentilis_bold.typeface.json',function(font){
var optionsNumber = {
size:1,
height:0.5,
font:font,
weight:'normal',
style:'normal',
bevelThickness:2,
bevelSize:2,
bevelSegments:2,
bevelEnable:true,
curveSegments:12,
steps:1
}
text = new THREE.Mesh(new THREE.TextGeometry("Lison's School Bus", optionsNumber),meshRed);
carMain.add(text);
text.scale.x = 0.8;
text.rotation.y = Math.PI/2;
text.position.set(16.76,8.6,4.4);
})
//车牌
//前面车牌
var licencePlateFront = new THREE.Mesh(new THREE.CubeGeometry(4,1.4,1),meshGray);
carMain.add(licencePlateFront);
licencePlateFront.translateX(19.6);
licencePlateFront.translateY(1.2);
licencePlateFront.rotation.y = Math.PI/2;
//后车牌
var licencePlateBack = licencePlateFront.clone();
carMain.add(licencePlateBack);
licencePlateBack.translateZ(-30.3);
licencePlateBack.translateY(1);
var car = new THREE.Object3D();
car.add(carMain);
carMain.position.set(-5,1.7,0);
//扣掉汽车前窗户
// var carBody = subtract(carBodyOutside,windowFront,meshYellow);
// carBody = subtract(carBody,windowBack,meshYellow);
// //扣掉汽车内部
// carBody = subtract(carBody,carBodyInside,meshYellow);
// //扣掉窗户和门
// carBody = subtract(carBody,windowRight,meshYellow);
// carBody = subtract(carBody,doorRight,meshYellow);
// carBody = subtract(carBody,windowLeft,meshYellow);
// carBody = subtract(carBody,doorLeftHole,meshYellow);
// carBody = subtract(carBody,dirverDoorWindow,meshYellow);
//
// carMain.add(carBody)
var ModleCar = {};
ModleCar = car;
ModleCar.wheelOutsideBR = wheelOutsideBR;
ModleCar.wheelOutsideBL = wheelOutsideBL;
ModleCar.wheelOutsideAR = wheelOutsideAR;
ModleCar.wheelOutsideAL = wheelOutsideAL;
ModleCar.meshLightFront = meshLightFront;
ModleCar.meshBackLight = meshBackLight;
ModleCar.PlatePoint = PlatePoint;
ModleCar.carFrontLight = carFrontLight;
ModleCar.carFrontLightRight = carFrontLightRight;
ModleCar.doorcaseBody = doorcaseBody;
return ModleCar;
/*
//小车模型外部文件引入的代码
var car = ModleCar();
scene.add(car);
var wheelOutsideBR = car.wheelOutsideBR;
var wheelOutsideBL = car.wheelOutsideBL;
var wheelOutsideAR = car.wheelOutsideAR;
var wheelOutsideAL = car.wheelOutsideAL;
var meshBackLight = car.meshBackLight;
var PlatePoint = car.PlatePoint;
var carFrontLight = car.carFrontLight;
var carFrontLightRight = car.carFrontLightRight;
var doorcaseBody = car.doorcaseBody;
var meshLightFront = car.meshLightFront;
*/
}

Resources