Not able to load more than one JSON using three.js - json

I am using the following loadmodel function to load a json into html. (jsons were exported from Blender)
(function init(){
console.log("Init")
loadmodel('object1');
loadmodel('object2');
loadmodel('object3');
loadmodel('object4');
requestAnimationFrame(rotate);
})();
function loadmodel(str){
var json = "{% static 'three/' %}" + str + '.json.gz';
var loader = new THREE.JSONLoader();
loader.load(json, function(geometry, materials){
alfaromeo = new THREE.Mesh(
geometry, new THREE.MeshFaceMaterial(materials)
);
alfaromeo.name = str;
names.push(str);
scene.add(alfaromeo);
});
}
My problem is that I have more than one json to load and when I call this function for each json, only the first one is getting loaded and the others are not. The same code is working well in my friends computer - all the jsons are loading well.
Is there anything I am missing?

As one of the comments stands, the JSONLoader is asynchronous, so the best way to be sure you are rendering what has been already downloaded is to trigger the render once you have download the JSON file in your onLoad method.
Actually what I would recommend is that you call just once to loadmodel to load just one JSON file, after the first download trigger again a new download, the last of your JSON file download should then trigger the scene render.
(function init(){
console.log("Init")
loadmodel('object1');
//this should be called when your last object has been added to the scene
//requestAnimationFrame(rotate);
})();
Just a quick n dirty example from your code:
function loadmodel(str)
{
var json = "{% static 'three/' %}" + str + '.json.gz';
var loader = new THREE.JSONLoader();
loader.load(json, function(geometry, materials){
alfaromeo = new THREE.Mesh(
geometry, new THREE.MeshFaceMaterial(materials));
alfaromeo.name = str;
names.push(str);
scene.add(alfaromeo);
// Add here proper logic to load next model...
if(str=="object1")
loadmodel("object2");
else if()...
else
{
console.info("done with all downloads!");
requestAnimationFrame(rotate);
}
});
}

Related

How to get coordinates from a KML file?

Is there any way to parse a kml file and get the coordinates from it with JavaScript?
I've tried doing it with "getElementsByTagName" (like here) but debugger says it's not a valid function.
Any ideas?
It's not easy but you can import the file xml and the parsing with jquery parseXML
// import the file --- se related function below
var content = getSelectedFileContent(importFilename);
// build an xmlObj for parsing
xmlDocObj = $($.parseXML(content));
function getSelectedFileContent(filename) {
// var importFilename = importAreaBaseURL + filename;
var request = new XMLHttpRequest();
request.open("GET", filename, false);
request.send(null);
return request.responseText;
};
at this point you can easy parse the xml obj for placemark and iterate over them for the tag/value you need via jquery
var placemarks = xmlDocObj.find("Placemark");
placemarks.each(function (index) {
if ($(this).find("Polygon").length > 0) {
tipoGeom = "Polygon";
tmpHtml = $(this).find("Polygon").find("outerBoundaryIs").find("coordinates").html();
gmlll_geom = kmlCoords2gmlll( tmpHtml);
inner = $(this).find("Polygon").find("innerBoundaryIs");
inner.each(function(index,el) {
$(el).find("coordinates").html(); // this are the coordinates for polygion
});
}
});
These are sample parts (an extract of functioning code .... not all you need) this code is just for a suggestion....

Setting local image as EaselJS background

I am building an EaselJS app, and I want the user to be able to select an image from their hard drive to be the background for the app. Once they are done interacting with the app and choose to submit I want to upload the image, but not before then. Is there a way I can do this? I am using Rails if that makes any difference.
You can use the method readAsDataURL from Filereader,then pass the result to an Image object and finally pass that image as parameter of a new easeljs.Bitmap object.
function previewFile(){
var file = input.files[0];
var reader = new FileReader();
reader.onloadend = function () {
image.src = reader.result;
var bitmap = new createjs.Bitmap(image);
stage.addChild(bitmap);
}
if (file) {
reader.readAsDataURL(file);
} else {
alert("fail");
}
}
I created a fiddle that does something like that:
https://jsfiddle.net/vampaynani/b5maj7nd/

Changing the pitch of the sound of an HTML5 audio node

I would like to change the pitch of a sound file using the HTML 5 Audio node.
I had a suggestion to use the setVelocity property and I have found this is a function of the Panner Node
I have the following code in which I have tried changing the call parameters, but with no discernible result.
Does anyone have any ideas, please?
I have the folowing code:
var gAudioContext = new AudioContext()
var gAudioBuffer;
var playAudioFile = function (gAudioBuffer) {
var panner = gAudioContext.createPanner();
gAudioContext.listener.dopplerFactor = 1000
source.connect(panner);
panner.setVelocity(0,2000,0);
panner.connect(gainNode);
gainNode.connect(gAudioContext.destination);
gainNode.gain.value = 0.5
source.start(0); // Play sound
};
var loadAudioFile = (function (url) {
var request = new XMLHttpRequest();
request.open('get', 'Sounds/English.wav', true);
request.responseType = 'arraybuffer';
request.onload = function () {
gAudioContext.decodeAudioData(request.response,
function(incomingBuffer) {
playAudioFile(incomingBuffer);
}
);
};
request.send();
}());
I'm trying to achieve something similar and I also failed at using PannerNode.setVelocity().
One working technique I found is by using the following package (example included in the README): https://www.npmjs.com/package/soundbank-pitch-shift
It is also possible with a biquad filter, available natively. See an example here: http://codepen.io/qur2/pen/emVQwW
I didn't find a simple sound to make it obvious (CORS restriction with ajax loading).
You can read more at http://chimera.labs.oreilly.com/books/1234000001552/ch04.html and https://developer.mozilla.org/en-US/docs/Web/API/BiquadFilterNode.
Hope this helps!

Zip a folder in as3 Adobe AIR

I have created an Air app that after user interaction will creat a folder with bmp's, xml and text doc's.
All works apart from making the final zip which needs to be automatic.
I have been looking for a solution to this but cant find it.
Perhaps I am just not seeing it, and if so, can someone show me please.
My original posting on this is here ---
zip many files with Air as3 flash
The closest thing I have found was this one --- zip a folder using fzip
But for some reason my coment was deleted which was --
I like this. It is the closest I have come to a working solution to my own problem. That said, I tested this and it works nicely as is. Can this script be moded to run without interaction??? I am in need of it for a program that I have written. ANY asistance is welcom........ apart from just pointing me to Adobe referance as it dose not have anything like what I need. (well that I can see or find)
So now I am re-asking the comunity.
For some reason it will work with manual selection and manual save-to, but not aotonomusly.
There must be a workround to this even if it requires another full page of script.
====================================================================
UPDATE:
For closing this off, I have finally got my solution.
You can find it here. "zip file contents have no data".
Hope that my problem can help someone in the future.
Try using the as3 commons zip library.
http://www.as3commons.org/as3-commons-zip/index.html
In order to do this you're going to need to load your directory, loop through all its contents and load each asset.
This code snippet includes a bulk loader to handle that for you.
warning
I pulled most of this code out of a project where I was doing something similar but I have not tested it as is. There may be some syntax errors!
private var zip:Zip;
zip = new Zip();
zip.addEventListener(IOErrorEvent.IO_ERROR, this.createNewZip); //creates a new zip
zip.addEventListener(Event.COMPLETE, handleZipLoaded); //loads the current zip, this is not shown here
zip.load(new URLRequest(File.applicationStorageDirectory.resolvePath("myZip.zip").url)); //path to your zip file
Method to create your new zip file
private function createNewZip(e:IOErrorEvent):void{
trace("no zip");
var stream:FileStream = new FileStream();
stream.open(File.applicationStorageDirectory.resolvePath("myZip.zip"), FileMode.WRITE);
zip.serialize(stream);
stream.close();
}
You can use this to add all items in a directory to your zip file.
private function addDirToZip():void{
var f:File = File.resolvePath("Your Dir");
//this will be called when your directory listing has loaded
f.addEventListener(FileListEvent.DIRECTORY_LISTING, handleDirLoaded);
//you can also get the dir listing inline and not use a listener
//doing it async will prevent ui lock
f.getDirectoryListingAsync();
}
Next your going to need to load all of the files
protected function handleDirLoaded(e:FileListEvent):void{
loadExternal = new Vector.<File>; //vector used to keep a handle on all files
e.target.removeEventListener(FileListEvent.DIRECTORY_LISTING, handleDirLoaded);
for(var i:int = 0 ; i < files.length ; i++){
var f:File = files[i] as File;
if(f.extension == "File Types you want"){ //you can do some file type checking here
loadExternal.push(f);
}
}
//start loading in the files
loadFile();
}
This will go through the loadExternal vector and load all files
private function loadFile():void{
currentFile = loadExternal.shift(); //returns the first item off the array
//load the file
var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoaded);
l.load(new URLRequest(currentFile.url));
}
Once each item is loaded you can store it for addition into the zip
private function handleLoaded(e:Event):void{
var l:Loader = e.target.loader as Loader;
l.contentLoaderInfo.removeEventListener(Event.COMPLETE, handleLoaded);
//storing everything in a dictionary
assets[currentFile.name] = l.content;
//if we still have items to load go and do it all again
if(loadExternal.length != 0){
loadFile();
} else {
//now all files are loaded so lets add them to the zip
addAssetsToZip();
}
}
This is where all the loaded files actually get put into the zip and it is saved
private funcion addAssetsToZip():void{
for(var fileName:String in assets){
var ba:ByteArray = new ByteArray(); //going to write this to the zip
//make an object that holds the data and filename
var data:Object = {};
data.name = fileName;
data.content = assets[fileName];
ba.writeObject(data);
//write this file to the zip
zip.addFile(key, ba, false);
}
//and finally save everything out
zip.close();
var stream:FileStream = new FileStream();
stream.open(File.applicationStorageDirectory.resolvePath("myZip.zip"), FileMode.WRITE);
zip.serialize(stream);
stream.close();
}

Binding JSON string to ListView in Metro apps?

I have a metro application(HTML5 & WinJS) in which am trying to display service data . Actually here am retrieving JSON data from my service but am unable to bind this data into listview . Anyone give me some working example.
Thank you.
You can use the WinJS.xhr() for this. You can read more about it on this link https://msdn.microsoft.com/pt-br/library/windows/apps/br229787.aspx and here is an example:
var path = "data/file.json";
function getData(path) {
WinJS.xhr({ url: path }).then(
function (response) {
var json = JSON.parse(response.responseText);
// Since this is an asynchronous function, you can't
// return the data, so you can:
// 1) retrieve the data to a namespace once the app loads.
var list = new WinJS.Binding.List(json);
Somenomespace.data = list;
// 2) or do all the binding inside the function.
var listView = document.getElementById("listViewID");
listView.winControl.itemDataSource = list.dataSource;
});
}
If you use the built in JSON.parse(jsonString) function you can loop through the content using a normal for loop as it then is a normal object and add it as usuall. Just remember to process or render the data.
Her is an example from code i had in a search page using listview:
var response = JSON.parse(data) ;
var originalResults = new WinJS.Binding.List();
for (x in response) {
originalResults.push(response[x]);
}
this.populateFilterBar(element, originalResults);
this.applyFilter(this.filters[0], originalResults);