- import System.IO;
- //import System.Drawing.Imaging;
- //**************************************************************************************************
- //************************************ The Whirld Project ******************************************
- //******************** http://www.unifycommunity.com/wiki/index.php?title=Whirld *******************
- //**************************************************************************************************
- class WhirldUTW extends System.Object {
- var whirld : Whirld;
- var objects : Hashtable = new Hashtable();
- var txts : Hashtable = new Hashtable();
- var txtArr : Array = new Array();
- var mshArr : Array = new Array();
- var trnArr : Array = new Array();
- var readChr = 0;
- var whirldBuffer : GameObject;
- var materials : Hashtable = new Hashtable();
- var prefabs : Array;
- function WhirldUTW(lnk : Whirld) {
- whirld = lnk;
- }
- //function Load() {
- //Load();
- //Game.Controller.StartCoroutine("Load");
- //}
- //function Cancel() {
- //Game.Controller.StopCoroutine("Load");
- //}
- function Load() {
- if(Game && Game.Controller) prefabs = new Array (Game.Controller.prefabs);
- if(whirld.data[0] != "[" && whirld.data[0] != "{") {
- whirld.status = WorldLoadCode.SyntaxError;
- return;
- }
- //Create Buffer Object
- whirldBuffer = new GameObject("WhirldBuffer");
- //Read headers
- while(true) {
- s = whirld.data[readChr];
- readChr += 1;
- if(readChr >= whirld.data.length) {
- whirld.status = WorldLoadCode.SyntaxError;
- return;
- }
- else if(s == "{") break; //Finished reading headers
- else if(s == "[") { //Beginning new header
- var n = "";
- var v = "";
- }
- else if(s == ":" && n == "") { //Header name read, read value
- n = v;
- v = "";
- }
- else if(s == "]") { //Header ended
- var vS = v.Split(","[0]);
- if(n == "txt") txtArr.Add(v);
- else if(n == "msh") mshArr.Add(v);
- else if(n == "trn") trnArr.Add(v);
- //else if(n == "rndFogColor") RenderSettings.fogColor = Color(parseFloat(vS[0]), parseFloat(vS[1]), parseFloat(vS[2]), 1);
- else if(n == "rndFogDensity") RenderSettings.fogDensity = parseFloat(v);
- else if(n == "rndAmbientLight") RenderSettings.ambientLight = Color(parseFloat(vS[0]), parseFloat(vS[1]), parseFloat(vS[2]), parseFloat(vS[3]));
- else whirld.worldParams.Add(n, v);
- }
- else v += s; //Header char read
- }
- //Download texture assets referenced in headers
- i = 1;
- for(var v : String in txtArr) { //[txt:name,url,wrapMode,anisoLevel]
- vS = v.Split(","[0]);
- whirld.statusTxt = "Downloading Texture " + i + " of " + txtArr.length + " (" + vS[0] + "): " + vS[1];
- var www : WWW = new WWW(vS[1]);
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nTexture Undownloadable: " + vS[0] + " " + vS[1] + " (" + www.error + ")";
- else {
- var txt = www.texture;
- if(!vS[0] || vS[0] == 0) txt.wrapMode = TextureWrapMode.Clamp;
- else txt.wrapMode = TextureWrapMode.Repeat;
- txt.anisoLevel = (vS[3] ? vS[3] : 1);
- //txt.Apply(true);
- //txt.Compress(true);
- txts.Add(vS[0], txt);
- whirld.statusTxt = "";
- }
- i++;
- }
- //Download mesh assets referenced in headers
- var meshesDown : int;
- var meshMaterials : Hashtable = new Hashtable();
- var meshMatLibs : Hashtable = new Hashtable();
- for(var v : String in mshArr) { //[msh:name,url]
- vS = v.Split(","[0]);
- var hasCollider = (vS.length > 2 ? parseInt(vS[2]) : 0);
- meshesDown++;
- whirld.statusTxt = "Downloading Mesh " + meshesDown + " of " + mshArr.length + " (" + vS[0] + "): " + vS[1];
- www = new WWW(whirld.getURL(vS[1]));
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nMesh Undownloadable: " + vS[0] + " " + vS[1] + " (" + www.error + ")";
- else {
- whirld.statusTxt = "Initializing " + vS[0] + "...";
- whirld.progress = 0;
- if(Application.isPlaying) yield;
- //Uncompress as necessary...
- var lastDot : int = vS[1].LastIndexOf(".");
- if(vS[1].Substring(lastDot + 1) == "gz") {
- var data : String = new Ionic.Zlib.GZipStream(new MemoryStream(), Ionic.Zlib.CompressionMode.Decompress).UncompressString(www.bytes);
- vS[1] = vS[1].Substring(0, lastDot);
- }
- lastDot = vS[1].LastIndexOf(".");
- var ext : String = vS[1].Substring(lastDot + 1);
- //Binary UniTyMesh Object
- if(ext == "utm") {
- var msh : Mesh = MeshSerializer.ReadMesh(www.bytes);
- }
- //.obj File
- else if(ext == "obj") {
- msh = new Mesh();
- var verts = new Array();
- var norms = new Array();
- var uvs = new Array();
- var tris = new Array();
- var triangles = new Array();
- var mats = new Array();
- var file : String[] = data.Split("\n"[0]);
- for (var str : String in file) {
- if(str == "") continue;
- var l : String[] = str.Split(" "[0]);
- if(l[0] == "v") verts.Add(Vector3(-parseFloat(l[1]), parseFloat(l[2]), parseFloat(l[3])));
- else if(l[0] == "vn") norms.Add(Vector3(parseFloat(l[1]), parseFloat(l[2]), parseFloat(l[3])));
- else if(l[0] == "vt") uvs.Add(Vector2(parseFloat(l[1]), parseFloat(l[2])));
- else if(l[0] == "f") {
- tris.Add(parseInt(l[2].Substring(0, l[2].IndexOf("/"))) - 1);
- tris.Add(parseInt(l[1].Substring(0, l[1].IndexOf("/"))) - 1);
- tris.Add(parseInt(l[3].Substring(0, l[3].IndexOf("/"))) - 1);
- }
- else if(l[0] == "usemtl") {
- if(meshMaterials.ContainsKey(l[1])) mats.Add(meshMaterials[l[1]]);
- else mats.Add(null);
- if(tris.length > 0) {
- triangles.Add(tris);
- tris = new Array();
- }
- }
- else if(l[0] == "mtllib") { //Time to load a material library!
- if(!meshMatLibs.ContainsKey(l[1])) {
- meshMatLibs.Add(l[1], true); //Only load a material library once, even if it is referenced by multiple meshes
- whirld.statusTxt = "Downloading Mesh Material Library: " + l[1];
- www = new WWW(whirld.getURL(l[1]));
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nMesh Material Library Undownloadable: " + l[1] + " (" + www.error + ")";
- else {
- whirld.statusTxt = "Initializing " + vS[0] + "...";
- whirld.progress = 0;
- yield;
- var meshlib : String[] = www.data.Split("\n"[0]);
- var curMat : Material;
- var meshTxtsDown : int = 0;
- var meshTxts : int = 0;
- var offset : int = -1;
- while(true) {
- offset = www.data.IndexOf("map_Ka", offset + 1);
- if(offset == -1) break;
- meshTxts++;
- }
- for (var meshline : String in meshlib) {
- var ml : String[] = meshline.Split(" "[0]);
- if(ml[0] == "newmtl") { //Beginning of new material
- if(curMat) { //Save current material
- meshMaterials.Add(curMat.name, curMat);
- }
- curMat = new Material(Shader.Find("VertexLit"));
- curMat.name = ml[1];
- }
- else if(ml[0] == "#Shader") { //Set shader of current material
- var shdr = meshline.Substring(8).Replace("Diffuse", "VertexLit");
- if(shdr != "VertexLit" && shdr != "VertexLit Fast") curMat.shader = Shader.Find(shdr);
- }
- else if(ml[0] == "Ka") { //Set color of current material
- curMat.color = Color(parseFloat(ml[1]), parseFloat(ml[2]), parseFloat(ml[3]), 1);
- }
- else if(ml[0] == "Kd") {
- curMat.SetColor("_Emission", Color(parseFloat(ml[1]), parseFloat(ml[2]), parseFloat(ml[3]), 1));
- }
- else if(ml[0] == "Ks") {
- curMat.SetColor("_SpecColor", Color(parseFloat(ml[1]), parseFloat(ml[2]), parseFloat(ml[3]), 1));
- }
- else if(ml[0] == "Ns") {
- curMat.SetFloat("_Shininess", parseFloat(ml[1]));
- }
- else if(ml[0] == "map_Ka") { //Set texture of current material
- meshTxtsDown += 1;
- whirld.statusTxt = "Downloading Mesh Texture " + meshTxtsDown + " of " + meshTxts + " (" + ml[7] + ")";
- www = new WWW(whirld.getURL(ml[7]));
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nMesh Texture Undownloadable: " + ml[7];
- else {
- whirld.statusTxt = "Initializing " + vS[0] + "...";
- whirld.progress = 0;
- yield;
- var mshTxt : Texture2D = new Texture2D(4, 4, TextureFormat.DXT1, true);
- www.LoadImageIntoTexture(mshTxt);
- mshTxt.Apply(true);
- mshTxt.Compress(true);
- curMat.mainTexture = mshTxt;
- curMat.mainTextureOffset = Vector2(parseFloat(ml[2]), parseFloat(ml[3]));
- curMat.mainTextureScale = Vector2(parseFloat(ml[5]), parseFloat(ml[6]));
- }
- }
- else if(ml[0] == "d") { //Set alpha cutoff of current material
- //curMat.shader = Shader.Find("Transparent/Cutout/VertexLit");
- //curMat.SetFloat("_Cutoff", parseFloat(ml[1]));
- }
- }
- if(curMat) { //Save last material (others get saves as file is read)
- meshMaterials.Add(curMat.name, curMat);
- }
- }
- }
- }
- }
- msh.vertices = verts.ToBuiltin(Vector3);
- msh.normals = norms.ToBuiltin(Vector3);
- msh.uv = uvs.ToBuiltin(Vector2);
- if(triangles.length > 0) {
- triangles.Add(tris);
- msh.subMeshCount = triangles.length;
- for(i=0; i < triangles.length; i++) msh.SetTriangles(triangles[i].ToBuiltin(int), i);
- }
- else msh.triangles = tris.ToBuiltin(int);
- }
- //Unknown File Type
- else whirld.info += "\nMesh Type Unrecognized: " + vS[0] + " " + vS[1] + " (." + ext + ")";
- msh.Optimize();
- if(hasCollider != 1) { //This mesh is being created, and it has a renderer
- var mshObj : GameObject = new GameObject(vS[0]);
- mshObj.AddComponent(MeshFilter);
- mshObj.GetComponent(MeshFilter).mesh = msh;
- mshObj.AddComponent(MeshRenderer);
- mshObj.GetComponent(MeshRenderer).materials = mats.ToBuiltin(Material);
- if(hasCollider != -1) { //This mesh has a collider, and it is the same as it's rendered mesh
- mshObj.AddComponent(MeshCollider);
- mshObj.GetComponent(MeshCollider).mesh = msh;
- }
- if(msh.uv.length < 1) whirld.TextureGO(mshObj);
- objects.Add(vS[0], mshObj);
- mshObj.transform.parent = whirldBuffer.transform;
- }
- else { //This mesh has a custom collider
- if(objects.ContainsKey(vS[0])) { //This mesh already exists, add a custom collider to it
- mshObj = objects[vS[0]];
- mshObj.AddComponent(MeshCollider);
- mshObj.GetComponent(MeshCollider).mesh = msh;
- }
- else { //This mesh is just a collider. It hasn't been created already, so we need to do that.
- mshObj = new GameObject(vS[0]);
- mshObj.AddComponent(MeshCollider);
- mshObj.GetComponent(MeshCollider).mesh = msh;
- objects.Add(vS[0], mshObj);
- mshObj.transform.parent = whirldBuffer.transform;
- }
- }
- whirld.statusTxt = "";
- }
- i++;
- }
- //Download terrain assets referenced in headers
- i = 1;
- for(var v : String in trnArr) {
- //v = "name;r:width,height,length,heightmapResolution //,detailResolution,controlResolution,textureResolution;h:heightMapUrl";
- var vS2 : String[] = v.Split(";"[0]);
- var tName = vS2[0];
- for(i2 = 1; i2<vS2.length; i2++) {
- var str : String[] = vS2[i2].Split(":"[0]);
- if(str[0] == "r") var tRes : String[] = str[1].Split(","[0]);
- else if(str[0] == "h") var tHtmp : String = whirld.getURL(str[1]);
- else if(str[0] == "l") var tLtmp : String = whirld.getURL(str[1]);
- else if(str[0] == "s") var tSpmp : String = whirld.getURL(str[1]);
- else if(str[0] == "s2") var tSpmp2 : String = whirld.getURL(str[1]);
- else if(str[0] == "t") var tTxts : String[] = str[1].Split(","[0]);
- else if(str[0] == "d") var tDtmp : String = whirld.getURL(str[1]);
- }
- whirld.statusTxt = "Downloading Terrain " + i + " of " + trnArr.length + " (" + tName + "): " + tHtmp;
- www = new WWW(tHtmp);
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nTerrain Undownloadable: " + tName + " " + tHtmp + " (" + www.error + ")";
- else {
- whirld.statusTxt = "Initializing " + tName + "...";
- whirld.progress = 0;
- if(Application.isPlaying) yield;
- var tWidth : int = parseInt(tRes[0]);
- var tHeight : int = parseInt(tRes[1]);
- var tLength : int = parseInt(tRes[2]);
- var tHRes : int = parseInt(tRes[3]);
- //var tDRes : int = parseInt(tRes[4]);
- //var tCRes : int = parseInt(tRes[5]);
- //var tBRes : int = parseInt(tRes[6]);
- var trnDat : TerrainData = new TerrainData();
- //Heights
- trnDat.heightmapResolution = tHRes;
- //trnDat.Init(tCRes, tDRes, tBRes);
- var hmap = trnDat.GetHeights(0, 0, tHRes, tHRes);
- var br : BinaryReader;
- if(true) { //Terrain RAW file is compressed
- /*var stream = new DeflateStream(new MemoryStream(www.bytes), CompressionMode.Decompress);
- var buffer : byte[] = new byte[4096];
- var ms : MemoryStream = new MemoryStream();
- var bytesRead : int = 0;
- while (bytesRead > 0) {
- bytesRead = stream.Read(buffer, 0, buffer.Length);
- if (bytesRead > 0) ms.Write(buffer, 0, bytesRead);
- }
- br = new BinaryReader(ms);*/
- br = new BinaryReader(new MemoryStream(new Ionic.Zlib.GZipStream(new MemoryStream(), Ionic.Zlib.CompressionMode.Decompress).UncompressBuffer(www.bytes)));
- }
- else br = new BinaryReader(new MemoryStream(www.bytes));
- for (var x : int = 0; x < tHRes; x++) for (var y : int = 0; y < tHRes; y++) hmap[x, y] = br.ReadUInt16() / 65535.00000000;
- trnDat.SetHeights(0, 0, hmap);
- trnDat.size = Vector3(tWidth, tHeight, tLength);
- //Textures
- if(tTxts) {
- var splatPrototypes : SplatPrototype[] = new SplatPrototype[tTxts.length];
- for(i=0; i < tTxts.length; i++) {
- var splatTxt : String[] = tTxts[i].Split("="[0]);
- var splatTxtSize : String[] = splatTxt[1].Split("x"[0]);
- whirld.statusTxt = "Downloading Terrain Texture " + (i + 1) + " of " + tTxts.length + " (" + splatTxt[0] + ")";
- www = new WWW(whirld.getURL(splatTxt[0]));
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nTerrain Texture Undownloadable: #" + (i + 1) + " (" + splatTxt[0] + ")";
- else {
- whirld.statusTxt = "Initializing Terrain Texture " + (i + 1) + " of " + tTxts.length + "...";
- yield;
- splatPrototypes[i] = new SplatPrototype();
- splatPrototypes[i].texture = new Texture2D(4, 4, TextureFormat.DXT1, true);
- www.LoadImageIntoTexture(splatPrototypes[i].texture);
- splatPrototypes[i].texture.Apply(true);
- splatPrototypes[i].texture.Compress(true);
- splatPrototypes[i].tileSize = Vector2(parseInt(splatTxtSize[0]), parseInt(splatTxtSize[1]));
- }
- }
- }
- else {
- splatPrototypes = new SplatPrototype[whirld.worldTerrainTextures.length];
- for(i=0; i < whirld.worldTerrainTextures.length; i++) {
- splatPrototypes[i] = new SplatPrototype();
- splatPrototypes[i].texture = whirld.worldTerrainTextures[i];
- splatPrototypes[i].tileSize = Vector2(15, 15);
- }
- }
- trnDat.splatPrototypes = splatPrototypes;
- //Lightmap
- if(tLtmp) {
- whirld.statusTxt = "Downloading Terrain Lightmap (" + tName + ")";
- www = new WWW(tLtmp);
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nTerrain Lightmap Undownloadable: " + tName + " " + tLtmp + " (" + www.error + ")";
- else {
- trnDat.lightmap = www.texture;
- }
- }
- //Splatmap
- if(tSpmp) {
- if(tSpmp2) {
- whirld.statusTxt = "Downloading Augmentative Terrain Texturemap (" + tName + ")";
- www = new WWW(tSpmp2);
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- var mapColors2 = www.texture.GetPixels();
- }
- whirld.statusTxt = "Downloading Terrain Texturemap (" + tName + ")";
- www = new WWW(tSpmp);
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- whirld.progress = 0;
- whirld.statusTxt = "Mapping Terrain Textures...";
- yield;
- if (www.error != null) whirld.info += "\nTerrain Texturemap Undownloadable: " + tName + " " + tLtmp + " (" + www.error + ")";
- else {
- if (www.texture.format != TextureFormat.ARGB32 || www.texture.width != www.texture.height || Mathf.ClosestPowerOfTwo(www.texture.width) != www.texture.width) {
- whirld.info += "\nTerrain Splatmap Unusable: Splatmap must be in RGBA 32 bit format, square, and it's size a power of 2";
- }
- else {
- trnDat.alphamapResolution = www.texture.width;
- var splatmapData = trnDat.GetAlphamaps(0, 0, www.texture.width, www.texture.width);
- var mapColors = www.texture.GetPixels();
- var ht : int = www.texture.height;
- var wd : int = www.texture.width;
- for (y = 0; y < ht; y++) for (x = 0; x < wd; x++) for (z = 0; z < trnDat.alphamapLayers; z++) {
- if(z < 4) splatmapData[x,y,z] = mapColors[x * wd + y][z];
- else splatmapData[x,y,z] = mapColors2[x * wd + y][z-4];
- }
- trnDat.SetAlphamaps(0, 0, splatmapData);
- }
- }
- }
- //Details (rocks, trees, grass, etc)
- if(tDtmp) {
- whirld.statusTxt = "Downloading Terrain Details (" + tDtmp + ")";
- www = new WWW(tDtmp);
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nTerrain Details Undownloadable: " + tName + " " + tDtmp + " (" + www.error + ")";
- else {
- var treePrototypes : Array = new Array();
- var treeInstances : Array = new Array();
- var treeProto : TreePrototype;
- var detailProto : DetailPrototype;
- var detailPrototypes : Array = new Array();
- file = new Ionic.Zlib.GZipStream(new MemoryStream(), Ionic.Zlib.CompressionMode.Decompress).UncompressString(www.bytes).Split("\n"[0]);
- for (i=0; i < file.length; i++) {
- if(file[i] == "" || i == file.length - 1) { //Apply Existing Trees
- if(treeProto) {
- treePrototypes.Add(treeProto);
- treeProto = null;
- //continue;
- }
- if(detailProto) {
- detailPrototypes.Add(detailProto);
- detailProto = null;
- //continue;
- }
- }
- if(file[i].length > 10 && file[i].Substring(0, 10) == "detailmap2") {
- whirld.statusTxt = "Downloading Augmentative Terrain Detail Map (" + whirld.getURL(file[i].Substring(11)) + ")";
- www = new WWW(whirld.getURL(file[i].Substring(11)));
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nAugmentative Terrain Detail Map Undownloadable: " + tName + " " + file[i].Substring(11) + " (" + www.error + ")";
- else {
- tex = www.texture;
- pixels = www.texture.GetPixels();
- if(detailPrototypes.length > 4) var detLayer4 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 4);
- if(detailPrototypes.length > 5) var detLayer5 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 5);
- if(detailPrototypes.length > 6) var detLayer6 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 6);
- if(detailPrototypes.length > 7) var detLayer7 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 7);
- i2 = 0;
- for(iY = 0; iY < trnDat.detailResolution; iY++) {
- for(iX = 0; iX < trnDat.detailResolution; iX++) {
- if(detailPrototypes.length > 4) detLayer4[iX, iY] = Mathf.RoundToInt(pixels[i2].r * 16);
- if(detailPrototypes.length > 5) detLayer5[iX, iY] = Mathf.RoundToInt(pixels[i2].g * 16);
- if(detailPrototypes.length > 6) detLayer6[iX, iY] = Mathf.RoundToInt(pixels[i2].b * 16);
- if(detailPrototypes.length > 7) detLayer7[iX, iY] = Mathf.RoundToInt(pixels[i2].a * 16);
- i2 += 1;
- }
- }
- }
- }
- else if(file[i].length > 10 && file[i].Substring(0, 9) == "detailmap") {
- whirld.statusTxt = "Downloading Terrain Detail Map (" + whirld.getURL(file[i].Substring(10)) + ")";
- www = new WWW(whirld.getURL(file[i].Substring(10)));
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nTerrain Detail Map Undownloadable: " + tName + " " + file[i].Substring(10) + " (" + www.error + ")";
- else {
- tex = www.texture;
- pixels = www.texture.GetPixels();
- trnDat.detailResolution = www.texture.width;
- if(detailPrototypes.length > 0) var detLayer0 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 0);
- if(detailPrototypes.length > 1) var detLayer1 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 1);
- if(detailPrototypes.length > 2) var detLayer2 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 2);
- if(detailPrototypes.length > 3) var detLayer3 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 3);
- i2 = 0;
- for(iY = 0; iY < trnDat.detailResolution; iY++) {
- for(iX = 0; iX < trnDat.detailResolution; iX++) {
- if(detailPrototypes.length > 0) detLayer0[iX, iY] = Mathf.RoundToInt(pixels[i2].r * 16);
- if(detailPrototypes.length > 1) detLayer1[iX, iY] = Mathf.RoundToInt(pixels[i2].g * 16);
- if(detailPrototypes.length > 2) detLayer2[iX, iY] = Mathf.RoundToInt(pixels[i2].b * 16);
- if(detailPrototypes.length > 3) detLayer3[iX, iY] = Mathf.RoundToInt(pixels[i2].a * 16);
- i2 += 1;
- }
- }
- }
- }
- else if(file[i] == "tree") { //Create new tree prototype
- treeProto = new TreePrototype();
- }
- else if(file[i] == "detail") {
- detailProto = new DetailPrototype();
- }
- else if(treeProto) {
- if(file[i].Substring(0, 1) == "m") {
- //treeProto.prefab = Resources.Load(file[i].Substring(2));
- //treeProto.prefab = Game.Controller.prefab;
- //prefab.AddComponent(MeshFilter);
- //prefab.AddComponent(MeshRenderer);
- if(objects.ContainsKey(file[i].Substring(2))) {
- treeProto.prefab = prefabs.Pop();
- treeProto.prefab.name = file[i].Substring(2);
- if(!treeProto.prefab.GetComponent(MeshFilter)) treeProto.prefab.AddComponent(MeshFilter);
- treeProto.prefab.GetComponent(MeshFilter).mesh = objects[file[i].Substring(2)].GetComponent(MeshFilter).mesh;
- if(!treeProto.prefab.GetComponent(MeshRenderer)) treeProto.prefab.AddComponent(MeshRenderer);
- treeProto.prefab.GetComponent(MeshRenderer).materials = objects[file[i].Substring(2)].GetComponent(MeshRenderer).materials;
- //treeProto.prefab = objects[file[i].Substring(2)];
- }
- else whirld.info += "\nTerrain Detail Mesh not found: " + file[i].Substring(2);
- }
- else if(file[i].Substring(0, 1) == "b") treeProto.bendFactor = parseFloat(file[i].Substring(2));
- else if(file[i+1] == "") { //Read detail objects
- var treedat : String[] = file[i].Split(";"[0]);
- for(var tr : String in treedat) {
- if(!tr) continue;
- var tree = tr.Split(","[0]);
- if(!tree[0] || tree[0] == "") continue;
- var treeInstance = new TreeInstance();
- treeInstance.prototypeIndex = treePrototypes.length;
- treeInstance.position = Vector3(parseFloat(tree[0]), parseFloat(tree[1]), parseFloat(tree[2]));
- treeInstance.widthScale = parseFloat(tree[3]);
- treeInstance.heightScale = parseFloat(tree[4]);
- var c : float = Random.Range(.6, .7);
- treeInstance.color = Color(c - .15, c - .15, c - .15, 1);
- treeInstance.lightmapColor = Color(c + .15, c + .15, c + .15, 0);
- treeInstances.Add(treeInstance);
- }
- }
- }
- else if(detailProto) {
- l = file[i].Split(" "[0]);
- if(l[0] == "pO") {
- if(objects.ContainsKey(l[1])) {
- //detailProto.prototype = objects[l[1]];
- detailProto.prototype = prefabs.Pop();
- detailProto.prototype.name = l[1];
- if(!detailProto.prototype.GetComponent(MeshFilter)) detailProto.prototype.AddComponent(MeshFilter);
- detailProto.prototype.GetComponent(MeshFilter).mesh = objects[l[1]].GetComponent(MeshFilter).mesh;
- if(!detailProto.prototype.GetComponent(MeshRenderer)) detailProto.prototype.AddComponent(MeshRenderer);
- detailProto.prototype.GetComponent(MeshRenderer).material = objects[l[1]].GetComponent(MeshRenderer).material;
- }
- else whirld.info += "\nTerrain Detail Mesh not found: " + l[1];
- }
- else if(l[0] == "pT") {
- l[1] = whirld.getURL(l[1]);
- whirld.statusTxt = "Downloading Terrain Detail Texture (" + l[1] + ")";
- www = new WWW(l[1]);
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- if (www.error != null) whirld.info += "\nTerrain Detail Texture Undownloadable: " + l[1];
- else {
- whirld.statusTxt = "Initializing " + vS[0] + "...";
- whirld.progress = 0;
- yield;
- mshTxt = new Texture2D(4, 4, TextureFormat.DXT5, true);
- www.LoadImageIntoTexture(mshTxt);
- mshTxt.Apply(true);
- mshTxt.Compress(true);
- mshTxt.wrapMode = TextureWrapMode.Clamp;
- detailProto.prototypeTexture = mshTxt;
- }
- }
- else if(l[0] == "minW") detailProto.minWidth = parseFloat(l[1]);
- else if(l[0] == "maxW") detailProto.maxWidth = parseFloat(l[1]);
- else if(l[0] == "minH") detailProto.minHeight = parseFloat(l[1]);
- else if(l[0] == "maxH") detailProto.maxHeight = parseFloat(l[1]);
- else if(l[0] == "nS") detailProto.noiseSpread = parseFloat(l[1]);
- else if(l[0] == "bF") detailProto.bendFactor = parseFloat(l[1]);
- else if(l[0] == "hC") detailProto.healthyColor = Color(parseFloat(l[1]), parseFloat(l[2]), parseFloat(l[3]));
- else if(l[0] == "dC") detailProto.dryColor = Color(parseFloat(l[1]), parseFloat(l[2]), parseFloat(l[3]));
- else if(l[0] == "lF") detailProto.lightmapFactor = parseFloat(l[1]);
- else if(l[0] == "gL") detailProto.grayscaleLighting = (l[1] == "1" ? true : false);
- else if(l[0] == "rM") {
- if(l[1] == "GrassBillboard") detailProto.renderMode = DetailRenderMode.GrassBillboard;
- else if(l[1] == "VertexLit") detailProto.renderMode = DetailRenderMode.VertexLit;
- else detailProto.renderMode = DetailRenderMode.Grass;
- }
- else if(l[0] == "uM") detailProto.usePrototypeMesh = (l[1] == "1" ? true : false);
- }
- }
- trnDat.treePrototypes = treePrototypes.ToBuiltin(TreePrototype);
- trnDat.treeInstances = treeInstances.ToBuiltin(TreeInstance);
- trnDat.detailPrototypes = detailPrototypes.ToBuiltin(DetailPrototype);
- if(detailPrototypes.length > 0) trnDat.SetDetailLayer(0, 0, 0, detLayer0);
- if(detailPrototypes.length > 1) trnDat.SetDetailLayer(0, 0, 1, detLayer1);
- if(detailPrototypes.length > 2) trnDat.SetDetailLayer(0, 0, 2, detLayer2);
- if(detailPrototypes.length > 3) trnDat.SetDetailLayer(0, 0, 3, detLayer3);
- if(detailPrototypes.length > 4) trnDat.SetDetailLayer(0, 0, 4, detLayer4);
- if(detailPrototypes.length > 5) trnDat.SetDetailLayer(0, 0, 5, detLayer5);
- if(detailPrototypes.length > 6) trnDat.SetDetailLayer(0, 0, 6, detLayer6);
- if(detailPrototypes.length > 7) trnDat.SetDetailLayer(0, 0, 7, detLayer7);
- //trnDat.RefreshPrototypes();
- //trnDat.RecalculateTreePositions();
- }
- /*for(i=0; i<trnDat.treePrototypes.length; i++) {
- trnDat.treePrototypes[i].prefab.name = trnDat.treePrototypes[i].prefab.name.Replace(" ", "_");
- MeshWriteObj(trnDat.treePrototypes[i].prefab.GetComponent(MeshFilter), trnDat.treePrototypes[i].prefab.name);
- whirld.data = "[msh:" + trnDat.treePrototypes[i].prefab.name + "," + trnDat.treePrototypes[i].prefab.name + ".obj.gz]" + whirld.data;
- trnV += (trnV != "" ? "\n\n" : "") + "tree\nm:" + trnDat.treePrototypes[i].prefab.name + "\nb:" + trnDat.treePrototypes[i].bendFactor + "\n";
- for(var tree : TreeInstance in trnDat.treeInstances) {
- if(tree.prototypeIndex != i) continue;
- trnV += tree.position.x.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) + "," + tree.position.y.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) + "," + tree.position.z.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) + "," + tree.widthScale.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) + "," + tree.heightScale.ToString("F1", System.Globalization.CultureInfo.InvariantCulture) + ";";
- }
- }*/
- }
- //Go!
- var trnObj : GameObject = new GameObject(tName);
- trnObj.AddComponent(Terrain);
- trnObj.GetComponent(Terrain).terrainData = trnDat;
- trnObj.AddComponent(TerrainCollider);
- trnObj.GetComponent(TerrainCollider).terrainData = trnDat;
- objects.Add(tName, trnObj);
- GameObject.Destroy(trnObj);
- whirld.statusTxt = "";
- }
- i++;
- }
- //Begin reading first object
- readObject(whirld.world.transform);
- //Trash buffer objects
- GameObject.Destroy(whirldBuffer);
- //Success!
- //whirld.info = "World Loaded";
- whirld.status = WorldLoadCode.Success;
- }
- function readObject(parent : Transform) {
- var c : String; //Character
- var i : int = 0; //Index of param
- var n : String = ""; //Param name we are reading data for
- var v : String = ""; //Value we are building
- var d : Array = new Array(); //Array of all values in current param data
- var obj : GameObject; //Object we have created
- while(true) {
- if(readChr >= whirld.data.length) return;
- //Get Char
- s = whirld.data[readChr];
- //We just attempted to read past the end of the world data - the world file must have been malformed
- /*if(s == "") {
- whirld.info = "Malformed World File";
- whirld.status = WorldLoadCode.SyntaxError;
- }*/
- //Ignore spaces
- if(s == " " && false) { }
- //Name fully read, begin collecting param value(s)
- else if(s == ":") {
- n = v;
- v = "";
- }
- //Move to next section of value
- else if(s == ",") {
- d.Add(v);
- v = "";
- }
- //Begin recursively reading child object
- else if(s == "{") {
- readChr += 1;
- readObject(obj.transform);
- continue; //Continue to next obj once the child "thread" we just launched has finished parsing objects at it's level
- }
- //Assign current value to object, Begin reading new value
- else if(s == ";" || s == "}") {
- //Object name just read, create object
- if(!obj) {
- if(objects.ContainsKey(v)) {
- if(objects[v] != null) var goP : GameObject = objects[v];
- else Debug.Log("Whirld: Objects[" + v + "] is null");
- //else goP = gameObject.Find();
- }
- else {
- goP = Resources.Load(v);
- if(goP) objects.Add(v, goP);
- }
- if(goP) {
- obj = GameObject.Instantiate(goP);
- obj.name = v;
- }
- else {
- obj = new GameObject(v);
- objects.Add(v, obj);
- }
- obj.transform.parent = parent;
- var whirldObject : WhirldObject = obj.GetComponent(WhirldObject);
- if(whirldObject) whirldObject.params = new Hashtable();
- var lightSource : Light = obj.GetComponent(Light);
- }
- //Object already created, assign property to object
- else {
- if(n == "p" || (n == "" && i == 1)) obj.transform.localPosition = Vector3(parseFloat(d[0]), parseFloat(d[1]), parseFloat(v));
- else if((n == "r" || (n == "" && i == 2)) && d.length == 3) obj.transform.rotation = Quaternion(parseFloat(d[0]), parseFloat(d[1]), parseFloat(d[2]), parseFloat(v));
- else if((n == "r" || (n == "" && i == 2)) && d.length == 2) obj.transform.rotation = Quaternion.Euler(parseFloat(d[0]), parseFloat(d[1]), parseFloat(v));
- else if((n == "r" || (n == "" && i == 2)) && d.length == 0) obj.transform.rotation = Quaternion.identity;
- else if((n == "s" || (n == "" && i == 3)) && d.length == 0) obj.transform.localScale = Vector3.one * parseFloat(v);
- else if(n == "s" || (n == "" && i == 3)) obj.transform.localScale = Vector3(parseFloat(d[0]), parseFloat(d[1]), parseFloat(v));
- else if(n == "cc") {
- obj.AddComponent(CombineChildren);
- whirld.worldParams["ccc"] = 1;
- //if(!whirld.worldParams.ContainsKey("cc")) whirld.worldParams.Add("cc", 0);
- }
- else if(n == "m") {
- d.Add(v);
- MeshRead(obj, d);
- }
- else if(lightSource && n == "color") {
- lightSource.color.r = parseFloat(d[0]);
- lightSource.color.g = parseFloat(d[1]);
- lightSource.color.b = parseFloat(v);
- }
- else if(lightSource && n == "intensity") lightSource.intensity = parseFloat(v);
- else {
- if(whirldObject) whirldObject.params.Add(n, v);
- }
- }
- //Reset properties
- v = "";
- n = "";
- if(d.length > 0) d = new Array();
- i += 1;
- //Done reading this object
- if(s == "}") {
- //Finish up this object
- if(obj.name == "cube" || obj.name == "pyramid" || obj.name == "cone" || obj.name == "mesh") {
- whirld.TextureGO(obj);
- }
- var renderer : MeshRenderer = obj.GetComponent(MeshRenderer);
- if(renderer && (renderer.material == null || renderer.material.name == "Default-Diffuse (Instance)")) renderer.material = whirld.defaultMaterial;
- //Debug.Log(renderer.material);
- //Increment ReadChar
- readChr += 1;
- //Read the next object
- if(readChr < whirld.data.length && whirld.data[readChr] == "{") {
- readChr += 1;
- readObject(parent);
- return;
- }
- //Done reading objects at this level of recursion
- else {
- return;
- }
- }
- }
- //Assign char to property we are reading
- else {
- if(n) v += s; //Building value
- else n += s; //Building name
- }
- readChr += 1;
- }
- }
- function Save() {
- whirld.data += "[rndFogColor:" + RenderSettings.fogColor.r + "," + RenderSettings.fogColor.g + "," + RenderSettings.fogColor.b + "]";
- whirld.data += "[rndFogDensity:" + RenderSettings.fogDensity + "]";
- whirld.data += "[rndAmbientLight:" + RenderSettings.ambientLight.r + "," + RenderSettings.ambientLight.g + "," + RenderSettings.ambientLight.b + "," + RenderSettings.ambientLight.a + "]";
- //This thing has WorldData - grab it!
- var whirldObject : WhirldObject = whirld.world.GetComponent(WhirldObject);
- if(whirldObject) for (var dat : WhirldData in whirldObject.data) {
- whirld.data += "[" + dat.n + ":" + dat.v + "]";
- }
- var objects : Hashtable = new Hashtable();
- Save(null);
- var t : String = "";
- for(var de : DictionaryEntry in materials) {
- var mat : Material = de.Value;
- t += "\n\nnewmtl " + mat.name + "\nKa " + mat.color.r + " " + mat.color.g + " " + mat.color.b;
- if(mat.HasProperty("_Emission")) {
- var col : Color = mat.GetColor("_Emission");
- t += "\nKd " + col.r + " " + col.g + " " + col.b;
- }
- if(mat.HasProperty("_SpecColor")) {
- col = mat.GetColor("_SpecColor");
- t += "\nKs " + col.r + " " + col.g + " " + col.b;
- }
- if(mat.HasProperty("_Shininess")) t += "\nNs " + mat.GetFloat("_Shininess");
- if(mat.mainTexture) {
- //var file : String = EditorUtility.GetAssetPath(mat.mainTexture);
- //var fName : String = file.Substring(file.LastIndexOf("/") + 1);
- //File.Copy(file, whirld.path + fName);
- File.WriteAllBytes(whirld.path + mat.name + ".png", mat.mainTexture.EncodeToPNG());
- t += "\nmap_Ka -o " + mat.mainTextureOffset.x + " " + mat.mainTextureOffset.y + " -s " + mat.mainTextureScale.x + " " + mat.mainTextureScale.y + " " + mat.name + /*(mat.mainTexture.format == TextureFormat.ARGB32 ? ".png" : ".jpg")*/ ".jpg";
- }
- t += "\n#Shader " + mat.shader.name;
- if(mat.HasProperty("_BaseLight")) t += "\n#BaseLight " + mat.GetFloat("_BaseLight");
- if(mat.HasProperty("_AO")) t += "\n#AO " + mat.GetFloat("_AO");
- if(mat.HasProperty("_Occlusion")) t += "\n#Occlusion " + mat.GetFloat("_Occlusion");
- if(mat.HasProperty("_Cutoff")) t += "\n#Cutoff " + mat.GetFloat("_Cutoff");
- //t += "\nillum " + (mat.HasProperty("_SpecColor") ? 2 : 1);
- }
- if(t != "") System.IO.File.WriteAllText(whirld.path + "Whirld.mtl", "#Unity3D Whirld Materials" + t);
- }
- function Save(trobj : Transform) {
- for (var tr : Transform in (trobj == null ? whirld.world.transform : trobj)) {
- //Sanitize Names
- tr.gameObject.name = tr.gameObject.name.Replace(" ","_");
- var light : Light = tr.gameObject.GetComponent(Light);
- if(light) tr.gameObject.name = "Light";
- //Save boilerplate object data
- whirld.data += "{" + tr.gameObject.name + ";" + tr.localPosition.x.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "," + tr.localPosition.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "," + tr.localPosition.z.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + ";" + (tr.rotation == Quaternion.identity ? "0" : tr.rotation.eulerAngles.x.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "," + tr.rotation.eulerAngles.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "," + tr.rotation.eulerAngles.z.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) /*+ "," + tr.rotation.w*/) + ";" + (tr.localScale == Vector3.one ? 1 : tr.localScale.x.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "," + tr.localScale.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "," + tr.localScale.z.ToString("F3", System.Globalization.CultureInfo.InvariantCulture));
- //This thing hasn't been previously encountered
- if(!objects.ContainsKey(tr.gameObject.name)) {
- //Check for CombineChildren
- var combineChildren : CombineChildren = tr.gameObject.GetComponent(CombineChildren);
- if(CombineChildren) whirld.data += ";cc:1";
- //This thing has WorldData - grab it!
- var whirldObject : WhirldObject = tr.gameObject.GetComponent(WhirldObject);
- if(whirldObject) for (var dat : WhirldData in whirldObject.data) {
- whirld.data += ";" + dat.n + ":" + dat.v;
- }
- //This thing is a light source - save it's properties!
- if(light) {
- whirld.data += ";color:" + light.color.r + "," + light.color.g + "," + light.color.b + ";intensity:" + light.intensity;
- }
- //This thing is not a defined resource
- goP = Resources.Load(tr.gameObject.name);
- if(!goP) {
- //This thing has a mesh - include it!
- var mF : MeshFilter = tr.gameObject.GetComponent(MeshFilter);
- var mR : MeshRenderer = tr.gameObject.GetComponent(MeshRenderer);
- var mC : MeshCollider = tr.gameObject.GetComponent(MeshCollider);
- if(mF && mR.enabled) {
- //whirld.data += ";m:" + MeshWrite(mF);
- //whirld.data += ";ms:/" + tr.gameObject.name;
- //whirld.data += ";ms:" + String(System.Text.Encoding.ASCII.GetChars(MeshSerializer.WriteMesh(mF.mesh, false)));
- /*whirld.data = "[msh:" + tr.gameObject.name + ",http://domain.com/" + tr.gameObject.name + ".utm]" + whirld.data;
- MeshSerializer.WriteMeshToFileForWeb(mF.mesh, tr.gameObject.name + ".utm", false);*/
- MeshWriteObj(mF, tr.gameObject.name);
- whirld.data = "[msh:" + tr.gameObject.name + "," + tr.gameObject.name + ".obj.gz" + ((!mC || !mC.sharedMesh) ? ",-1" : "") + "]" + whirld.data;
- }
- if(mC && mC.sharedMesh) {
- if(!mF || !mR.enabled || mC.sharedMesh != mF.sharedMesh) {
- m = mC.sharedMesh;
- mD = "#Unity3D Whirld Collider\n\ng " + m.name + "\n";
- for(var v : Vector3 in m.vertices) mD += "v " + (-v.x).ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.z.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "\n";
- mD += "\n";
- for(var v : Vector3 in m.normals) mD += "vn " + (-v.x).ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.z.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "\n";
- mD += "\n";
- for(var v : Vector3 in m.uv) mD += "vt " + v.x.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "\n";
- mD += "\n";
- for (i=0; i<m.triangles.Length; i+=3) mD += "f " + (m.triangles[i+1]+1) + "/" + (m.triangles[i+1]+1) + "/" + (m.triangles[i+1]+1) + " " + (m.triangles[i]+1) + "/" + (m.triangles[i]+1) + "/" + (m.triangles[i]+1) + " " + (m.triangles[i+2]+1) + "/" + (m.triangles[i+2]+1) + "/" + (m.triangles[i+2]+1) + "\n";
- File.WriteAllBytes(whirld.path + tr.gameObject.name + "cldr.obj.gz", new Ionic.Zlib.GZipStream(new MemoryStream(), Ionic.Zlib.CompressionMode.Compress, 9).CompressString(mD));
- whirld.data = "[msh:" + tr.gameObject.name + "," + tr.gameObject.name + "cldr.obj.gz,1]" + whirld.data;
- }
- }
- //This is a terrain object! Save it's heightmap, lightmap, and splatmap
- var trn : Terrain = tr.gameObject.GetComponent(Terrain);
- if(trn) {
- var trnRes : String;
- var trnDat : TerrainData = trn.terrainData;
- //Save Heightmap
- var hmap = trnDat.GetHeights(0, 0, trnDat.heightmapWidth, trnDat.heightmapHeight);
- ms = new MemoryStream();
- var br : BinaryWriter = new BinaryWriter(ms);
- for (var x : int = 0; x < trnDat.heightmapWidth; x++) for (var y : int = 0; y < trnDat.heightmapHeight; y++) {
- var val : System.UInt16 = hmap[x, y] * 65535;
- br.Write(val);
- }
- var buffer : byte[] = ms.ToArray();
- File.WriteAllBytes(whirld.path + tr.gameObject.name + ".gz", new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, 9).CompressBuffer(buffer));
- trnRes += ";h:" + tr.gameObject.name + ".gz";
- //Save Lightmap
- if(trnDat.lightmap) {
- File.WriteAllBytes(whirld.path + tr.gameObject.name + "l.png", trnDat.lightmap.EncodeToPNG());
- trnRes += ";l:" + tr.gameObject.name + "l.png";
- }
- //Save Splatmap
- var sMap = trnDat.GetAlphamaps(0, 0, trnDat.alphamapWidth, trnDat.alphamapHeight);
- var sTxt : Texture2D = new Texture2D(trnDat.alphamapWidth, trnDat.alphamapHeight, TextureFormat.ARGB32, false);
- for (y = 0; y < trnDat.alphamapWidth; y++) for (x = 0; x < trnDat.alphamapHeight; x++) sTxt.SetPixel(y, x, Vector4((trnDat.alphamapLayers > 0 ? sMap[x,y,0] : 0), (trnDat.alphamapLayers > 1 ? sMap[x,y,1] : 0), (trnDat.alphamapLayers > 2 ? sMap[x,y,2] : 0), (trnDat.alphamapLayers > 3 ? sMap[x,y,3] : 0)));
- sTxt.Apply(false);
- File.WriteAllBytes(whirld.path + tr.gameObject.name + "s.png", sTxt.EncodeToPNG());
- trnRes += ";s:" + tr.gameObject.name + "s.png";
- if(trnDat.alphamapLayers > 4) { //Save Second Splat Map if there are more than 4 textures applied to this terrain
- sTxt = new Texture2D(trnDat.alphamapWidth, trnDat.alphamapHeight, TextureFormat.ARGB32, false);
- for (y = 0; y < trnDat.alphamapWidth; y++) for (x = 0; x < trnDat.alphamapHeight; x++) sTxt.SetPixel(y, x, Vector4((trnDat.alphamapLayers > 4 ? sMap[x,y,4] : 0), (trnDat.alphamapLayers > 5 ? sMap[x,y,5] : 0), (trnDat.alphamapLayers > 6 ? sMap[x,y,6] : 0), (trnDat.alphamapLayers > 7 ? sMap[x,y,7] : 0)));
- sTxt.Apply(false);
- File.WriteAllBytes(whirld.path + tr.gameObject.name + "s2.png", sTxt.EncodeToPNG());
- trnRes += ";s2:" + tr.gameObject.name + "s2.png";
- }
- //if(trnDat.splatPrototypes[0].texture.format == TextureFormat.RGB24) {
- trnRes += ";t:";
- for(i=0; i < trnDat.alphamapLayers; i++) {
- trnRes += (i > 0 ? "," : "") + tr.gameObject.name + "" + i + ".jpg=" + trnDat.splatPrototypes[i].tileSize.x + "x" + trnDat.splatPrototypes[i].tileSize.y;
- if(trnDat.splatPrototypes[0].texture.format == TextureFormat.RGB24) File.WriteAllBytes(whirld.path + tr.gameObject.name + "" + i + ".png", trnDat.splatPrototypes[i].texture.EncodeToPNG());
- /*image = Image.FromFile(whirld.path + tr.gameObject.name + "" + i + "o.png");
- foreach (var info : ImageCodecInfo in ImageCodecInfo.GetImageEncoders()) if (info.FormatDescription == "JPEG") {
- var encoder = info;
- break;
- }
- var parms : EncoderParameters = new EncoderParameters(1);
- parms.Param[0] = new EncoderParameter(Encoder.Compression, 40);
- image.Save(whirld.path + tr.gameObject.name + "" + i + ".png", jpegEncoder, parms);*/
- }
- //}
- //Save Trees
- var trnV = "";
- for(i=0; i<trnDat.treePrototypes.length; i++) {
- trnDat.treePrototypes[i].prefab.name = trnDat.treePrototypes[i].prefab.name.Replace(" ", "_");
- MeshWriteObj(trnDat.treePrototypes[i].prefab.GetComponent(MeshFilter), trnDat.treePrototypes[i].prefab.name);
- whirld.data = "[msh:" + trnDat.treePrototypes[i].prefab.name + "," + trnDat.treePrototypes[i].prefab.name + ".obj.gz]" + whirld.data;
- trnV += (trnV != "" ? "\n\n" : "") + "tree\nm:" + trnDat.treePrototypes[i].prefab.name + "\nb:" + trnDat.treePrototypes[i].bendFactor + "\n";
- for(var tree : TreeInstance in trnDat.treeInstances) {
- if(tree.prototypeIndex != i) continue;
- trnV += tree.position.x.ToString("F6", System.Globalization.CultureInfo.InvariantCulture) + "," + tree.position.y.ToString("F6", System.Globalization.CultureInfo.InvariantCulture) + "," + tree.position.z.ToString("F6", System.Globalization.CultureInfo.InvariantCulture) + "," + tree.widthScale.ToString("F6", System.Globalization.CultureInfo.InvariantCulture) + "," + tree.heightScale.ToString("F6", System.Globalization.CultureInfo.InvariantCulture) + ";";
- }
- }
- //Save Details
- if(trnDat.detailPrototypes.length > 0) {
- for(i=0; i<trnDat.detailPrototypes.length; i++) {
- var dP : DetailPrototype = trnDat.detailPrototypes[i];
- if(dP.prototype) dP.prototype.name = dP.prototype.name.Replace(" ", "_");
- trnV += (trnV != "" ? "\n\n" : "") + "detail";
- if(dP.prototype) {
- trnV += "\npO " + dP.prototype.name;
- MeshWriteObj(dP.prototype.GetComponent(MeshFilter), dP.prototype.name);
- whirld.data = "[msh:" + dP.prototype.name + "," + dP.prototype.name + ".obj.gz]" + whirld.data;
- }
- else {
- trnV += "\npT " + dP.prototypeTexture.name + ".png";
- if(dP.prototypeTexture.format == TextureFormat.ARGB32) File.WriteAllBytes(whirld.path + dP.prototypeTexture.name + ".png", dP.prototypeTexture.EncodeToPNG());
- }
- trnV += "\nminW " + dP.minWidth;
- trnV += "\nmaxW " + dP.maxWidth;
- trnV += "\nminH " + dP.minHeight;
- trnV += "\nmaxH " + dP.maxHeight;
- trnV += "\nnS" + dP.noiseSpread;
- trnV += "\nbF " + dP.bendFactor;
- trnV += "\nhC " + dP.healthyColor.r + " " + dP.healthyColor.g + " " + dP.healthyColor.b;
- trnV += "\ndC " + dP.dryColor.r + " " + dP.dryColor.g + " " + dP.dryColor.b;
- trnV += "\nlF " + dP.lightmapFactor;
- trnV += "\ngL " + (dP.grayscaleLighting ? 1 : 0);
- trnV += "\nrM " + dP.renderMode;
- trnV += "\nuM " + (dP.usePrototypeMesh ? 1 : 0);
- }
- var detLayer0 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 0);
- if(trnDat.detailPrototypes.length > 1) var detLayer1 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 1);
- if(trnDat.detailPrototypes.length > 2) var detLayer2 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 2);
- if(trnDat.detailPrototypes.length > 3) var detLayer3 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 3);
- if(trnDat.detailPrototypes.length > 4) var detLayer4 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 4);
- if(trnDat.detailPrototypes.length > 5) var detLayer5 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 5);
- if(trnDat.detailPrototypes.length > 6) var detLayer6 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 6);
- if(trnDat.detailPrototypes.length > 7) var detLayer7 = trnDat.GetDetailLayer(0, 0, trnDat.detailResolution, trnDat.detailResolution, 7);
- //Save DetailMap
- var pixels : Array = new Array();
- for(var iY : int = 0; iY < trnDat.detailResolution; iY++) {
- for(var iX : int = 0; iX < trnDat.detailResolution; iX++) {
- var r : float = (trnDat.detailPrototypes.length > 0 ? detLayer0[iX, iY] : 0);
- var g : float = (trnDat.detailPrototypes.length > 1 ? detLayer1[iX, iY] : 0);
- var b : float = (trnDat.detailPrototypes.length > 2 ? detLayer2[iX, iY] : 0);
- var a : float = (trnDat.detailPrototypes.length > 3 ? detLayer3[iX, iY] : 0);
- pixels.Add(new Color(r / 16, g / 16, b / 16, a / 16));
- }
- }
- var tex : Texture2D = new Texture2D (trnDat.detailResolution, trnDat.detailResolution, TextureFormat.ARGB32, false);
- tex.SetPixels(pixels.ToBuiltin(Color),0);
- tex.Apply(false);
- File.WriteAllBytes(whirld.path + tr.gameObject.name + "d.png", tex.EncodeToPNG());
- trnV += "\n\ndetailmap " + tr.gameObject.name + "d.png";
- //Save 2nd DetailMap
- if(trnDat.detailPrototypes.length > 4) {
- pixels = new Array();
- for(iY = 0; iY < trnDat.detailResolution; iY++) {
- for(iX = 0; iX < trnDat.detailResolution; iX++) {
- r = (trnDat.detailPrototypes.length > 4 ? detLayer4[iX, iY] : 0);
- g = (trnDat.detailPrototypes.length > 5 ? detLayer5[iX, iY] : 0);
- b = (trnDat.detailPrototypes.length > 6 ? detLayer6[iX, iY] : 0);
- a = (trnDat.detailPrototypes.length > 7 ? detLayer7[iX, iY] : 0);
- pixels.Add(new Color(r / 16, g / 16, b / 16, a / 16));
- }
- }
- tex = new Texture2D (trnDat.detailResolution, trnDat.detailResolution, TextureFormat.ARGB32, false);
- tex.SetPixels(pixels.ToBuiltin(Color),0);
- tex.Apply(false);
- File.WriteAllBytes(whirld.path + tr.gameObject.name + "d2.png", tex.EncodeToPNG());
- trnV += "\n\ndetailmap2 " + tr.gameObject.name + "d2.png";
- }
- //Save Detail File
- File.WriteAllBytes(whirld.path + tr.gameObject.name + ".utd.gz", new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, 9).CompressString(trnV));
- trnRes += ";d:" + tr.gameObject.name + ".utd.gz";
- }
- //Add terrain resource to world assets list
- whirld.data = "[trn:" + tr.gameObject.name + ";r:" + trnDat.size.x + "," + trnDat.size.y + "," + trnDat.size.z + "," + trnDat.heightmapWidth + trnRes + "]" + whirld.data;
- }
- //Look for children objects to save
- Save(tr);
- }
- objects.Add(tr.gameObject.name, goP);
- }
- whirld.data += "}";
- }
- if(trobj == null) {
- whirld.info = "World Saved";
- whirld.status = WorldLoadCode.Success;
- }
- }
- }
- function MeshRead(o : GameObject, dat : Array) {
- var m : Mesh = new Mesh();
- var vertices : Array = new Array();
- var normals : Array = new Array();
- var uv : Array = new Array();
- for(var str : String in dat) {
- var s = str.Split(" "[0]);
- if(s[0] == "v") vertices.Add(Vector3(parseFloat(s[1]), parseFloat(s[2]), parseFloat(s[3])));
- else if(s[0] == "n") normals.Add(Vector3(parseFloat(s[1]), parseFloat(s[2]), parseFloat(s[3])));
- else if(s[0] == "u") uv.Add(Vector2(parseFloat(s[1]), parseFloat(s[2])));
- else if(s[0] == "t") {
- var i = 1;
- var triangles : int[] = new int[s.length - 1];
- while(i < s.length) {
- triangles[i - 1] = parseInt(s[i]);
- i++;
- }
- }
- }
- m.vertices = vertices;
- m.normals = normals;
- m.uv = uv;
- m.triangles = triangles;
- //m.RecalculateBounds();
- //m.RecalculateNormals();
- //m.Optimize();
- o.AddComponent(MeshFilter);
- o.GetComponent(MeshFilter).mesh = m;
- o.AddComponent(MeshRenderer);
- o.AddComponent(MeshCollider);
- o.GetComponent(MeshCollider).mesh = m;
- }
- function MeshWrite(mf : MeshFilter) {
- var m : Mesh = mf.mesh;
- var mats : Material[] = mf.renderer.sharedMaterials;
- var s : String = "";
- for(var v : Vector3 in m.vertices) s += "v " + v.x + " " + v.y + " " + v.z + ",";
- for(var v : Vector3 in m.normals) s += "n " + v.x + " " + v.y + " " + v.z + ",";
- for(var v : Vector3 in m.uv) s += "u " + v.x + " " + v.y + " " + v.z + ",";
- s += "t";
- for(var t : int in m.triangles) s += " " + t;
- /*
- for(int material=0; material < m.subMeshCount; material ++) {
- s += "m " + mats[material].name + ",";
- int[] triangles = m.GetTriangles(material);
- for (int i=0;i<triangles.Length;i+=3) {
- sb.Append(string.Format("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}\n",
- triangles[i]+1, triangles[i+1]+1, triangles[i+2]+1));
- }
- }*/
- return s;
- }
- function MeshWriteObj(mF : MeshFilter, name : String) {
- var m : Mesh = mF.sharedMesh;
- var mats : Material[] = mF.renderer.sharedMaterials;
- var mD : String = "#Unity3D Whirld Object\n\nmtllib Whirld.mtl\n\ng " + mF.name + "\n";
- for(var v : Vector3 in m.vertices) mD += "v " + (-v.x).ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.z.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "\n";
- mD += "\n";
- for(var v : Vector3 in m.normals) mD += "vn " + (-v.x).ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.z.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "\n";
- mD += "\n";
- for(var v : Vector3 in m.uv) mD += "vt " + v.x.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + " " + v.y.ToString("F3", System.Globalization.CultureInfo.InvariantCulture) + "\n";
- for (var material : int = 0; material < m.subMeshCount; material ++) {
- if(!materials.ContainsKey(mats[material].name)) materials.Add(mats[material].name, mats[material]);
- mD += "\nusemtl " + mats[material].name + "\n";
- var triangles : int[] = m.GetTriangles(material);
- for (i=0; i<triangles.Length; i+=3) mD += "f " + (triangles[i+1]+1) + "/" + (triangles[i+1]+1) + "/" + (triangles[i+1]+1) + " " + (triangles[i]+1) + "/" + (triangles[i]+1) + "/" + (triangles[i]+1) + " " + (triangles[i+2]+1) + "/" + (triangles[i+2]+1) + "/" + (triangles[i+2]+1) + "\n";
- }
- var ms : MemoryStream = new MemoryStream();
- File.WriteAllBytes(whirld.path + name + ".obj.gz", new Ionic.Zlib.GZipStream(ms, Ionic.Zlib.CompressionMode.Compress, 9).CompressString(mD));
- }
- function ReadWWW(www : WWW) {
- /*if(Application.isPlaying) {
- whirldCoroutine = whirld.world.GetComponent(WhirldCoroutine);
- if(!whirldCoroutine) { //Create a MonoBehaviour which we can use to yield stuff
- whirld.world.AddComponent(WhirldCoroutine);
- whirldCoroutine = whirld.world.GetComponent(WhirldCoroutine);
- }
- //whirldCoroutine.StartCoroutine(whirldCoroutine.WWWLoad(www, whirld));
- whirldCoroutine.WWWLoad(www, whirld);
- }
- else {
- while(!www.isDone) whirld.progress = www.progress;
- //while(!www.isDone) EditorUtility.DisplayProgressBar("Loading UTW World", whirld.statusTxt, www.progress);
- //EditorUtility.ClearProgressBar();
- }*/
- while(!www.isDone) {
- whirld.progress = www.progress;
- yield new WaitForSeconds(.1);
- }
- }
Whirld 2
by Aubrey Falconer
