From ce60a410cf7fbecee248124ec8ed3e06ba39a23f Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 13 Jan 2015 15:34:26 -0800 Subject: [PATCH 01/30] Reenable entity list tools --- examples/editEntities.js | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/editEntities.js b/examples/editEntities.js index 172089ed62..24b658dfcd 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -232,6 +232,7 @@ var toolBar = (function () { cameraManager.disable(); } else { hasShownPropertiesTool = false; + entityListTool.setVisible(true); cameraManager.enable(); gridTool.setVisible(true); grid.setEnabled(true); From 9e8458edd92162f7074e3dc77af22714a90791b2 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 13 Jan 2015 15:35:19 -0800 Subject: [PATCH 02/30] Add support for teleport, delete, and filtering in entity list --- examples/html/entityList.html | 140 +++++++++++++++++++++++++------ examples/html/style.css | 26 +++++- examples/libraries/entityList.js | 49 +++++++---- 3 files changed, 171 insertions(+), 44 deletions(-) diff --git a/examples/html/entityList.html b/examples/html/entityList.html index 7caa45f19d..26a302cb41 100644 --- a/examples/html/entityList.html +++ b/examples/html/entityList.html @@ -2,13 +2,30 @@ +
- + + +
- - - - - - - - - -
TypeURL
+
+ + + + + + + + + + +
Type  ▾URL
+
diff --git a/examples/html/style.css b/examples/html/style.css index 7ffbacb15e..12e87baee5 100644 --- a/examples/html/style.css +++ b/examples/html/style.css @@ -114,6 +114,7 @@ table#entity-table { #entity-table tr { cursor: pointer; + border-bottom: 1px solid #e5e5e5; } #entity-table tr.selected { @@ -133,14 +134,18 @@ table#entity-table { border: 0px black solid; word-wrap: nowrap; white-space: nowrap; + text-overflow: ellipsis; +} + +#entity-table td.url { + white-space: nowrap; + overflow: hidden; } th#entity-type { width: 60px; } -th#entity-url { -} div.input-area { @@ -186,3 +191,20 @@ table#properties-table { col#col-label { width: 130px; } + +div.outer { + position: relative; +} +div.inner { + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + position: absolute; + width: 100%; +} + +td { + + + vertical-align: top; +} diff --git a/examples/libraries/entityList.js b/examples/libraries/entityList.js index eb01295d97..10a2209309 100644 --- a/examples/libraries/entityList.js +++ b/examples/libraries/entityList.js @@ -24,10 +24,38 @@ EntityListTool = function(opts) { type: 'selectionUpdate', selectedIDs: selectedIDs, }; + print("Sending: " + JSON.stringify(data)); webView.eventBridge.emitScriptEvent(JSON.stringify(data)); }); + function sendUpdate() { + var entities = []; + var ids = Entities.findEntities(MyAvatar.position, 100); + for (var i = 0; i < ids.length; i++) { + var id = ids[i]; + var properties = Entities.getEntityProperties(id); + entities.push({ + id: id.id, + type: properties.type, + url: properties.type == "Model" ? properties.modelURL : "", + }); + } + + var selectedIDs = []; + for (var i = 0; i < selectionManager.selections.length; i++) { + selectedIDs.push(selectionManager.selections[i].id); + } + + var data = { + type: "update", + entities: entities, + selectedIDs: selectedIDs, + }; + webView.eventBridge.emitScriptEvent(JSON.stringify(data)); + } + webView.eventBridge.webEventReceived.connect(function(data) { + print("Got: " + data); data = JSON.parse(data); if (data.type == "selectionUpdate") { var ids = data.entityIds; @@ -46,22 +74,13 @@ EntityListTool = function(opts) { Menu.isOptionChecked(MENU_EASE_ON_FOCUS)); } } else if (data.type == "refresh") { - var entities = []; - var ids = Entities.findEntities(MyAvatar.position, 100); - for (var i = 0; i < ids.length; i++) { - var id = ids[i]; - var properties = Entities.getEntityProperties(id); - entities.push({ - id: id.id, - type: properties.type, - url: properties.type == "Model" ? properties.modelURL : "", - }); + sendUpdate(); + } else if (data.type == "teleport") { + if (selectionManager.hasSelection()) { + MyAvatar.position = selectionManager.worldPosition; } - var data = { - type: "update", - entities: entities, - }; - webView.eventBridge.emitScriptEvent(JSON.stringify(data)); + } else if (data.type == "delete") { + deleteSelectedEntities(); } }); From 7ddec78cd52a1ec98a3757efd33a936250ce55d3 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 13 Jan 2015 15:36:25 -0800 Subject: [PATCH 03/30] Add list.min.js for entity list tool --- examples/html/list.min.js | 1 + 1 file changed, 1 insertion(+) create mode 100644 examples/html/list.min.js diff --git a/examples/html/list.min.js b/examples/html/list.min.js new file mode 100644 index 0000000000..56c17e398d --- /dev/null +++ b/examples/html/list.min.js @@ -0,0 +1 @@ +!function(){function a(b,c,d){var e=a.resolve(b);if(null==e){d=d||b,c=c||"root";var f=new Error('Failed to require "'+d+'" from "'+c+'"');throw f.path=d,f.parent=c,f.require=!0,f}var g=a.modules[e];if(!g._resolving&&!g.exports){var h={};h.exports={},h.client=h.component=!0,g._resolving=!0,g.call(this,h.exports,a.relative(e),h),delete g._resolving,g.exports=h.exports}return g.exports}a.modules={},a.aliases={},a.resolve=function(b){"/"===b.charAt(0)&&(b=b.slice(1));for(var c=[b,b+".js",b+".json",b+"/index.js",b+"/index.json"],d=0;di;i++)if(h.test(f[i].className)){if(c)return f[i];d[j]=f[i],j++}return d}}()}),a.register("javve-get-attribute/index.js",function(a,b,c){c.exports=function(a,b){var c=a.getAttribute&&a.getAttribute(b)||null;if(!c)for(var d=a.attributes,e=d.length,f=0;e>f;f++)void 0!==b[f]&&b[f].nodeName===b&&(c=b[f].nodeValue);return c}}),a.register("javve-natural-sort/index.js",function(a,b,c){c.exports=function(a,b,c){var d,e,f=/(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,g=/(^[ ]*|[ ]*$)/g,h=/(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,i=/^0x[0-9a-f]+$/i,j=/^0/,c=c||{},k=function(a){return c.insensitive&&(""+a).toLowerCase()||""+a},l=k(a).replace(g,"")||"",m=k(b).replace(g,"")||"",n=l.replace(f,"\x00$1\x00").replace(/\0$/,"").replace(/^\0/,"").split("\x00"),o=m.replace(f,"\x00$1\x00").replace(/\0$/,"").replace(/^\0/,"").split("\x00"),p=parseInt(l.match(i))||1!=n.length&&l.match(h)&&Date.parse(l),q=parseInt(m.match(i))||p&&m.match(h)&&Date.parse(m)||null,r=c.desc?-1:1;if(q){if(q>p)return-1*r;if(p>q)return 1*r}for(var s=0,t=Math.max(n.length,o.length);t>s;s++){if(d=!(n[s]||"").match(j)&&parseFloat(n[s])||n[s]||0,e=!(o[s]||"").match(j)&&parseFloat(o[s])||o[s]||0,isNaN(d)!==isNaN(e))return isNaN(d)?1:-1;if(typeof d!=typeof e&&(d+="",e+=""),e>d)return-1*r;if(d>e)return 1*r}return 0}}),a.register("javve-to-string/index.js",function(a,b,c){c.exports=function(a){return a=void 0===a?"":a,a=null===a?"":a,a=a.toString()}}),a.register("component-type/index.js",function(a,b,c){var d=Object.prototype.toString;c.exports=function(a){switch(d.call(a)){case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object Error]":return"error"}return null===a?"null":void 0===a?"undefined":a!==a?"nan":a&&1===a.nodeType?"element":typeof a.valueOf()}}),a.register("list.js/index.js",function(a,b,c){!function(a,d){"use strict";var e=a.document,f=b("get-by-class"),g=b("extend"),h=b("indexof"),i=function(a,c,i){var j,k=this,l=b("./src/item")(k),m=b("./src/add-async")(k),n=b("./src/parse")(k);j={start:function(){k.listClass="list",k.searchClass="search",k.sortClass="sort",k.page=200,k.i=1,k.items=[],k.visibleItems=[],k.matchingItems=[],k.searched=!1,k.filtered=!1,k.handlers={updated:[]},k.plugins={},k.helpers={getByClass:f,extend:g,indexOf:h},g(k,c),k.listContainer="string"==typeof a?e.getElementById(a):a,k.listContainer&&(k.list=f(k.listContainer,k.listClass,!0),k.templater=b("./src/templater")(k),k.search=b("./src/search")(k),k.filter=b("./src/filter")(k),k.sort=b("./src/sort")(k),this.items(),k.update(),this.plugins())},items:function(){n(k.list),i!==d&&k.add(i)},plugins:function(){for(var a=0;af;f++){var h=null;a[f]instanceof l?(h=a[f],h.reload()):(e=k.items.length>k.page?!0:!1,h=new l(a[f],d,e)),k.items.push(h),c.push(h)}return k.update(),c},this.show=function(a,b){return this.i=a,this.page=b,k.update(),k},this.remove=function(a,b,c){for(var d=0,e=0,f=k.items.length;f>e;e++)k.items[e].values()[a]==b&&(k.templater.remove(k.items[e],c),k.items.splice(e,1),f--,e--,d++);return k.update(),d},this.get=function(a,b){for(var c=[],d=0,e=k.items.length;e>d;d++){var f=k.items[d];f.values()[a]==b&&c.push(f)}return c},this.size=function(){return k.items.length},this.clear=function(){return k.templater.clear(),k.items=[],k},this.on=function(a,b){return k.handlers[a].push(b),k},this.off=function(a,b){var c=k.handlers[a],d=h(c,b);return d>-1&&c.splice(d,1),k},this.trigger=function(a){for(var b=k.handlers[a].length;b--;)k.handlers[a][b](k);return k},this.reset={filter:function(){for(var a=k.items,b=a.length;b--;)a[b].filtered=!1;return k},search:function(){for(var a=k.items,b=a.length;b--;)a[b].found=!1;return k}},this.update=function(){var a=k.items,b=a.length;k.visibleItems=[],k.matchingItems=[],k.templater.clear();for(var c=0;b>c;c++)a[c].matching()&&k.matchingItems.length+1>=k.i&&k.visibleItems.lengthb;b++)j.item(a.items[b])},item:function(a){a.found=!1;for(var b=0,d=c.length;d>b;b++)if(j.values(a.values(),c[b]))return a.found=!0,void 0},values:function(a,c){return a.hasOwnProperty(c)&&(b=f(a[c]).toLowerCase(),""!==g&&b.search(g)>-1)?!0:!1},reset:function(){a.reset.search(),a.searched=!1}},k=function(b){return a.trigger("searchStart"),i.resetList(),i.setSearchString(b),i.setOptions(arguments),i.setColumns(),""===g?j.reset():(a.searched=!0,h?h(g,c):j.list()),a.update(),a.trigger("searchComplete"),a.visibleItems};return a.handlers.searchStart=a.handlers.searchStart||[],a.handlers.searchComplete=a.handlers.searchComplete||[],d.bind(e(a.listContainer,a.searchClass),"keyup",function(b){var c=b.target||b.srcElement,d=""===c.value&&!a.searched;d||k(c.value)}),d.bind(e(a.listContainer,a.searchClass),"input",function(a){var b=a.target||a.srcElement;""===b.value&&k("")}),a.helpers.toString=f,k}}),a.register("list.js/src/sort.js",function(a,b,c){var d=b("natural-sort"),e=b("classes"),f=b("events"),g=b("get-by-class"),h=b("get-attribute");c.exports=function(a){a.sortFunction=a.sortFunction||function(a,b,c){return c.desc="desc"==c.order?!0:!1,d(a.values()[c.valueName],b.values()[c.valueName],c)};var b={els:void 0,clear:function(){for(var a=0,c=b.els.length;c>a;a++)e(b.els[a]).remove("asc"),e(b.els[a]).remove("desc")},getOrder:function(a){var b=h(a,"data-order");return"asc"==b||"desc"==b?b:e(a).has("desc")?"asc":e(a).has("asc")?"desc":"asc"},getInSensitive:function(a,b){var c=h(a,"data-insensitive");b.insensitive="true"===c?!0:!1},setOrder:function(a){for(var c=0,d=b.els.length;d>c;c++){var f=b.els[c];if(h(f,"data-sort")===a.valueName){var g=h(f,"data-order");"asc"==g||"desc"==g?g==a.order&&e(f).add(a.order):e(f).add(a.order)}}}},c=function(){a.trigger("sortStart"),options={};var c=arguments[0].currentTarget||arguments[0].srcElement||void 0;c?(options.valueName=h(c,"data-sort"),b.getInSensitive(c,options),options.order=b.getOrder(c)):(options=arguments[1]||options,options.valueName=arguments[0],options.order=options.order||"asc",options.insensitive="undefined"==typeof options.insensitive?!0:options.insensitive),b.clear(),b.setOrder(options),options.sortFunction=options.sortFunction||a.sortFunction,a.items.sort(function(a,b){return options.sortFunction(a,b,options)}),a.update(),a.trigger("sortComplete")};return a.handlers.sortStart=a.handlers.sortStart||[],a.handlers.sortComplete=a.handlers.sortComplete||[],b.els=g(a.listContainer,a.sortClass),f.bind(b.els,"click",c),a.on("searchStart",b.clear),a.on("filterStart",b.clear),a.helpers.classes=e,a.helpers.naturalSort=d,a.helpers.events=f,a.helpers.getAttribute=h,c}}),a.register("list.js/src/item.js",function(a,b,c){c.exports=function(a){return function(b,c,d){var e=this;this._values={},this.found=!1,this.filtered=!1;var f=function(b,c,d){if(void 0===c)d?e.values(b,d):e.values(b);else{e.elm=c;var f=a.templater.get(e,b);e.values(f)}};this.values=function(b,c){if(void 0===b)return e._values;for(var d in b)e._values[d]=b[d];c!==!0&&a.templater.set(e,e.values())},this.show=function(){a.templater.show(e)},this.hide=function(){a.templater.hide(e)},this.matching=function(){return a.filtered&&a.searched&&e.found&&e.filtered||a.filtered&&!a.searched&&e.filtered||!a.filtered&&a.searched&&e.found||!a.filtered&&!a.searched},this.visible=function(){return e.elm.parentNode==a.list?!0:!1},f(b,c,d)}}}),a.register("list.js/src/templater.js",function(a,b,c){var d=b("get-by-class"),e=function(a){function b(b){if(void 0===b){for(var c=a.list.childNodes,d=0,e=c.length;e>d;d++)if(void 0===c[d].data)return c[d];return null}if(-1!==b.indexOf("<")){var f=document.createElement("div");return f.innerHTML=b,f.firstChild}return document.getElementById(a.item)}var c=b(a.item),e=this;this.get=function(a,b){e.create(a);for(var c={},f=0,g=b.length;g>f;f++){var h=d(a.elm,b[f],!0);c[b[f]]=h?h.innerHTML:""}return c},this.set=function(a,b){if(!e.create(a))for(var c in b)if(b.hasOwnProperty(c)){var f=d(a.elm,c,!0);f&&("IMG"===f.tagName&&""!==b[c]?f.src=b[c]:f.innerHTML=b[c])}},this.create=function(a){if(void 0!==a.elm)return!1;var b=c.cloneNode(!0);return b.removeAttribute("id"),a.elm=b,e.set(a,a.values()),!0},this.remove=function(b){a.list.removeChild(b.elm)},this.show=function(b){e.create(b),a.list.appendChild(b.elm)},this.hide=function(b){void 0!==b.elm&&b.elm.parentNode===a.list&&a.list.removeChild(b.elm)},this.clear=function(){if(a.list.hasChildNodes())for(;a.list.childNodes.length>=1;)a.list.removeChild(a.list.firstChild)}};c.exports=function(a){return new e(a)}}),a.register("list.js/src/filter.js",function(a,b,c){c.exports=function(a){return a.handlers.filterStart=a.handlers.filterStart||[],a.handlers.filterComplete=a.handlers.filterComplete||[],function(b){if(a.trigger("filterStart"),a.i=1,a.reset.filter(),void 0===b)a.filtered=!1;else{a.filtered=!0;for(var c=a.items,d=0,e=c.length;e>d;d++){var f=c[d];f.filtered=b(f)?!0:!1}}return a.update(),a.trigger("filterComplete"),a.visibleItems}}}),a.register("list.js/src/add-async.js",function(a,b,c){c.exports=function(a){return function(b,c,d){var e=b.splice(0,100);d=d||[],d=d.concat(a.add(e)),b.length>0?setTimeout(function(){addAsync(b,c,d)},10):(a.update(),c(d))}}}),a.register("list.js/src/parse.js",function(a,b,c){c.exports=function(a){var c=b("./item")(a),d=function(a){for(var b=a.childNodes,c=[],d=0,e=b.length;e>d;d++)void 0===b[d].data&&c.push(b[d]);return c},e=function(b,d){for(var e=0,f=b.length;f>e;e++)a.items.push(new c(d,b[e]))},f=function(b,c){var d=b.splice(0,100);e(d,c),b.length>0?setTimeout(function(){init.items.indexAsync(b,c)},10):a.update()};return function(){var b=d(a.list),c=a.valueNames;a.indexAsync?f(b,c):e(b,c)}}}),a.alias("component-classes/index.js","list.js/deps/classes/index.js"),a.alias("component-classes/index.js","classes/index.js"),a.alias("component-indexof/index.js","component-classes/deps/indexof/index.js"),a.alias("segmentio-extend/index.js","list.js/deps/extend/index.js"),a.alias("segmentio-extend/index.js","extend/index.js"),a.alias("component-indexof/index.js","list.js/deps/indexof/index.js"),a.alias("component-indexof/index.js","indexof/index.js"),a.alias("javve-events/index.js","list.js/deps/events/index.js"),a.alias("javve-events/index.js","events/index.js"),a.alias("component-event/index.js","javve-events/deps/event/index.js"),a.alias("timoxley-to-array/index.js","javve-events/deps/to-array/index.js"),a.alias("javve-get-by-class/index.js","list.js/deps/get-by-class/index.js"),a.alias("javve-get-by-class/index.js","get-by-class/index.js"),a.alias("javve-get-attribute/index.js","list.js/deps/get-attribute/index.js"),a.alias("javve-get-attribute/index.js","get-attribute/index.js"),a.alias("javve-natural-sort/index.js","list.js/deps/natural-sort/index.js"),a.alias("javve-natural-sort/index.js","natural-sort/index.js"),a.alias("javve-to-string/index.js","list.js/deps/to-string/index.js"),a.alias("javve-to-string/index.js","list.js/deps/to-string/index.js"),a.alias("javve-to-string/index.js","to-string/index.js"),a.alias("javve-to-string/index.js","javve-to-string/index.js"),a.alias("component-type/index.js","list.js/deps/type/index.js"),a.alias("component-type/index.js","type/index.js"),"object"==typeof exports?module.exports=a("list.js"):"function"==typeof define&&define.amd?define(function(){return a("list.js")}):this.List=a("list.js")}(); \ No newline at end of file From c51cac6381e836371c8559f977dd56387b1c115e Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 13 Jan 2015 15:38:28 -0800 Subject: [PATCH 04/30] Remove Model List dialog --- examples/editEntities.js | 36 +----------------------------------- 1 file changed, 1 insertion(+), 35 deletions(-) diff --git a/examples/editEntities.js b/examples/editEntities.js index 24b658dfcd..38d3d3af75 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -672,8 +672,7 @@ function setupModelMenus() { print("delete exists... don't add ours"); } - Menu.addMenuItem({ menuName: "Edit", menuItemName: "Model List...", afterItem: "Models" }); - Menu.addMenuItem({ menuName: "Edit", menuItemName: "Paste Models", shortcutKey: "CTRL+META+V", afterItem: "Model List..." }); + Menu.addMenuItem({ menuName: "Edit", menuItemName: "Paste Models", shortcutKey: "CTRL+META+V", afterItem: "Models" }); Menu.addMenuItem({ menuName: "Edit", menuItemName: "Allow Selecting of Large Models", shortcutKey: "CTRL+META+L", afterItem: "Paste Models", isCheckable: true, isChecked: true }); Menu.addMenuItem({ menuName: "Edit", menuItemName: "Allow Selecting of Small Models", shortcutKey: "CTRL+META+S", @@ -700,7 +699,6 @@ function cleanupModelMenus() { Menu.removeMenuItem("Edit", "Delete"); } - Menu.removeMenuItem("Edit", "Model List..."); Menu.removeMenuItem("Edit", "Paste Models"); Menu.removeMenuItem("Edit", "Allow Selecting of Large Models"); Menu.removeMenuItem("Edit", "Allow Selecting of Small Models"); @@ -764,38 +762,6 @@ function handeMenuEvent(menuItem) { } else { print(" Delete Entity.... not holding..."); } - } else if (menuItem == "Model List...") { - var models = new Array(); - models = Entities.findEntities(MyAvatar.position, Number.MAX_VALUE); - for (var i = 0; i < models.length; i++) { - models[i].properties = Entities.getEntityProperties(models[i]); - models[i].toString = function() { - var modelname; - if (this.properties.type == "Model") { - modelname = decodeURIComponent( - this.properties.modelURL.indexOf("/") != -1 ? - this.properties.modelURL.substring(this.properties.modelURL.lastIndexOf("/") + 1) : - this.properties.modelURL); - } else { - modelname = this.properties.id; - } - return "[" + this.properties.type + "] " + modelname; - }; - } - var form = [{label: "Model: ", options: models}]; - form.push({label: "Action: ", options: ["Properties", "Delete", "Teleport"]}); - form.push({ button: "Cancel" }); - if (Window.form("Model List", form)) { - var selectedModel = form[0].value; - if (form[1].value == "Properties") { - editModelID = selectedModel; - entityPropertyDialogBox.openDialog(editModelID); - } else if (form[1].value == "Delete") { - Entities.deleteEntity(selectedModel); - } else if (form[1].value == "Teleport") { - MyAvatar.position = selectedModel.properties.position; - } - } } else if (menuItem == "Paste Models") { modelImporter.paste(); } else if (menuItem == "Export Models") { From 705e6181a11202189376f3b93fa34f724259c4a6 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Thu, 15 Jan 2015 11:12:42 -0800 Subject: [PATCH 05/30] Move entity delete action to function --- examples/editEntities.js | 44 ++++++++++++++++++++++------------------ 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/examples/editEntities.js b/examples/editEntities.js index 38d3d3af75..369ab73d17 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -735,6 +735,28 @@ Script.update.connect(function (deltaTime) { selectionDisplay.checkMove(); }); +function deleteSelectedEntities() { + if (SelectionManager.hasSelection()) { + print(" Delete Entities"); + SelectionManager.saveProperties(); + var savedProperties = []; + for (var i = 0; i < selectionManager.selections.length; i++) { + var entityID = SelectionManager.selections[i]; + var initialProperties = SelectionManager.savedProperties[entityID.id]; + SelectionManager.savedProperties[entityID.id]; + savedProperties.push({ + entityID: entityID, + properties: initialProperties + }); + Entities.deleteEntity(entityID); + } + SelectionManager.clearSelections(); + pushCommandForSelections([], savedProperties); + } else { + print(" Delete Entity.... not holding..."); + } +} + function handeMenuEvent(menuItem) { if (menuItem == "Allow Selecting of Small Models") { allowSmallModels = Menu.isOptionChecked("Allow Selecting of Small Models"); @@ -743,25 +765,7 @@ function handeMenuEvent(menuItem) { } else if (menuItem == "Allow Selecting of Lights") { Entities.setLightsArePickable(Menu.isOptionChecked("Allow Selecting of Lights")); } else if (menuItem == "Delete") { - if (SelectionManager.hasSelection()) { - print(" Delete Entities"); - SelectionManager.saveProperties(); - var savedProperties = []; - for (var i = 0; i < selectionManager.selections.length; i++) { - var entityID = SelectionManager.selections[i]; - var initialProperties = SelectionManager.savedProperties[entityID.id]; - SelectionManager.savedProperties[entityID.id]; - savedProperties.push({ - entityID: entityID, - properties: initialProperties - }); - Entities.deleteEntity(entityID); - } - SelectionManager.clearSelections(); - pushCommandForSelections([], savedProperties); - } else { - print(" Delete Entity.... not holding..."); - } + deleteSelectedEntities(); } else if (menuItem == "Paste Models") { modelImporter.paste(); } else if (menuItem == "Export Models") { @@ -790,7 +794,7 @@ Controller.keyPressEvent.connect(function(event) { Controller.keyReleaseEvent.connect(function (event) { // since sometimes our menu shortcut keys don't work, trap our menu items here also and fire the appropriate menu items if (event.text == "BACKSPACE" || event.text == "DELETE") { - handeMenuEvent("Delete"); + deleteSelectedEntities(); } else if (event.text == "TAB") { selectionDisplay.toggleSpaceMode(); } else if (event.text == "f") { From d3a6a411fb74d6acdedf1e515f838564a77b1068 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 16 Jan 2015 16:23:29 -0800 Subject: [PATCH 06/30] Update entity list to use list.js more directly --- examples/html/entityList.html | 61 ++++++++++++++++------------------- examples/html/style.css | 16 ++++----- 2 files changed, 33 insertions(+), 44 deletions(-) diff --git a/examples/html/entityList.html b/examples/html/entityList.html index 26a302cb41..6c9846f5e4 100644 --- a/examples/html/entityList.html +++ b/examples/html/entityList.html @@ -1,4 +1,3 @@ - @@ -14,6 +13,8 @@ var DESC_STRING = ' ▴'; function loaded() { + entityList = new List('entity-list', { valueNames: ['type', 'url']}); + entityList.clear(); elEntityTable = document.getElementById("entity-table"); elEntityTableBody = document.getElementById("entity-table-body"); elRefresh = document.getElementById("refresh"); @@ -37,7 +38,8 @@ selectedEntities = selection; - entities[id].el.className = 'selected'; + this.className = 'selected'; + EventBridge.emitWebEvent(JSON.stringify({ type: "selectionUpdate", focus: false, @@ -46,8 +48,6 @@ } function onRowDoubleClicked() { - var id = this.dataset.entityId; - EventBridge.emitWebEvent(JSON.stringify({ type: "selectionUpdate", focus: true, @@ -60,21 +60,21 @@ var urlParts = url.split('/'); var filename = urlParts[urlParts.length - 1]; - var el = document.createElement('tr'); - el.setAttribute('id', 'entity_' + id); - el.innerHTML += "" + type + ""; - el.innerHTML += "
" + filename + "
"; - el.dataset.entityId = id; - el.onclick = onRowClicked; - el.ondblclick = onRowDoubleClicked; - elEntityTableBody.appendChild(el); - - // Add element to local dict - entities[id] = { - id: id, - name: id, - el: el, - }; + entityList.add([{ id: id, type: type, url: filename }], function(items) { + var el = items[0].elm; + var id = items[0]._values.id; + entities[id] = { + id: id, + name: id, + el: el, + }; + el.setAttribute('id', 'entity_' + id); + el.setAttribute('title', url); + el.dataset.entityId = id; + el.onclick = onRowClicked; + el.ondblclick = onRowDoubleClicked; + el.innerHTML + }); if (refreshEntityListTimer) { clearTimeout(refreshEntityListTimer); @@ -91,10 +91,8 @@ } function clearEntities() { - for (id in entities) { - elEntityTableBody.removeChild(entities[id].el); - } entities = {}; + entityList.clear(); } var elSortOrder = { @@ -122,7 +120,6 @@ function refreshEntityListObject() { refreshEntityListTimer = null; - entityList = new List('entity-list', { valueNames: ['type', 'url']}); entityList.sort(currentSortColumn, { order: currentSortOrder }); entityList.search(document.getElementById("filter").value); } @@ -174,15 +171,6 @@ } }); } - - // var _id = 0; - // setInterval(function() { - // for(var i = 0; i < 2; i++) { - // addEntity(_id, ['Model', 'Light'][i], 'http' + _id); - // _id++; - // } - // }, 5000); - setTimeout(refreshEntities, 1); } @@ -198,11 +186,16 @@ - - + + + + + + +
Type  ▾URL Type  ▾URL
Type
URL
diff --git a/examples/html/style.css b/examples/html/style.css index 42cf37d34a..ad78d0234c 100644 --- a/examples/html/style.css +++ b/examples/html/style.css @@ -5,9 +5,10 @@ body { margin: 0; padding: 0; - background-color: #efefef; + background-color: rgb(76, 76, 76); + color: rgb(204, 204, 204); font-family: Arial; - font-size: 11.5px; + font-size: 11px; -webkit-touch-callout: none; -webkit-user-select: none; @@ -17,12 +18,6 @@ body { user-select: none; } -body.properties { - background-color: rgb(76, 76, 76); - color: rgb(204, 204, 204); - font-size: 11px; -} - .selectable { -webkit-touch-callout: text; -webkit-user-select: text; @@ -117,13 +112,13 @@ input.coord { table#entity-table { border-collapse: collapse; font-family: Sans-Serif; - /* font-size: 12px; */ + font-size: 10px; width: 100%; } #entity-table tr { cursor: pointer; - border-bottom: 1px solid #e5e5e5; + border-bottom: 1px solid rgb(63, 63, 63) } #entity-table tr.selected { @@ -140,6 +135,7 @@ table#entity-table { } #entity-table td { + font-size: 11px; border: 0px black solid; word-wrap: nowrap; white-space: nowrap; From ba752040ddfad0437b33c989504e43cb330cc603 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 16 Jan 2015 16:24:19 -0800 Subject: [PATCH 07/30] Update WebWindow to redefine EventBridge after refresh --- interface/src/scripting/WebWindowClass.cpp | 16 ++++++++++++---- interface/src/scripting/WebWindowClass.h | 3 +++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/interface/src/scripting/WebWindowClass.cpp b/interface/src/scripting/WebWindowClass.cpp index cc6f4fbfff..be87870f26 100644 --- a/interface/src/scripting/WebWindowClass.cpp +++ b/interface/src/scripting/WebWindowClass.cpp @@ -41,19 +41,27 @@ WebWindowClass::WebWindowClass(const QString& title, const QString& url, int wid _dockWidget = new QDockWidget(title, toolWindow); _dockWidget->setFeatures(QDockWidget::DockWidgetMovable); - QWebView* webView = new QWebView(_dockWidget); - webView->page()->mainFrame()->addToJavaScriptWindowObject("EventBridge", _eventBridge); - webView->setUrl(url); - _dockWidget->setWidget(webView); + + _webView = new QWebView(_dockWidget); + _webView->setUrl(url); + addEventBridgeToWindowObject(); + + _dockWidget->setWidget(_webView); toolWindow->addDockWidget(Qt::RightDockWidgetArea, _dockWidget); + connect(_webView->page()->mainFrame(), &QWebFrame::javaScriptWindowObjectCleared, + this, &WebWindowClass::addEventBridgeToWindowObject); connect(this, &WebWindowClass::destroyed, _dockWidget, &QWidget::deleteLater); } WebWindowClass::~WebWindowClass() { } +void WebWindowClass::addEventBridgeToWindowObject() { + _webView->page()->mainFrame()->addToJavaScriptWindowObject("EventBridge", _eventBridge); +} + void WebWindowClass::setVisible(bool visible) { if (visible) { QMetaObject::invokeMethod( diff --git a/interface/src/scripting/WebWindowClass.h b/interface/src/scripting/WebWindowClass.h index ae0d14ae06..0fa88804f2 100644 --- a/interface/src/scripting/WebWindowClass.h +++ b/interface/src/scripting/WebWindowClass.h @@ -14,6 +14,7 @@ #include #include +#include class ScriptEventBridge : public QObject { Q_OBJECT @@ -42,9 +43,11 @@ public: public slots: void setVisible(bool visible); ScriptEventBridge* getEventBridge() const { return _eventBridge; } + void addEventBridgeToWindowObject(); private: QDockWidget* _dockWidget; + QWebView* _webView; ScriptEventBridge* _eventBridge; }; From f8f9c25d381620ff1e2ed0a6d2fcb274ab960eb4 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 19 Jan 2015 14:59:28 -0800 Subject: [PATCH 08/30] Back to JPG compression for heightfield colors. --- .../src/metavoxels/MetavoxelServer.cpp | 2 +- libraries/metavoxels/src/Spanner.cpp | 76 +++++-------------- libraries/networking/src/PacketHeaders.cpp | 2 +- 3 files changed, 20 insertions(+), 60 deletions(-) diff --git a/assignment-client/src/metavoxels/MetavoxelServer.cpp b/assignment-client/src/metavoxels/MetavoxelServer.cpp index f52cdf3e49..5c4591cf61 100644 --- a/assignment-client/src/metavoxels/MetavoxelServer.cpp +++ b/assignment-client/src/metavoxels/MetavoxelServer.cpp @@ -311,7 +311,7 @@ MetavoxelPersister::MetavoxelPersister(MetavoxelServer* server) : const char* SAVE_FILE = "/resources/metavoxels.dat"; const int FILE_MAGIC = 0xDADAFACE; -const int FILE_VERSION = 3; +const int FILE_VERSION = 4; void MetavoxelPersister::load() { QString path = QCoreApplication::applicationDirPath() + SAVE_FILE; diff --git a/libraries/metavoxels/src/Spanner.cpp b/libraries/metavoxels/src/Spanner.cpp index e890821ec2..b550207ec0 100644 --- a/libraries/metavoxels/src/Spanner.cpp +++ b/libraries/metavoxels/src/Spanner.cpp @@ -681,41 +681,17 @@ void HeightfieldHeightEditor::clear() { } static QByteArray encodeHeightfieldColor(int offsetX, int offsetY, int width, int height, const QByteArray& contents) { - QByteArray inflated(HEIGHTFIELD_DATA_HEADER_SIZE + contents.size(), 0); + QByteArray inflated(HEIGHTFIELD_DATA_HEADER_SIZE, 0); qint32* header = (qint32*)inflated.data(); *header++ = offsetX; *header++ = offsetY; *header++ = width; *header++ = height; if (!contents.isEmpty()) { - // encode with Paeth filter (see http://en.wikipedia.org/wiki/Portable_Network_Graphics#Filtering) - const uchar* src = (const uchar*)contents.constData(); - uchar* dest = (uchar*)inflated.data() + HEIGHTFIELD_DATA_HEADER_SIZE; - *dest++ = *src++; - *dest++ = *src++; - *dest++ = *src++; - int stride = width * DataBlock::COLOR_BYTES; - for (uchar* end = dest + stride - DataBlock::COLOR_BYTES; dest != end; dest++, src++) { - *dest = *src - src[-DataBlock::COLOR_BYTES]; - } - for (int y = 1; y < height; y++) { - *dest++ = *src - src[-stride]; - src++; - *dest++ = *src - src[-stride]; - src++; - *dest++ = *src - src[-stride]; - src++; - for (uchar* end = dest + stride - DataBlock::COLOR_BYTES; dest != end; dest++, src++) { - int a = src[-DataBlock::COLOR_BYTES]; - int b = src[-stride]; - int c = src[-stride - DataBlock::COLOR_BYTES]; - int p = a + b - c; - int ad = abs(a - p); - int bd = abs(b - p); - int cd = abs(c - p); - *dest = *src - (ad < bd ? (ad < cd ? a : c) : (bd < cd ? b : c)); - } - } + QBuffer buffer(&inflated); + buffer.open(QIODevice::WriteOnly | QIODevice::Append); + QImage((const uchar*)contents.constData(), width, height, width * DataBlock::COLOR_BYTES, + QImage::Format_RGB888).save(&buffer, "JPG"); } return qCompress(inflated); } @@ -727,35 +703,19 @@ static QByteArray decodeHeightfieldColor(const QByteArray& encoded, int& offsetX offsetY = *header++; width = *header++; height = *header++; - QByteArray contents(inflated.size() - HEIGHTFIELD_DATA_HEADER_SIZE, 0); - if (!contents.isEmpty()) { - const uchar* src = (const uchar*)inflated.constData() + HEIGHTFIELD_DATA_HEADER_SIZE; - uchar* dest = (uchar*)contents.data(); - *dest++ = *src++; - *dest++ = *src++; - *dest++ = *src++; - int stride = width * DataBlock::COLOR_BYTES; - for (uchar* end = dest + stride - DataBlock::COLOR_BYTES; dest != end; dest++, src++) { - *dest = *src + dest[-DataBlock::COLOR_BYTES]; - } - for (int y = 1; y < height; y++) { - *dest = (*src++) + dest[-stride]; - dest++; - *dest = (*src++) + dest[-stride]; - dest++; - *dest = (*src++) + dest[-stride]; - dest++; - for (uchar* end = dest + stride - DataBlock::COLOR_BYTES; dest != end; dest++, src++) { - int a = dest[-DataBlock::COLOR_BYTES]; - int b = dest[-stride]; - int c = dest[-stride - DataBlock::COLOR_BYTES]; - int p = a + b - c; - int ad = abs(a - p); - int bd = abs(b - p); - int cd = abs(c - p); - *dest = *src + (ad < bd ? (ad < cd ? a : c) : (bd < cd ? b : c)); - } - } + int payloadSize = inflated.size() - HEIGHTFIELD_DATA_HEADER_SIZE; + if (payloadSize == 0) { + return QByteArray(); + } + QImage image = QImage::fromData((const uchar*)inflated.constData() + HEIGHTFIELD_DATA_HEADER_SIZE, payloadSize, "JPG"); + if (image.format() != QImage::Format_RGB888) { + image = image.convertToFormat(QImage::Format_RGB888); + } + QByteArray contents(width * height * DataBlock::COLOR_BYTES, 0); + char* dest = contents.data(); + int stride = width * DataBlock::COLOR_BYTES; + for (int y = 0; y < height; y++, dest += stride) { + memcpy(dest, image.constScanLine(y), stride); } return contents; } diff --git a/libraries/networking/src/PacketHeaders.cpp b/libraries/networking/src/PacketHeaders.cpp index 5b9811a152..110892a106 100644 --- a/libraries/networking/src/PacketHeaders.cpp +++ b/libraries/networking/src/PacketHeaders.cpp @@ -78,7 +78,7 @@ PacketVersion versionForPacketType(PacketType type) { case PacketTypeAudioStreamStats: return 1; case PacketTypeMetavoxelData: - return 11; + return 12; default: return 0; } From e5f3d48ffbbdac5fb58923caf9ccc2edf6513f18 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 19 Jan 2015 16:33:41 -0800 Subject: [PATCH 09/30] Fix for splatted textures against empty regions. --- interface/resources/shaders/metavoxel_heightfield_splat.frag | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/resources/shaders/metavoxel_heightfield_splat.frag b/interface/resources/shaders/metavoxel_heightfield_splat.frag index bb6b0d6536..180cb653ad 100644 --- a/interface/resources/shaders/metavoxel_heightfield_splat.frag +++ b/interface/resources/shaders/metavoxel_heightfield_splat.frag @@ -22,7 +22,7 @@ varying vec4 alphaValues; void main(void) { // blend the splat textures - gl_FragColor = gl_Color * (texture2D(diffuseMaps[0], gl_TexCoord[0].st) * alphaValues.x + + gl_FragColor = vec4(gl_Color.rgb, step(0.5, gl_Color.a)) * (texture2D(diffuseMaps[0], gl_TexCoord[0].st) * alphaValues.x + texture2D(diffuseMaps[1], gl_TexCoord[1].st) * alphaValues.y + texture2D(diffuseMaps[2], gl_TexCoord[2].st) * alphaValues.z + texture2D(diffuseMaps[3], gl_TexCoord[3].st) * alphaValues.w); From dafa44570a448cffc50d04c828fa3e8bcf235584 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 19 Jan 2015 17:15:58 -0800 Subject: [PATCH 10/30] That was not the shader change I wanted to check in. This was. --- interface/resources/shaders/metavoxel_heightfield_splat.frag | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interface/resources/shaders/metavoxel_heightfield_splat.frag b/interface/resources/shaders/metavoxel_heightfield_splat.frag index 180cb653ad..0754987fc3 100644 --- a/interface/resources/shaders/metavoxel_heightfield_splat.frag +++ b/interface/resources/shaders/metavoxel_heightfield_splat.frag @@ -22,7 +22,8 @@ varying vec4 alphaValues; void main(void) { // blend the splat textures - gl_FragColor = vec4(gl_Color.rgb, step(0.5, gl_Color.a)) * (texture2D(diffuseMaps[0], gl_TexCoord[0].st) * alphaValues.x + + gl_FragColor = vec4(gl_Color.rgb, step(1.0, gl_Color.a + 1.0 / 512.0)) * + (texture2D(diffuseMaps[0], gl_TexCoord[0].st) * alphaValues.x + texture2D(diffuseMaps[1], gl_TexCoord[1].st) * alphaValues.y + texture2D(diffuseMaps[2], gl_TexCoord[2].st) * alphaValues.z + texture2D(diffuseMaps[3], gl_TexCoord[3].st) * alphaValues.w); From a16b54a34a9ff0e9a15e8591a30c9dde29ce8735 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 19 Jan 2015 17:23:31 -0800 Subject: [PATCH 11/30] Let's try not using the "augmented" data, since we don't need it. --- interface/src/MetavoxelSystem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index a566b18b7e..eb2933d113 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -154,7 +154,7 @@ void MetavoxelSystem::simulate(float deltaTime) { } SimulateVisitor simulateVisitor(deltaTime, getLOD()); - guideToAugmented(simulateVisitor); + guide(simulateVisitor); } class RenderVisitor : public MetavoxelVisitor { @@ -199,7 +199,7 @@ void MetavoxelSystem::render() { viewFrustum->getNearBottomLeft(), viewFrustum->getNearBottomRight()); RenderVisitor renderVisitor(getLOD()); - guideToAugmented(renderVisitor, true); + guide(renderVisitor); if (!_heightfieldBaseBatches.isEmpty() && Menu::getInstance()->isOptionChecked(MenuOption::RenderHeightfields)) { glEnableClientState(GL_VERTEX_ARRAY); From 16de6a130bfdc81346f942072b248687fc12df3e Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 19 Jan 2015 17:29:43 -0800 Subject: [PATCH 12/30] Scratch that last change; it wasn't the problem. --- interface/src/MetavoxelSystem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index eb2933d113..a566b18b7e 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -154,7 +154,7 @@ void MetavoxelSystem::simulate(float deltaTime) { } SimulateVisitor simulateVisitor(deltaTime, getLOD()); - guide(simulateVisitor); + guideToAugmented(simulateVisitor); } class RenderVisitor : public MetavoxelVisitor { @@ -199,7 +199,7 @@ void MetavoxelSystem::render() { viewFrustum->getNearBottomLeft(), viewFrustum->getNearBottomRight()); RenderVisitor renderVisitor(getLOD()); - guide(renderVisitor); + guideToAugmented(renderVisitor, true); if (!_heightfieldBaseBatches.isEmpty() && Menu::getInstance()->isOptionChecked(MenuOption::RenderHeightfields)) { glEnableClientState(GL_VERTEX_ARRAY); From e4f29412d58a4228693844d8974647f43c9d7118 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Mon, 19 Jan 2015 18:11:14 -0800 Subject: [PATCH 13/30] cheaper failure adding entity to physics engine --- libraries/physics/src/PhysicsEngine.cpp | 103 ++++++++++++------------ libraries/physics/src/PhysicsEngine.h | 2 +- 2 files changed, 51 insertions(+), 54 deletions(-) diff --git a/libraries/physics/src/PhysicsEngine.cpp b/libraries/physics/src/PhysicsEngine.cpp index 90fd6c65cd..a216e062b3 100644 --- a/libraries/physics/src/PhysicsEngine.cpp +++ b/libraries/physics/src/PhysicsEngine.cpp @@ -60,14 +60,17 @@ void PhysicsEngine::addEntityInternal(EntityItem* entity) { assert(entity); void* physicsInfo = entity->getPhysicsInfo(); if (!physicsInfo) { - EntityMotionState* motionState = new EntityMotionState(entity); - if (addObject(motionState)) { + ShapeInfo shapeInfo; + entity->computeShapeInfo(shapeInfo); + btCollisionShape* shape = _shapeManager.getShape(shapeInfo); + if (shape) { + EntityMotionState* motionState = new EntityMotionState(entity); entity->setPhysicsInfo(static_cast(motionState)); _entityMotionStates.insert(motionState); + addObject(shapeInfo, shape, motionState); } else { // We failed to add the entity to the simulation. Probably because we couldn't create a shape for it. //qDebug() << "failed to add entity " << entity->getEntityItemID() << " to physics engine"; - delete motionState; } } } @@ -244,59 +247,53 @@ void PhysicsEngine::stepSimulation() { // CF_DISABLE_VISUALIZE_OBJECT = 32, //disable debug drawing // CF_DISABLE_SPU_COLLISION_PROCESSING = 64//disable parallel/SPU processing -bool PhysicsEngine::addObject(ObjectMotionState* motionState) { +void PhysicsEngine::addObject(const ShapeInfo& shapeInfo, btCollisionShape* shape, ObjectMotionState* motionState) { + assert(shape); assert(motionState); - ShapeInfo shapeInfo; - motionState->computeShapeInfo(shapeInfo); - btCollisionShape* shape = _shapeManager.getShape(shapeInfo); - if (shape) { - btVector3 inertia(0.0f, 0.0f, 0.0f); - float mass = 0.0f; - btRigidBody* body = NULL; - switch(motionState->computeMotionType()) { - case MOTION_TYPE_KINEMATIC: { - body = new btRigidBody(mass, motionState, shape, inertia); - body->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); - body->updateInertiaTensor(); - motionState->_body = body; - motionState->addKinematicController(); - const float KINEMATIC_LINEAR_VELOCITY_THRESHOLD = 0.01f; // 1 cm/sec - const float KINEMATIC_ANGULAR_VELOCITY_THRESHOLD = 0.01f; // ~1 deg/sec - body->setSleepingThresholds(KINEMATIC_LINEAR_VELOCITY_THRESHOLD, KINEMATIC_ANGULAR_VELOCITY_THRESHOLD); - break; - } - case MOTION_TYPE_DYNAMIC: { - mass = motionState->computeMass(shapeInfo); - shape->calculateLocalInertia(mass, inertia); - body = new btRigidBody(mass, motionState, shape, inertia); - body->updateInertiaTensor(); - motionState->_body = body; - motionState->updateObjectVelocities(); - // NOTE: Bullet will deactivate any object whose velocity is below these thresholds for longer than 2 seconds. - // (the 2 seconds is determined by: static btRigidBody::gDeactivationTime - const float DYNAMIC_LINEAR_VELOCITY_THRESHOLD = 0.05f; // 5 cm/sec - const float DYNAMIC_ANGULAR_VELOCITY_THRESHOLD = 0.087266f; // ~5 deg/sec - body->setSleepingThresholds(DYNAMIC_LINEAR_VELOCITY_THRESHOLD, DYNAMIC_ANGULAR_VELOCITY_THRESHOLD); - break; - } - case MOTION_TYPE_STATIC: - default: { - body = new btRigidBody(mass, motionState, shape, inertia); - body->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT); - body->updateInertiaTensor(); - motionState->_body = body; - break; - } + + btVector3 inertia(0.0f, 0.0f, 0.0f); + float mass = 0.0f; + btRigidBody* body = NULL; + switch(motionState->computeMotionType()) { + case MOTION_TYPE_KINEMATIC: { + body = new btRigidBody(mass, motionState, shape, inertia); + body->setCollisionFlags(btCollisionObject::CF_KINEMATIC_OBJECT); + body->updateInertiaTensor(); + motionState->_body = body; + motionState->addKinematicController(); + const float KINEMATIC_LINEAR_VELOCITY_THRESHOLD = 0.01f; // 1 cm/sec + const float KINEMATIC_ANGULAR_VELOCITY_THRESHOLD = 0.01f; // ~1 deg/sec + body->setSleepingThresholds(KINEMATIC_LINEAR_VELOCITY_THRESHOLD, KINEMATIC_ANGULAR_VELOCITY_THRESHOLD); + break; + } + case MOTION_TYPE_DYNAMIC: { + mass = motionState->computeMass(shapeInfo); + shape->calculateLocalInertia(mass, inertia); + body = new btRigidBody(mass, motionState, shape, inertia); + body->updateInertiaTensor(); + motionState->_body = body; + motionState->updateObjectVelocities(); + // NOTE: Bullet will deactivate any object whose velocity is below these thresholds for longer than 2 seconds. + // (the 2 seconds is determined by: static btRigidBody::gDeactivationTime + const float DYNAMIC_LINEAR_VELOCITY_THRESHOLD = 0.05f; // 5 cm/sec + const float DYNAMIC_ANGULAR_VELOCITY_THRESHOLD = 0.087266f; // ~5 deg/sec + body->setSleepingThresholds(DYNAMIC_LINEAR_VELOCITY_THRESHOLD, DYNAMIC_ANGULAR_VELOCITY_THRESHOLD); + break; + } + case MOTION_TYPE_STATIC: + default: { + body = new btRigidBody(mass, motionState, shape, inertia); + body->setCollisionFlags(btCollisionObject::CF_STATIC_OBJECT); + body->updateInertiaTensor(); + motionState->_body = body; + break; } - // wtf? - body->setFlags(BT_DISABLE_WORLD_GRAVITY); - body->setRestitution(motionState->_restitution); - body->setFriction(motionState->_friction); - body->setDamping(motionState->_linearDamping, motionState->_angularDamping); - _dynamicsWorld->addRigidBody(body); - return true; } - return false; + body->setFlags(BT_DISABLE_WORLD_GRAVITY); + body->setRestitution(motionState->_restitution); + body->setFriction(motionState->_friction); + body->setDamping(motionState->_linearDamping, motionState->_angularDamping); + _dynamicsWorld->addRigidBody(body); } bool PhysicsEngine::removeObject(ObjectMotionState* motionState) { diff --git a/libraries/physics/src/PhysicsEngine.h b/libraries/physics/src/PhysicsEngine.h index f37f12ea8d..4dc4b67156 100644 --- a/libraries/physics/src/PhysicsEngine.h +++ b/libraries/physics/src/PhysicsEngine.h @@ -59,7 +59,7 @@ public: /// \param motionState pointer to Object's MotionState /// \return true if Object added - bool addObject(ObjectMotionState* motionState); + void addObject(const ShapeInfo& shapeInfo, btCollisionShape* shape, ObjectMotionState* motionState); /// \param motionState pointer to Object's MotionState /// \return true if Object removed From 214a18c44649fd10b460150efcfb4acdfd5a0e4a Mon Sep 17 00:00:00 2001 From: David Rowe Date: Mon, 19 Jan 2015 19:33:12 -0800 Subject: [PATCH 14/30] Guard against derefencing NULL --- interface/src/ui/overlays/Overlays.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/interface/src/ui/overlays/Overlays.cpp b/interface/src/ui/overlays/Overlays.cpp index 8f9f54c591..b08b429ad0 100644 --- a/interface/src/ui/overlays/Overlays.cpp +++ b/interface/src/ui/overlays/Overlays.cpp @@ -220,7 +220,12 @@ unsigned int Overlays::cloneOverlay(unsigned int id) { } else if (_overlaysWorld.contains(id)) { thisOverlay = _overlaysWorld[id]; } - return addOverlay(thisOverlay->createClone()); + + if (thisOverlay) { + return addOverlay(thisOverlay->createClone()); + } + + return 0; // Not found } bool Overlays::editOverlay(unsigned int id, const QScriptValue& properties) { From 35bd1cda8987edc5bf209bfbdfecac7769428869 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 19 Jan 2015 21:52:56 -0800 Subject: [PATCH 15/30] I believe this should fix some problems with flickering/crashing on edits: don't reapply properties that we've already read (thus clearing cached data, stepping on other threads, etc.) --- libraries/metavoxels/src/Bitstream.cpp | 20 +++++++++----- libraries/metavoxels/src/SharedObject.cpp | 4 +-- libraries/metavoxels/src/SharedObject.h | 6 +++-- libraries/metavoxels/src/Spanner.cpp | 32 +++++++++++++++++------ libraries/metavoxels/src/Spanner.h | 4 +-- 5 files changed, 46 insertions(+), 20 deletions(-) diff --git a/libraries/metavoxels/src/Bitstream.cpp b/libraries/metavoxels/src/Bitstream.cpp index c3bd05d3c7..642562bfb5 100644 --- a/libraries/metavoxels/src/Bitstream.cpp +++ b/libraries/metavoxels/src/Bitstream.cpp @@ -2432,12 +2432,13 @@ void MappedObjectStreamer::writeRawDelta(Bitstream& out, const QObject* object, } QObject* MappedObjectStreamer::read(Bitstream& in, QObject* object) const { + bool reread = (object != NULL); if (!object && _metaObject) { object = _metaObject->newInstance(); } foreach (const StreamerPropertyPair& property, _properties) { QVariant value = property.first->read(in); - if (property.second.isValid() && object) { + if (property.second.isValid() && object && !reread) { property.second.write(object, value); } } @@ -2445,6 +2446,7 @@ QObject* MappedObjectStreamer::read(Bitstream& in, QObject* object) const { } QObject* MappedObjectStreamer::readRawDelta(Bitstream& in, const QObject* reference, QObject* object) const { + bool reread = (object != NULL); if (!object && _metaObject) { object = _metaObject->newInstance(); } @@ -2452,7 +2454,7 @@ QObject* MappedObjectStreamer::readRawDelta(Bitstream& in, const QObject* refere QVariant value; property.first->readDelta(in, value, (property.second.isValid() && reference && reference->metaObject() == _metaObject) ? property.second.read(reference) : QVariant()); - if (property.second.isValid() && object) { + if (property.second.isValid() && object && !reread) { property.second.write(object, value); } } @@ -2475,13 +2477,13 @@ void SharedObjectStreamer::writeRawDelta(Bitstream& out, const QObject* object, QObject* SharedObjectStreamer::read(Bitstream& in, QObject* object) const { QObject* result = MappedObjectStreamer::read(in, object); - static_cast(result)->readExtra(in); + static_cast(result)->readExtra(in, object != NULL); return result; } QObject* SharedObjectStreamer::readRawDelta(Bitstream& in, const QObject* reference, QObject* object) const { QObject* result = MappedObjectStreamer::readRawDelta(in, reference, object); - static_cast(result)->readExtraDelta(in, static_cast(reference)); + static_cast(result)->readExtraDelta(in, static_cast(reference), object != NULL); return result; } @@ -2592,6 +2594,7 @@ void GenericObjectStreamer::writeRawDelta(Bitstream& out, const QObject* object, } QObject* GenericObjectStreamer::read(Bitstream& in, QObject* object) const { + bool reread = (object != NULL); if (!object) { object = new GenericSharedObject(_weakSelf); } @@ -2599,11 +2602,14 @@ QObject* GenericObjectStreamer::read(Bitstream& in, QObject* object) const { foreach (const StreamerNamePair& property, _properties) { values.append(property.first->read(in)); } - static_cast(object)->setValues(values); + if (!reread) { + static_cast(object)->setValues(values); + } return object; } QObject* GenericObjectStreamer::readRawDelta(Bitstream& in, const QObject* reference, QObject* object) const { + bool reread = (object != NULL); if (!object) { object = new GenericSharedObject(_weakSelf); } @@ -2615,7 +2621,9 @@ QObject* GenericObjectStreamer::readRawDelta(Bitstream& in, const QObject* refer static_cast(reference)->getValues().at(i) : QVariant()); values.append(value); } - static_cast(object)->setValues(values); + if (!reread) { + static_cast(object)->setValues(values); + } return object; } diff --git a/libraries/metavoxels/src/SharedObject.cpp b/libraries/metavoxels/src/SharedObject.cpp index dcfa9732b3..6369037e2a 100644 --- a/libraries/metavoxels/src/SharedObject.cpp +++ b/libraries/metavoxels/src/SharedObject.cpp @@ -135,7 +135,7 @@ void SharedObject::writeExtra(Bitstream& out) const { // nothing by default } -void SharedObject::readExtra(Bitstream& in) { +void SharedObject::readExtra(Bitstream& in, bool reread) { // nothing by default } @@ -143,7 +143,7 @@ void SharedObject::writeExtraDelta(Bitstream& out, const SharedObject* reference // nothing by default } -void SharedObject::readExtraDelta(Bitstream& in, const SharedObject* reference) { +void SharedObject::readExtraDelta(Bitstream& in, const SharedObject* reference, bool reread) { // nothing by default } diff --git a/libraries/metavoxels/src/SharedObject.h b/libraries/metavoxels/src/SharedObject.h index ebea322bf1..cd46ae9658 100644 --- a/libraries/metavoxels/src/SharedObject.h +++ b/libraries/metavoxels/src/SharedObject.h @@ -84,13 +84,15 @@ public: virtual void writeExtra(Bitstream& out) const; /// Reads the non-property contents of this object from the specified stream. - virtual void readExtra(Bitstream& in); + /// \param reread if true, reread the contents from the stream but don't reapply them + virtual void readExtra(Bitstream& in, bool reread = false); /// Writes the delta-encoded non-property contents of this object to the specified stream. virtual void writeExtraDelta(Bitstream& out, const SharedObject* reference) const; /// Reads the delta-encoded non-property contents of this object from the specified stream. - virtual void readExtraDelta(Bitstream& in, const SharedObject* reference); + /// \param reread if true, reread the contents from the stream but don't reapply them + virtual void readExtraDelta(Bitstream& in, const SharedObject* reference, bool reread = false); /// Writes the subdivision of the contents of this object (preceeded by a /// reference to the object itself) to the specified stream if necessary. diff --git a/libraries/metavoxels/src/Spanner.cpp b/libraries/metavoxels/src/Spanner.cpp index b550207ec0..c771b8fb4a 100644 --- a/libraries/metavoxels/src/Spanner.cpp +++ b/libraries/metavoxels/src/Spanner.cpp @@ -3678,9 +3678,18 @@ void Heightfield::writeExtra(Bitstream& out) const { _root->write(state); } -void Heightfield::readExtra(Bitstream& in) { +void Heightfield::readExtra(Bitstream& in, bool reread) { if (getWillBeVoxelized()) { - in >> _height >> _color >> _material >> _stack; + if (reread) { + HeightfieldHeightPointer height; + HeightfieldColorPointer color; + HeightfieldMaterialPointer material; + HeightfieldStackPointer stack; + in >> height >> color >> material >> stack; + + } else { + in >> _height >> _color >> _material >> _stack; + } return; } MetavoxelLOD lod; @@ -3692,7 +3701,9 @@ void Heightfield::readExtra(Bitstream& in) { HeightfieldNodePointer root(new HeightfieldNode()); root->read(state); - setRoot(root); + if (!reread) { + setRoot(root); + } } void Heightfield::writeExtraDelta(Bitstream& out, const SharedObject* reference) const { @@ -3716,7 +3727,7 @@ void Heightfield::writeExtraDelta(Bitstream& out, const SharedObject* reference) } } -void Heightfield::readExtraDelta(Bitstream& in, const SharedObject* reference) { +void Heightfield::readExtraDelta(Bitstream& in, const SharedObject* reference, bool reread) { MetavoxelLOD lod, referenceLOD; if (in.getContext()) { MetavoxelStreamBase* base = static_cast(in.getContext()); @@ -3726,16 +3737,21 @@ void Heightfield::readExtraDelta(Bitstream& in, const SharedObject* reference) { HeightfieldStreamBase base = { in, lod, referenceLOD }; HeightfieldStreamState state = { base, glm::vec2(), 1.0f }; - setRoot(static_cast(reference)->getRoot()); bool changed; in >> changed; if (changed) { HeightfieldNodePointer root(new HeightfieldNode()); root->readDelta(static_cast(reference)->getRoot(), state); - setRoot(root); - + if (!reread) { + setRoot(root); + } } else if (state.becameSubdividedOrCollapsed()) { - setRoot(HeightfieldNodePointer(_root->readSubdivision(state))); + HeightfieldNodePointer root(_root->readSubdivision(state)); + if (!reread) { + setRoot(root); + } + } else if (!reread) { + setRoot(static_cast(reference)->getRoot()); } } diff --git a/libraries/metavoxels/src/Spanner.h b/libraries/metavoxels/src/Spanner.h index 12d04edd14..653893c84d 100644 --- a/libraries/metavoxels/src/Spanner.h +++ b/libraries/metavoxels/src/Spanner.h @@ -820,9 +820,9 @@ public: virtual bool intersects(const glm::vec3& start, const glm::vec3& end, float& distance, glm::vec3& normal); virtual void writeExtra(Bitstream& out) const; - virtual void readExtra(Bitstream& in); + virtual void readExtra(Bitstream& in, bool reread); virtual void writeExtraDelta(Bitstream& out, const SharedObject* reference) const; - virtual void readExtraDelta(Bitstream& in, const SharedObject* reference); + virtual void readExtraDelta(Bitstream& in, const SharedObject* reference, bool reread); virtual void maybeWriteSubdivision(Bitstream& out); virtual SharedObject* readSubdivision(Bitstream& in); From 483d072709c086f20eec186984f4a45f7ad0cc36 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 20 Jan 2015 10:47:57 -0800 Subject: [PATCH 16/30] handle override path from address bar --- libraries/networking/src/AccountManager.cpp | 27 +++++++--- libraries/networking/src/AccountManager.h | 9 ++-- libraries/networking/src/AddressManager.cpp | 60 ++++++++++++++------- libraries/networking/src/AddressManager.h | 4 +- 4 files changed, 70 insertions(+), 30 deletions(-) diff --git a/libraries/networking/src/AccountManager.cpp b/libraries/networking/src/AccountManager.cpp index 0c63ecc731..067bd110c4 100644 --- a/libraries/networking/src/AccountManager.cpp +++ b/libraries/networking/src/AccountManager.cpp @@ -158,7 +158,8 @@ void AccountManager::setAuthURL(const QUrl& authURL) { void AccountManager::authenticatedRequest(const QString& path, QNetworkAccessManager::Operation operation, const JSONCallbackParameters& callbackParams, const QByteArray& dataByteArray, - QHttpMultiPart* dataMultiPart) { + QHttpMultiPart* dataMultiPart, + const QVariantMap& propertyMap) { QMetaObject::invokeMethod(this, "invokedRequest", Q_ARG(const QString&, path), @@ -166,13 +167,15 @@ void AccountManager::authenticatedRequest(const QString& path, QNetworkAccessMan Q_ARG(QNetworkAccessManager::Operation, operation), Q_ARG(const JSONCallbackParameters&, callbackParams), Q_ARG(const QByteArray&, dataByteArray), - Q_ARG(QHttpMultiPart*, dataMultiPart)); + Q_ARG(QHttpMultiPart*, dataMultiPart), + Q_ARG(QVariantMap, propertyMap)); } void AccountManager::unauthenticatedRequest(const QString& path, QNetworkAccessManager::Operation operation, - const JSONCallbackParameters& callbackParams, - const QByteArray& dataByteArray, - QHttpMultiPart* dataMultiPart) { + const JSONCallbackParameters& callbackParams, + const QByteArray& dataByteArray, + QHttpMultiPart* dataMultiPart, + const QVariantMap& propertyMap) { QMetaObject::invokeMethod(this, "invokedRequest", Q_ARG(const QString&, path), @@ -180,14 +183,16 @@ void AccountManager::unauthenticatedRequest(const QString& path, QNetworkAccessM Q_ARG(QNetworkAccessManager::Operation, operation), Q_ARG(const JSONCallbackParameters&, callbackParams), Q_ARG(const QByteArray&, dataByteArray), - Q_ARG(QHttpMultiPart*, dataMultiPart)); + Q_ARG(QHttpMultiPart*, dataMultiPart), + Q_ARG(QVariantMap, propertyMap)); } void AccountManager::invokedRequest(const QString& path, bool requiresAuthentication, QNetworkAccessManager::Operation operation, const JSONCallbackParameters& callbackParams, - const QByteArray& dataByteArray, QHttpMultiPart* dataMultiPart) { + const QByteArray& dataByteArray, QHttpMultiPart* dataMultiPart, + const QVariantMap& propertyMap) { QNetworkAccessManager& networkAccessManager = NetworkAccessManager::getInstance(); @@ -255,6 +260,14 @@ void AccountManager::invokedRequest(const QString& path, } if (networkReply) { + if (!propertyMap.isEmpty()) { + // we have properties to set on the reply so the user can check them after + foreach(const QString& propertyKey, propertyMap.keys()) { + networkReply->setProperty(qPrintable(propertyKey), propertyMap.value(propertyKey)); + } + } + + if (!callbackParams.isEmpty()) { // if we have information for a callback, insert the callbackParams into our local map _pendingCallbackMap.insert(networkReply, callbackParams); diff --git a/libraries/networking/src/AccountManager.h b/libraries/networking/src/AccountManager.h index 53512a8bb3..06fe366d69 100644 --- a/libraries/networking/src/AccountManager.h +++ b/libraries/networking/src/AccountManager.h @@ -48,13 +48,15 @@ public: QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, const JSONCallbackParameters& callbackParams = JSONCallbackParameters(), const QByteArray& dataByteArray = QByteArray(), - QHttpMultiPart* dataMultiPart = NULL); + QHttpMultiPart* dataMultiPart = NULL, + const QVariantMap& propertyMap = QVariantMap()); void unauthenticatedRequest(const QString& path, QNetworkAccessManager::Operation operation = QNetworkAccessManager::GetOperation, const JSONCallbackParameters& callbackParams = JSONCallbackParameters(), const QByteArray& dataByteArray = QByteArray(), - QHttpMultiPart* dataMultiPart = NULL); + QHttpMultiPart* dataMultiPart = NULL, + const QVariantMap& propertyMap = QVariantMap()) ; const QUrl& getAuthURL() const { return _authURL; } void setAuthURL(const QUrl& authURL); @@ -109,7 +111,8 @@ private: QNetworkAccessManager::Operation operation, const JSONCallbackParameters& callbackParams, const QByteArray& dataByteArray, - QHttpMultiPart* dataMultiPart); + QHttpMultiPart* dataMultiPart, + const QVariantMap& propertyMap); QUrl _authURL; QMap _pendingCallbackMap; diff --git a/libraries/networking/src/AddressManager.cpp b/libraries/networking/src/AddressManager.cpp index fba3861f43..54f45304ad 100644 --- a/libraries/networking/src/AddressManager.cpp +++ b/libraries/networking/src/AddressManager.cpp @@ -119,14 +119,16 @@ bool AddressManager::handleUrl(const QUrl& lookupUrl) { if (!handleUsername(lookupUrl.authority())) { // we're assuming this is either a network address or global place name // check if it is a network address first - if (!handleNetworkAddress(lookupUrl.host() + if (handleNetworkAddress(lookupUrl.host() + (lookupUrl.port() == -1 ? "" : ":" + QString::number(lookupUrl.port())))) { + // we may have a path that defines a relative viewpoint - if so we should jump to that now + handleRelativeViewpoint(lookupUrl.path()); + } else { // wasn't an address - lookup the place name - attemptPlaceNameLookup(lookupUrl.host()); + // we may have a path that defines a relative viewpoint - pass that through the lookup so we can go to it after + attemptPlaceNameLookup(lookupUrl.host(), lookupUrl.path()); + } - - // we may have a path that defines a relative viewpoint - if so we should jump to that now - handleRelativeViewpoint(lookupUrl.path()); } return true; @@ -164,12 +166,14 @@ void AddressManager::handleAPIResponse(QNetworkReply& requestReply) { QJsonObject responseObject = QJsonDocument::fromJson(requestReply.readAll()).object(); QJsonObject dataObject = responseObject["data"].toObject(); - goToAddressFromObject(dataObject.toVariantMap()); + goToAddressFromObject(dataObject.toVariantMap(), requestReply); emit lookupResultsFinished(); } -void AddressManager::goToAddressFromObject(const QVariantMap& dataObject) { +const char OVERRIDE_PATH_KEY[] = "override_path"; + +void AddressManager::goToAddressFromObject(const QVariantMap& dataObject, const QNetworkReply& reply) { const QString DATA_OBJECT_PLACE_KEY = "place"; const QString DATA_OBJECT_USER_LOCATION_KEY = "location"; @@ -223,18 +227,29 @@ void AddressManager::goToAddressFromObject(const QVariantMap& dataObject) { QString newRootPlaceName = rootMap[PLACE_NAME_KEY].toString(); setRootPlaceName(newRootPlaceName); - // take the path that came back - const QString PLACE_PATH_KEY = "path"; - QString returnedPath = locationMap[PLACE_PATH_KEY].toString(); + // check if we had a path to override the path returned + QString overridePath = reply.property(OVERRIDE_PATH_KEY).toString(); - bool shouldFaceViewpoint = locationMap.contains(LOCATION_API_ONLINE_KEY); - - if (!returnedPath.isEmpty()) { - // try to parse this returned path as a viewpoint, that's the only thing it could be for now - if (!handleRelativeViewpoint(returnedPath, shouldFaceViewpoint)) { - qDebug() << "Received a location path that was could not be handled as a viewpoint -" << returnedPath; + if (!overridePath.isEmpty()) { + if (!handleRelativeViewpoint(overridePath)){ + qDebug() << "User entered path could not be handled as a viewpoint - " << overridePath; + } + } else { + // take the path that came back + const QString PLACE_PATH_KEY = "path"; + QString returnedPath = locationMap[PLACE_PATH_KEY].toString(); + + bool shouldFaceViewpoint = locationMap.contains(LOCATION_API_ONLINE_KEY); + + if (!returnedPath.isEmpty()) { + // try to parse this returned path as a viewpoint, that's the only thing it could be for now + if (!handleRelativeViewpoint(returnedPath, shouldFaceViewpoint)) { + qDebug() << "Received a location path that was could not be handled as a viewpoint -" << returnedPath; + } } } + + } else { qDebug() << "Received an address manager API response with no domain key. Cannot parse."; qDebug() << locationMap; @@ -260,12 +275,21 @@ void AddressManager::handleAPIError(QNetworkReply& errorReply) { const QString GET_PLACE = "/api/v1/places/%1"; -void AddressManager::attemptPlaceNameLookup(const QString& lookupString) { +void AddressManager::attemptPlaceNameLookup(const QString& lookupString, const QString& overridePath) { // assume this is a place name and see if we can get any info on it QString placeName = QUrl::toPercentEncoding(lookupString); + + QVariantMap requestParams; + if (!overridePath.isEmpty()) { + requestParams.insert(OVERRIDE_PATH_KEY, overridePath); + } + AccountManager::getInstance().unauthenticatedRequest(GET_PLACE.arg(placeName), QNetworkAccessManager::GetOperation, - apiCallbackParameters()); + apiCallbackParameters(), + QByteArray(), + NULL, + requestParams); } bool AddressManager::handleNetworkAddress(const QString& lookupString) { diff --git a/libraries/networking/src/AddressManager.h b/libraries/networking/src/AddressManager.h index 58e4e88330..3071d68ea2 100644 --- a/libraries/networking/src/AddressManager.h +++ b/libraries/networking/src/AddressManager.h @@ -47,7 +47,7 @@ public: const QString& getRootPlaceName() const { return _rootPlaceName; } void setRootPlaceName(const QString& rootPlaceName); - void attemptPlaceNameLookup(const QString& lookupString); + void attemptPlaceNameLookup(const QString& lookupString, const QString& overridePath = QString()); void setPositionGetter(PositionGetter positionGetter) { _positionGetter = positionGetter; } void setOrientationGetter(OrientationGetter orientationGetter) { _orientationGetter = orientationGetter; } @@ -57,7 +57,7 @@ public: public slots: void handleLookupString(const QString& lookupString); void goToUser(const QString& username); - void goToAddressFromObject(const QVariantMap& addressMap); + void goToAddressFromObject(const QVariantMap& addressMap, const QNetworkReply& reply); void storeCurrentAddress(); From a66888939c7c0ebef3520036db1b5449a3366537 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 20 Jan 2015 10:51:11 -0800 Subject: [PATCH 17/30] add some debugging for domain switch --- libraries/networking/src/AccountManager.cpp | 1 + libraries/networking/src/AddressManager.cpp | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/libraries/networking/src/AccountManager.cpp b/libraries/networking/src/AccountManager.cpp index 067bd110c4..f902adbc18 100644 --- a/libraries/networking/src/AccountManager.cpp +++ b/libraries/networking/src/AccountManager.cpp @@ -240,6 +240,7 @@ void AccountManager::invokedRequest(const QString& path, } else { networkReply = networkAccessManager.put(networkRequest, dataMultiPart); } + qDebug() << "IS THIS WHERE?"; dataMultiPart->setParent(networkReply); } else { networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); diff --git a/libraries/networking/src/AddressManager.cpp b/libraries/networking/src/AddressManager.cpp index 54f45304ad..ff2925beea 100644 --- a/libraries/networking/src/AddressManager.cpp +++ b/libraries/networking/src/AddressManager.cpp @@ -207,6 +207,8 @@ void AddressManager::goToAddressFromObject(const QVariantMap& dataObject, const if (domainObject.contains(DOMAIN_NETWORK_ADDRESS_KEY)) { QString domainHostname = domainObject[DOMAIN_NETWORK_ADDRESS_KEY].toString(); + qDebug() << "Possible domain change required to connect to" << domainHostname + << "on" << DEFAULT_DOMAIN_SERVER_PORT; emit possibleDomainChangeRequired(domainHostname, DEFAULT_DOMAIN_SERVER_PORT); } else { QString iceServerAddress = domainObject[DOMAIN_ICE_SERVER_ADDRESS_KEY].toString(); @@ -215,6 +217,9 @@ void AddressManager::goToAddressFromObject(const QVariantMap& dataObject, const QString domainIDString = domainObject[DOMAIN_ID_KEY].toString(); QUuid domainID(domainIDString); + qDebug() << "Possible domain change required to connect to domain with ID" << domainID + << "via ice-server at" << iceServerAddress; + emit possibleDomainChangeRequiredViaICEForID(iceServerAddress, domainID); } From cd23876afc6147526337c332ddf829b40fd5cb7b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 20 Jan 2015 11:00:08 -0800 Subject: [PATCH 18/30] fix QHttpMultiPart destroy from AccountManager --- libraries/networking/src/AccountManager.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/libraries/networking/src/AccountManager.cpp b/libraries/networking/src/AccountManager.cpp index f902adbc18..c4a4c4a458 100644 --- a/libraries/networking/src/AccountManager.cpp +++ b/libraries/networking/src/AccountManager.cpp @@ -240,8 +240,9 @@ void AccountManager::invokedRequest(const QString& path, } else { networkReply = networkAccessManager.put(networkRequest, dataMultiPart); } - qDebug() << "IS THIS WHERE?"; - dataMultiPart->setParent(networkReply); + + // make sure dataMultiPart is destroyed when the reply is + connect(networkReply, &QNetworkReply::destroyed, dataMultiPart, &QHttpMultiPart::deleteLater); } else { networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); if (operation == QNetworkAccessManager::PostOperation) { From 8202c84c794a7231c4cf44d3475db8ae2780821c Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 20 Jan 2015 12:37:39 -0800 Subject: [PATCH 19/30] Add entity list menu option --- examples/editEntities.js | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/examples/editEntities.js b/examples/editEntities.js index 4e06125ea1..ad064d269b 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -44,10 +44,16 @@ var entityListTool = EntityListTool(); var hasShownPropertiesTool = false; +var entityListVisible = false; + selectionManager.addEventListener(function() { selectionDisplay.updateHandles(); if (selectionManager.hasSelection() && !hasShownPropertiesTool) { + // Open properties and model list, but force selection of model list tab + propertiesTool.setVisible(false); + entityListTool.setVisible(false); propertiesTool.setVisible(true); + entityListTool.setVisible(true); hasShownPropertiesTool = true; } }); @@ -232,7 +238,6 @@ var toolBar = (function () { cameraManager.disable(); } else { hasShownPropertiesTool = false; - entityListTool.setVisible(true); cameraManager.enable(); gridTool.setVisible(true); grid.setEnabled(true); @@ -703,6 +708,8 @@ function setupModelMenus() { Menu.addMenuItem({ menuName: "File", menuItemName: "Export Models", shortcutKey: "CTRL+META+E", afterItem: "Models" }); Menu.addMenuItem({ menuName: "File", menuItemName: "Import Models", shortcutKey: "CTRL+META+I", afterItem: "Export Models" }); + Menu.addMenuItem({ menuName: "Tools", menuItemName: "Entity List...", shortcutKey: "CTRL+META+L", afterItem: "Tool Window" }); + Menu.addMenuItem({ menuName: "View", menuItemName: MENU_EASE_ON_FOCUS, afterItem: MENU_INSPECT_TOOL_ENABLED, isCheckable: true, isChecked: Settings.getValue(SETTING_EASE_ON_FOCUS) == "true" }); @@ -727,6 +734,8 @@ function cleanupModelMenus() { Menu.removeMenuItem("File", "Export Models"); Menu.removeMenuItem("File", "Import Models"); + Menu.removeMenuItem("Tools", "Entity List..."); + Menu.removeMenuItem("View", MENU_INSPECT_TOOL_ENABLED); Menu.removeMenuItem("View", MENU_EASE_ON_FOCUS); } @@ -797,6 +806,10 @@ function handeMenuEvent(menuItem) { } } else if (menuItem == "Import Models") { modelImporter.doImport(); + } else if (menuItem == "Entity List...") { + if (isActive) { + entityListTool.toggleVisible(); + } } tooltip.show(false); } From 891f6fa5138e46dea5c9772c2b5d2135e11c5a26 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 20 Jan 2015 12:40:16 -0800 Subject: [PATCH 20/30] Move entity list to edit menu --- examples/editEntities.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/editEntities.js b/examples/editEntities.js index ad064d269b..3c11b2d7eb 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -696,7 +696,8 @@ function setupModelMenus() { print("delete exists... don't add ours"); } - Menu.addMenuItem({ menuName: "Edit", menuItemName: "Paste Models", shortcutKey: "CTRL+META+V", afterItem: "Models" }); + Menu.addMenuItem({ menuName: "Edit", menuItemName: "Entity List...", shortcutKey: "CTRL+META+L", afterItem: "Models" }); + Menu.addMenuItem({ menuName: "Edit", menuItemName: "Paste Models", shortcutKey: "CTRL+META+V", afterItem: "Entity List..." }); Menu.addMenuItem({ menuName: "Edit", menuItemName: "Allow Selecting of Large Models", shortcutKey: "CTRL+META+L", afterItem: "Paste Models", isCheckable: true, isChecked: true }); Menu.addMenuItem({ menuName: "Edit", menuItemName: "Allow Selecting of Small Models", shortcutKey: "CTRL+META+S", @@ -708,7 +709,6 @@ function setupModelMenus() { Menu.addMenuItem({ menuName: "File", menuItemName: "Export Models", shortcutKey: "CTRL+META+E", afterItem: "Models" }); Menu.addMenuItem({ menuName: "File", menuItemName: "Import Models", shortcutKey: "CTRL+META+I", afterItem: "Export Models" }); - Menu.addMenuItem({ menuName: "Tools", menuItemName: "Entity List...", shortcutKey: "CTRL+META+L", afterItem: "Tool Window" }); Menu.addMenuItem({ menuName: "View", menuItemName: MENU_EASE_ON_FOCUS, afterItem: MENU_INSPECT_TOOL_ENABLED, isCheckable: true, isChecked: Settings.getValue(SETTING_EASE_ON_FOCUS) == "true" }); From 903921e11f590ad460b6e658429a75a23c4c022d Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 20 Jan 2015 12:40:31 -0800 Subject: [PATCH 21/30] Update entity list to auto-refresh list on start --- examples/html/entityList.html | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/html/entityList.html b/examples/html/entityList.html index 6c9846f5e4..e1318a225c 100644 --- a/examples/html/entityList.html +++ b/examples/html/entityList.html @@ -170,6 +170,7 @@ updateSelectedEntities(data.selectedIDs); } }); + setTimeout(refreshEntities, 1000); } } From bc21faeefb4120dc1a0895c032b937539509228d Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 20 Jan 2015 12:41:58 -0800 Subject: [PATCH 22/30] Add entityListTool.toggleVisible --- examples/libraries/entityList.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/libraries/entityList.js b/examples/libraries/entityList.js index 10a2209309..8fbc40698f 100644 --- a/examples/libraries/entityList.js +++ b/examples/libraries/entityList.js @@ -13,6 +13,10 @@ EntityListTool = function(opts) { webView.setVisible(visible); }; + that.toggleVisible = function() { + that.setVisible(!visible); + } + selectionManager.addEventListener(function() { var selectedIDs = []; From 3a287a08aba52f4359ca6937059b2b62ee380302 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 20 Jan 2015 12:43:49 -0800 Subject: [PATCH 23/30] Fix removal of entity list menu item --- examples/editEntities.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/editEntities.js b/examples/editEntities.js index 3c11b2d7eb..9187b624fd 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -725,6 +725,7 @@ function cleanupModelMenus() { Menu.removeMenuItem("Edit", "Delete"); } + Menu.removeMenuItem("Edit", "Entity List..."); Menu.removeMenuItem("Edit", "Paste Models"); Menu.removeMenuItem("Edit", "Allow Selecting of Large Models"); Menu.removeMenuItem("Edit", "Allow Selecting of Small Models"); @@ -734,8 +735,6 @@ function cleanupModelMenus() { Menu.removeMenuItem("File", "Export Models"); Menu.removeMenuItem("File", "Import Models"); - Menu.removeMenuItem("Tools", "Entity List..."); - Menu.removeMenuItem("View", MENU_INSPECT_TOOL_ENABLED); Menu.removeMenuItem("View", MENU_EASE_ON_FOCUS); } From 1a6557c72d0431fafd2771da2cfd3c35d8b988fd Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 20 Jan 2015 12:46:26 -0800 Subject: [PATCH 24/30] Remove removeEntity from entityList.html --- examples/html/entityList.html | 7 ------- 1 file changed, 7 deletions(-) diff --git a/examples/html/entityList.html b/examples/html/entityList.html index e1318a225c..6e7795a3f0 100644 --- a/examples/html/entityList.html +++ b/examples/html/entityList.html @@ -83,13 +83,6 @@ } } - function removeEntity(id) { - if (entities[id] !== undefined) { - elEntityTableBody.removeChild(entities[id].el); - delete entities[id]; - } - } - function clearEntities() { entities = {}; entityList.clear(); From 1f86edbfbf04621baf7234223a6cc1f1fe6cda59 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Tue, 20 Jan 2015 12:47:19 -0800 Subject: [PATCH 25/30] Remove console.log from entityList.html --- examples/html/entityList.html | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/html/entityList.html b/examples/html/entityList.html index 6e7795a3f0..01061f1eb0 100644 --- a/examples/html/entityList.html +++ b/examples/html/entityList.html @@ -101,7 +101,6 @@ currentSortColumn = column; currentSortOrder = "asc"; } - console.log(currentSortColumn, currentSortOrder); elSortOrder[column].innerHTML = currentSortOrder == "asc" ? ASC_STRING : DESC_STRING; entityList.sort(currentSortColumn, { order: currentSortOrder }); } From b4cd13f0be1917413b69d7fa8d20b76331a3c48d Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 20 Jan 2015 13:07:35 -0800 Subject: [PATCH 26/30] Fix for misaligned color/material textures when resolution is greater than the height map. --- .../shaders/metavoxel_heightfield_base.vert | 2 +- .../shaders/metavoxel_heightfield_splat.vert | 2 +- interface/src/MetavoxelSystem.cpp | 16 ++++++++++++++-- 3 files changed, 16 insertions(+), 4 deletions(-) diff --git a/interface/resources/shaders/metavoxel_heightfield_base.vert b/interface/resources/shaders/metavoxel_heightfield_base.vert index 03a99bd57c..38ec891e5a 100644 --- a/interface/resources/shaders/metavoxel_heightfield_base.vert +++ b/interface/resources/shaders/metavoxel_heightfield_base.vert @@ -43,5 +43,5 @@ void main(void) { gl_FrontColor = vec4(1.0, 1.0, 1.0, step(height, 0.0)); // pass along the scaled/offset texture coordinates - gl_TexCoord[0] = vec4((heightCoord - heightScale.st) * colorScale, 0.0, 1.0); + gl_TexCoord[0] = vec4((heightCoord - vec2(0.5, 0.5)) * colorScale + vec2(0.5, 0.5), 0.0, 1.0); } diff --git a/interface/resources/shaders/metavoxel_heightfield_splat.vert b/interface/resources/shaders/metavoxel_heightfield_splat.vert index d54da347cc..48681ecdd4 100644 --- a/interface/resources/shaders/metavoxel_heightfield_splat.vert +++ b/interface/resources/shaders/metavoxel_heightfield_splat.vert @@ -58,7 +58,7 @@ void main(void) { gl_TexCoord[3] = textureSpacePosition * vec4(splatTextureScalesS[3], splatTextureScalesT[3], 0.0, 1.0); // compute the alpha values for each texture - float value = texture2D(textureMap, (gl_MultiTexCoord0.st - heightScale) * textureScale).r; + float value = texture2D(textureMap, (gl_MultiTexCoord0.st - vec2(0.5, 0.5)) * textureScale + vec2(0.5, 0.5)).r; vec4 valueVector = vec4(value, value, value, value); alphaValues = step(textureValueMinima, valueVector) * step(valueVector, textureValueMaxima); } diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index a566b18b7e..86bdcd8ab9 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -2407,7 +2407,14 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g baseBatch.heightTextureID = _heightTextureID; baseBatch.heightScale = glm::vec4(1.0f / width, 1.0f / height, (innerWidth - 1) / -2.0f, (innerHeight - 1) / -2.0f); baseBatch.colorTextureID = _colorTextureID; - baseBatch.colorScale = glm::vec2((float)width / innerWidth, (float)height / innerHeight); + float widthMultiplier = 1.0f / (0.5f - 1.5f / width); + float heightMultiplier = 1.0f / (0.5f - 1.5f / height); + if (node->getColor()) { + int colorWidth = node->getColor()->getWidth(); + int colorHeight = node->getColor()->getContents().size() / (colorWidth * DataBlock::COLOR_BYTES); + baseBatch.colorScale = glm::vec2((0.5f - 0.5f / colorWidth) * widthMultiplier, + (0.5f - 0.5f / colorHeight) * heightMultiplier); + } Application::getInstance()->getMetavoxels()->addHeightfieldBaseBatch(baseBatch); if (!(cursor || _networkTextures.isEmpty())) { @@ -2422,7 +2429,12 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g splatBatch.heightTextureID = _heightTextureID; splatBatch.heightScale = glm::vec4(1.0f / width, 1.0f / height, 0.0f, 0.0f); splatBatch.materialTextureID = _materialTextureID; - splatBatch.textureScale = glm::vec2((float)width / innerWidth, (float)height / innerHeight); + if (node->getMaterial()) { + int materialWidth = node->getMaterial()->getWidth(); + int materialHeight = node->getMaterial()->getContents().size() / materialWidth; + splatBatch.textureScale = glm::vec2((0.5f - 0.5f / materialWidth) * widthMultiplier, + (0.5f - 0.5f / materialHeight) * heightMultiplier); + } splatBatch.splatTextureOffset = glm::vec2( glm::dot(translation, rotation * glm::vec3(1.0f, 0.0f, 0.0f)) / scale.x, glm::dot(translation, rotation * glm::vec3(0.0f, 0.0f, 1.0f)) / scale.z); From b2079ab84943f7db0afd1690b6678848194c7539 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 20 Jan 2015 14:42:48 -0800 Subject: [PATCH 27/30] Go ahead and generate mipmaps for the terrain color texture. --- interface/src/MetavoxelSystem.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 86bdcd8ab9..7df61c156c 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -1617,7 +1617,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g glGenTextures(1, &_colorTextureID); glBindTexture(GL_TEXTURE_2D, _colorTextureID); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); if (node->getColor()) { @@ -1625,6 +1625,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, node->getColor()->getWidth(), contents.size() / (node->getColor()->getWidth() * DataBlock::COLOR_BYTES), 0, GL_RGB, GL_UNSIGNED_BYTE, contents.constData()); + glGenerateMipmap(GL_TEXTURE_2D); } else { const quint8 WHITE_COLOR[] = { 255, 255, 255 }; From 460a307ebea1a897597145c1fa188b5083d92591 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 20 Jan 2015 18:12:00 -0800 Subject: [PATCH 28/30] Better stitching. --- interface/src/MetavoxelSystem.cpp | 456 +++++++++++++----------------- 1 file changed, 193 insertions(+), 263 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 7df61c156c..b9cce33828 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -1425,8 +1425,18 @@ public: char material; void setColorMaterial(const StackArray::Entry& entry) { color = entry.color; material = entry.material; } + + void mix(const EdgeCrossing& first, const EdgeCrossing& second, float t); }; +void EdgeCrossing::mix(const EdgeCrossing& first, const EdgeCrossing& second, float t) { + point = glm::mix(first.point, second.point, t); + normal = glm::normalize(glm::mix(first.normal, second.normal, t)); + color = qRgb(glm::mix(qRed(first.color), qRed(second.color), t), glm::mix(qGreen(first.color), qGreen(second.color), t), + glm::mix(qBlue(first.color), qBlue(second.color), t)); + material = (t < 0.5f) ? first.material : second.material; +} + const int MAX_NORMALS_PER_VERTEX = 4; class NormalIndex { @@ -1706,7 +1716,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g } const int EDGES_PER_CUBE = 12; - EdgeCrossing crossings[EDGES_PER_CUBE]; + EdgeCrossing crossings[EDGES_PER_CUBE * 2]; // as we scan down the cube generating vertices between grid points, we remember the indices of the last // (element, line, section--x, y, z) so that we can connect generated vertices as quads @@ -1737,13 +1747,6 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g lineSrc[stackWidth].getExtents(minimumY, maximumY); } if (maximumY >= minimumY) { - int position = minimumY; - int count = maximumY - minimumY + 1; - NormalIndex lastIndexY = { { -1, -1, -1, -1 } }; - indicesX.position = position; - indicesX.resize(count); - indicesZ[x].position = position; - indicesZ[x].resize(count); float heightfieldHeight = *heightLineSrc * voxelScale; float nextHeightfieldHeightX = heightLineSrc[1] * voxelScale; float nextHeightfieldHeightZ = heightLineSrc[width] * voxelScale; @@ -1754,6 +1757,8 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g const int LOWER_RIGHT_CORNER = 8; const int NO_CORNERS = 0; const int ALL_CORNERS = UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER | LOWER_LEFT_CORNER | LOWER_RIGHT_CORNER; + const int CORNER_COUNT = 4; + const int NEXT_CORNERS[] = { 1, 3, 0, 2 }; int corners = NO_CORNERS; if (heightfieldHeight != 0.0f) { corners |= UPPER_LEFT_CORNER; @@ -1768,37 +1773,38 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g corners |= LOWER_RIGHT_CORNER; } bool stitchable = x != 0 && z != 0 && !(corners == NO_CORNERS || corners == ALL_CORNERS); - VoxelPoint cornerPoints[4]; + EdgeCrossing cornerCrossings[CORNER_COUNT]; int clampedX = qMax(x - 1, 0), clampedZ = qMax(z - 1, 0); + int cornerMinimumY = INT_MAX, cornerMaximumY = -1; if (stitchable) { - for (unsigned int i = 0; i < sizeof(cornerPoints) / sizeof(cornerPoints[0]); i++) { + for (int i = 0; i < CORNER_COUNT; i++) { if (!(corners & (1 << i))) { continue; } int offsetX = (i & X_MAXIMUM_FLAG) ? 1 : 0; int offsetZ = (i & Y_MAXIMUM_FLAG) ? 1 : 0; const quint16* height = heightLineSrc + offsetZ * width + offsetX; - VoxelPoint& point = cornerPoints[i]; - int clampedOffsetX = clampedX + offsetX, clampedOffsetZ = clampedZ + offsetZ; - point.vertex = glm::vec3(clampedOffsetX, *height * voxelScale, clampedOffsetZ) * step; + float heightValue = *height * voxelScale; + int y = (int)heightValue; + cornerMinimumY = qMin(cornerMinimumY, y); + cornerMaximumY = qMax(cornerMaximumY, y); + EdgeCrossing& crossing = cornerCrossings[i]; + crossing.point = glm::vec3(offsetX, heightValue - y, offsetZ); int left = height[-1]; int right = height[1]; int down = height[-width]; int up = height[width]; - glm::vec3 normal = glm::normalize(glm::vec3((left == 0 || right == 0) ? 0.0f : left - right, + crossing.normal = glm::normalize(glm::vec3((left == 0 || right == 0) ? 0.0f : left - right, 2.0f / voxelScale, (up == 0 || down == 0) ? 0.0f : down - up)); - point.normal[0] = normal.x * numeric_limits::max(); - point.normal[1] = normal.y * numeric_limits::max(); - point.normal[2] = normal.z * numeric_limits::max(); + int clampedOffsetX = clampedX + offsetX, clampedOffsetZ = clampedZ + offsetZ; if (colorSrc) { const uchar* color = colorSrc + ((int)(clampedOffsetZ * colorStepZ) * colorWidth + (int)(clampedOffsetX * colorStepX)) * DataBlock::COLOR_BYTES; - point.color[0] = color[0]; - point.color[1] = color[1]; - point.color[2] = color[2]; - + crossing.color = qRgb(color[0], color[1], color[2]); + } else { - point.color[0] = point.color[1] = point.color[2] = numeric_limits::max(); + crossing.color = qRgb(numeric_limits::max(), numeric_limits::max(), + numeric_limits::max()); } int material = 0; if (materialSrc) { @@ -1813,12 +1819,18 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g material = mapping; } } - point.materials[0] = material; - point.materials[1] = point.materials[2] = point.materials[3] = 0; - point.materialWeights[0] = numeric_limits::max(); - point.materialWeights[1] = point.materialWeights[2] = point.materialWeights[3] = 0; + crossing.material = material; } + minimumY = qMin(minimumY, cornerMinimumY); + maximumY = qMax(maximumY, cornerMaximumY); } + int position = minimumY; + int count = maximumY - minimumY + 1; + NormalIndex lastIndexY = { { -1, -1, -1, -1 } }; + indicesX.position = position; + indicesX.resize(count); + indicesZ[x].position = position; + indicesZ[x].resize(count); for (int y = position, end = position + count; y < end; y++) { const StackArray::Entry& entry = lineSrc->getEntry(y, heightfieldHeight); if (displayHermite && x != 0 && z != 0 && !lineSrc->isEmpty() && y >= lineSrc->getPosition()) { @@ -1876,91 +1888,176 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g if (alphaTotal == 0 || alphaTotal == possibleTotal) { continue; // no corners set/all corners set } + // we first look for crossings with the heightfield corner vertices; these take priority + int crossingCount = 0; + if (y >= cornerMinimumY && y <= cornerMaximumY) { + // first look for set corners, which override any interpolated values + int crossedCorners = NO_CORNERS; + for (int i = 0; i < CORNER_COUNT; i++) { + if (!(corners & (1 << i))) { + continue; + } + int offsetX = (i & X_MAXIMUM_FLAG) ? 1 : 0; + int offsetZ = (i & Y_MAXIMUM_FLAG) ? 1 : 0; + const quint16* height = heightLineSrc + offsetZ * width + offsetX; + float heightValue = *height * voxelScale; + if (heightValue >= y && heightValue < y + 1) { + crossedCorners |= (1 << i); + } + } + switch (crossedCorners) { + case UPPER_LEFT_CORNER: + case LOWER_LEFT_CORNER | UPPER_LEFT_CORNER: + case LOWER_LEFT_CORNER | UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER: + case UPPER_LEFT_CORNER | LOWER_RIGHT_CORNER: + crossings[crossingCount++] = cornerCrossings[0]; + break; + + case UPPER_RIGHT_CORNER: + case UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER: + case UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER: + case UPPER_RIGHT_CORNER | LOWER_LEFT_CORNER: + crossings[crossingCount++] = cornerCrossings[1]; + break; + + case LOWER_LEFT_CORNER: + case LOWER_RIGHT_CORNER | LOWER_LEFT_CORNER: + case LOWER_RIGHT_CORNER | LOWER_LEFT_CORNER | UPPER_LEFT_CORNER: + crossings[crossingCount++] = cornerCrossings[2]; + break; + + case LOWER_RIGHT_CORNER: + case UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER: + case UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER | LOWER_LEFT_CORNER: + crossings[crossingCount++] = cornerCrossings[3]; + break; + + case NO_CORNERS: + for (int i = 0; i < CORNER_COUNT; i++) { + if (!(corners & (1 << i))) { + continue; + } + int offsetX = (i & X_MAXIMUM_FLAG) ? 1 : 0; + int offsetZ = (i & Y_MAXIMUM_FLAG) ? 1 : 0; + const quint16* height = heightLineSrc + offsetZ * width + offsetX; + float heightValue = *height * voxelScale; + if (heightValue >= y && heightValue < y + 1) { + crossings[crossingCount++] = cornerCrossings[i]; + } + int nextIndex = NEXT_CORNERS[i]; + if (!(corners & (1 << nextIndex))) { + continue; + } + int nextOffsetX = (nextIndex & X_MAXIMUM_FLAG) ? 1 : 0; + int nextOffsetZ = (nextIndex & Y_MAXIMUM_FLAG) ? 1 : 0; + const quint16* nextHeight = heightLineSrc + nextOffsetZ * width + nextOffsetX; + float nextHeightValue = *nextHeight * voxelScale; + float divisor = (nextHeightValue - heightValue); + if (divisor == 0.0f) { + continue; + } + float t1 = (y - heightValue) / divisor; + float t2 = (y + 1 - heightValue) / divisor; + if (t1 >= 0.0f && t1 <= 1.0f) { + crossings[crossingCount++].mix(cornerCrossings[i], cornerCrossings[nextIndex], t1); + } + if (t2 >= 0.0f && t2 <= 1.0f) { + crossings[crossingCount++].mix(cornerCrossings[i], cornerCrossings[nextIndex], t2); + } + } + break; + } + } + // the terrifying conditional code that follows checks each cube edge for a crossing, gathering // its properties (color, material, normal) if one is present; as before, boundary edges are excluded - int crossingCount = 0; - const StackArray::Entry& nextEntryY = lineSrc->getEntry(y + 1, heightfieldHeight); - if (middleX) { - const StackArray::Entry& nextEntryX = lineSrc[1].getEntry(y, nextHeightfieldHeightX); - const StackArray::Entry& nextEntryXY = lineSrc[1].getEntry(y + 1, nextHeightfieldHeightX); - if (alpha0 != alpha1) { - EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(entry.getHermiteX(crossing.normal), 0.0f, 0.0f); - crossing.setColorMaterial(alpha0 == 0 ? nextEntryX : entry); + if (crossingCount == 0) { + const StackArray::Entry& nextEntryY = lineSrc->getEntry(y + 1, heightfieldHeight); + if (middleX) { + const StackArray::Entry& nextEntryX = lineSrc[1].getEntry(y, nextHeightfieldHeightX); + const StackArray::Entry& nextEntryXY = lineSrc[1].getEntry(y + 1, nextHeightfieldHeightX); + if (alpha0 != alpha1) { + EdgeCrossing& crossing = crossings[crossingCount++]; + crossing.point = glm::vec3(entry.getHermiteX(crossing.normal), 0.0f, 0.0f); + crossing.setColorMaterial(alpha0 == 0 ? nextEntryX : entry); + } + if (alpha1 != alpha3) { + EdgeCrossing& crossing = crossings[crossingCount++]; + crossing.point = glm::vec3(1.0f, nextEntryX.getHermiteY(crossing.normal), 0.0f); + crossing.setColorMaterial(alpha1 == 0 ? nextEntryXY : nextEntryX); + } + if (alpha2 != alpha3) { + EdgeCrossing& crossing = crossings[crossingCount++]; + crossing.point = glm::vec3(nextEntryY.getHermiteX(crossing.normal), 1.0f, 0.0f); + crossing.setColorMaterial(alpha2 == 0 ? nextEntryXY : nextEntryY); + } + if (middleZ) { + const StackArray::Entry& nextEntryZ = lineSrc[stackWidth].getEntry(y, + nextHeightfieldHeightZ); + const StackArray::Entry& nextEntryXZ = lineSrc[stackWidth + 1].getEntry( + y, nextHeightfieldHeightXZ); + const StackArray::Entry& nextEntryXYZ = lineSrc[stackWidth + 1].getEntry( + y + 1, nextHeightfieldHeightXZ); + if (alpha1 != alpha5) { + EdgeCrossing& crossing = crossings[crossingCount++]; + crossing.point = glm::vec3(1.0f, 0.0f, nextEntryX.getHermiteZ(crossing.normal)); + crossing.setColorMaterial(alpha1 == 0 ? nextEntryXZ : nextEntryX); + } + if (alpha3 != alpha7) { + EdgeCrossing& crossing = crossings[crossingCount++]; + const StackArray::Entry& nextEntryXY = lineSrc[1].getEntry(y + 1, + nextHeightfieldHeightX); + crossing.point = glm::vec3(1.0f, 1.0f, nextEntryXY.getHermiteZ(crossing.normal)); + crossing.setColorMaterial(alpha3 == 0 ? nextEntryXYZ : nextEntryXY); + } + if (alpha4 != alpha5) { + EdgeCrossing& crossing = crossings[crossingCount++]; + crossing.point = glm::vec3(nextEntryZ.getHermiteX(crossing.normal), 0.0f, 1.0f); + crossing.setColorMaterial(alpha4 == 0 ? nextEntryXZ : nextEntryZ); + } + if (alpha5 != alpha7) { + EdgeCrossing& crossing = crossings[crossingCount++]; + const StackArray::Entry& nextEntryXZ = lineSrc[stackWidth + 1].getEntry( + y, nextHeightfieldHeightXZ); + crossing.point = glm::vec3(1.0f, nextEntryXZ.getHermiteY(crossing.normal), 1.0f); + crossing.setColorMaterial(alpha5 == 0 ? nextEntryXYZ : nextEntryXZ); + } + if (alpha6 != alpha7) { + EdgeCrossing& crossing = crossings[crossingCount++]; + const StackArray::Entry& nextEntryYZ = lineSrc[stackWidth].getEntry( + y + 1, nextHeightfieldHeightZ); + crossing.point = glm::vec3(nextEntryYZ.getHermiteX(crossing.normal), 1.0f, 1.0f); + crossing.setColorMaterial(alpha6 == 0 ? nextEntryXYZ : nextEntryYZ); + } + } } - if (alpha1 != alpha3) { + if (alpha0 != alpha2) { EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(1.0f, nextEntryX.getHermiteY(crossing.normal), 0.0f); - crossing.setColorMaterial(alpha1 == 0 ? nextEntryXY : nextEntryX); - } - if (alpha2 != alpha3) { - EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(nextEntryY.getHermiteX(crossing.normal), 1.0f, 0.0f); - crossing.setColorMaterial(alpha2 == 0 ? nextEntryXY : nextEntryY); + crossing.point = glm::vec3(0.0f, entry.getHermiteY(crossing.normal), 0.0f); + crossing.setColorMaterial(alpha0 == 0 ? nextEntryY : entry); } if (middleZ) { const StackArray::Entry& nextEntryZ = lineSrc[stackWidth].getEntry(y, nextHeightfieldHeightZ); - const StackArray::Entry& nextEntryXZ = lineSrc[stackWidth + 1].getEntry( - y, nextHeightfieldHeightXZ); - const StackArray::Entry& nextEntryXYZ = lineSrc[stackWidth + 1].getEntry( - y + 1, nextHeightfieldHeightXZ); - if (alpha1 != alpha5) { + const StackArray::Entry& nextEntryYZ = lineSrc[stackWidth].getEntry(y + 1, + nextHeightfieldHeightZ); + if (alpha0 != alpha4) { EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(1.0f, 0.0f, nextEntryX.getHermiteZ(crossing.normal)); - crossing.setColorMaterial(alpha1 == 0 ? nextEntryXZ : nextEntryX); + crossing.point = glm::vec3(0.0f, 0.0f, entry.getHermiteZ(crossing.normal)); + crossing.setColorMaterial(alpha0 == 0 ? nextEntryZ : entry); } - if (alpha3 != alpha7) { + if (alpha2 != alpha6) { EdgeCrossing& crossing = crossings[crossingCount++]; - const StackArray::Entry& nextEntryXY = lineSrc[1].getEntry(y + 1, nextHeightfieldHeightX); - crossing.point = glm::vec3(1.0f, 1.0f, nextEntryXY.getHermiteZ(crossing.normal)); - crossing.setColorMaterial(alpha3 == 0 ? nextEntryXYZ : nextEntryXY); + crossing.point = glm::vec3(0.0f, 1.0f, nextEntryY.getHermiteZ(crossing.normal)); + crossing.setColorMaterial(alpha2 == 0 ? nextEntryYZ : nextEntryY); } - if (alpha4 != alpha5) { + if (alpha4 != alpha6) { EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(nextEntryZ.getHermiteX(crossing.normal), 0.0f, 1.0f); - crossing.setColorMaterial(alpha4 == 0 ? nextEntryXZ : nextEntryZ); - } - if (alpha5 != alpha7) { - EdgeCrossing& crossing = crossings[crossingCount++]; - const StackArray::Entry& nextEntryXZ = lineSrc[stackWidth + 1].getEntry( - y, nextHeightfieldHeightXZ); - crossing.point = glm::vec3(1.0f, nextEntryXZ.getHermiteY(crossing.normal), 1.0f); - crossing.setColorMaterial(alpha5 == 0 ? nextEntryXYZ : nextEntryXZ); - } - if (alpha6 != alpha7) { - EdgeCrossing& crossing = crossings[crossingCount++]; - const StackArray::Entry& nextEntryYZ = lineSrc[stackWidth].getEntry( - y + 1, nextHeightfieldHeightZ); - crossing.point = glm::vec3(nextEntryYZ.getHermiteX(crossing.normal), 1.0f, 1.0f); - crossing.setColorMaterial(alpha6 == 0 ? nextEntryXYZ : nextEntryYZ); + crossing.point = glm::vec3(0.0f, nextEntryZ.getHermiteY(crossing.normal), 1.0f); + crossing.setColorMaterial(alpha4 == 0 ? nextEntryYZ : nextEntryZ); } } } - if (alpha0 != alpha2) { - EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(0.0f, entry.getHermiteY(crossing.normal), 0.0f); - crossing.setColorMaterial(alpha0 == 0 ? nextEntryY : entry); - } - if (middleZ) { - const StackArray::Entry& nextEntryZ = lineSrc[stackWidth].getEntry(y, nextHeightfieldHeightZ); - const StackArray::Entry& nextEntryYZ = lineSrc[stackWidth].getEntry(y + 1, nextHeightfieldHeightZ); - if (alpha0 != alpha4) { - EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(0.0f, 0.0f, entry.getHermiteZ(crossing.normal)); - crossing.setColorMaterial(alpha0 == 0 ? nextEntryZ : entry); - } - if (alpha2 != alpha6) { - EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(0.0f, 1.0f, nextEntryY.getHermiteZ(crossing.normal)); - crossing.setColorMaterial(alpha2 == 0 ? nextEntryYZ : nextEntryY); - } - if (alpha4 != alpha6) { - EdgeCrossing& crossing = crossings[crossingCount++]; - crossing.point = glm::vec3(0.0f, nextEntryZ.getHermiteY(crossing.normal), 1.0f); - crossing.setColorMaterial(alpha4 == 0 ? nextEntryYZ : nextEntryZ); - } - } - // determine whether we should ignore this vertex because it will be stitched + // make sure we have valid crossings to include int validCrossings = 0; for (int i = 0; i < crossingCount; i++) { if (qAlpha(crossings[i].color) != 0) { @@ -2108,173 +2205,6 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g point.setNormal(normals[i]); vertices.append(point); } - - if (stitchable) { - int nextIndex = vertices.size(); - const NormalIndex& previousIndexX = lastIndicesX.getClosest(y); - const NormalIndex& previousIndexZ = lastIndicesZ[x].getClosest(y); - switch (corners) { - case UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER: { - vertices.append(cornerPoints[0]); - vertices.append(cornerPoints[3]); - glm::vec3 normal = glm::cross(cornerPoints[0].vertex - cornerPoints[1].vertex, - cornerPoints[3].vertex - cornerPoints[1].vertex); - int firstIndex = index.getClosestIndex(normal, vertices); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex + 1, nextIndex, nextIndex); - if (previousIndexX.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - nextIndex, previousIndexX.getClosestIndex(normal, vertices)); - } - break; - } - case UPPER_LEFT_CORNER | LOWER_LEFT_CORNER | LOWER_RIGHT_CORNER: { - vertices.append(cornerPoints[0]); - vertices.append(cornerPoints[3]); - glm::vec3 normal = glm::cross(cornerPoints[3].vertex - cornerPoints[2].vertex, - cornerPoints[0].vertex - cornerPoints[2].vertex); - int firstIndex = index.getClosestIndex(normal, vertices); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex, nextIndex + 1, nextIndex + 1); - if (previousIndexZ.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - previousIndexZ.getClosestIndex(normal, vertices), nextIndex); - } - break; - } - case UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER | LOWER_LEFT_CORNER: { - vertices.append(cornerPoints[1]); - vertices.append(cornerPoints[2]); - vertices.append(cornerPoints[3]); - glm::vec3 normal = glm::cross(cornerPoints[3].vertex - cornerPoints[2].vertex, - cornerPoints[1].vertex - cornerPoints[2].vertex); - int firstIndex = index.getClosestIndex(normal, vertices); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex + 2, nextIndex, nextIndex); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex + 1, nextIndex + 2, nextIndex + 2); - if (previousIndexX.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - previousIndexX.getClosestIndex(normal, vertices), nextIndex + 1); - } - if (previousIndexZ.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - nextIndex, previousIndexZ.getClosestIndex(normal, vertices)); - } - break; - } - case UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER | LOWER_LEFT_CORNER: { - vertices.append(cornerPoints[0]); - vertices.append(cornerPoints[1]); - vertices.append(cornerPoints[2]); - glm::vec3 normal = glm::cross(cornerPoints[2].vertex - cornerPoints[0].vertex, - cornerPoints[1].vertex - cornerPoints[0].vertex); - int firstIndex = index.getClosestIndex(normal, vertices); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex + 1, nextIndex, nextIndex); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex, nextIndex + 2, nextIndex + 2); - break; - } - case UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER: { - vertices.append(cornerPoints[0]); - vertices.append(cornerPoints[1]); - const glm::vec3& first = vertices.at(index.indices[0]).vertex; - glm::vec3 normal = glm::cross(cornerPoints[1].vertex - first, - cornerPoints[0].vertex - first); - int firstIndex = index.getClosestIndex(normal, vertices); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex + 1, nextIndex, nextIndex); - if (previousIndexX.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - nextIndex, previousIndexX.getClosestIndex(normal, vertices)); - } - break; - } - case UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER: { - vertices.append(cornerPoints[1]); - vertices.append(cornerPoints[3]); - const glm::vec3& first = vertices.at(index.indices[0]).vertex; - glm::vec3 normal = glm::cross(cornerPoints[3].vertex - first, - cornerPoints[1].vertex - first); - int firstIndex = index.getClosestIndex(normal, vertices); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex + 1, nextIndex, nextIndex); - if (previousIndexZ.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, - firstIndex, nextIndex, previousIndexZ.getClosestIndex(normal, vertices)); - } - break; - } - case LOWER_RIGHT_CORNER | LOWER_LEFT_CORNER: { - vertices.append(cornerPoints[3]); - vertices.append(cornerPoints[2]); - const glm::vec3& first = vertices.at(index.indices[0]).vertex; - glm::vec3 normal = glm::cross(cornerPoints[2].vertex - first, - cornerPoints[3].vertex - first); - int firstIndex = index.getClosestIndex(normal, vertices); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex + 1, nextIndex, nextIndex); - if (previousIndexX.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - previousIndexX.getClosestIndex(normal, vertices), nextIndex + 1); - } - break; - } - case LOWER_LEFT_CORNER | UPPER_LEFT_CORNER: { - vertices.append(cornerPoints[2]); - vertices.append(cornerPoints[0]); - const glm::vec3& first = vertices.at(index.indices[0]).vertex; - glm::vec3 normal = glm::cross(cornerPoints[0].vertex - first, - cornerPoints[2].vertex - first); - int firstIndex = index.getClosestIndex(normal, vertices); - appendIndices(indices, quadIndices, vertices, step, firstIndex, - nextIndex + 1, nextIndex, nextIndex); - if (previousIndexZ.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - previousIndexZ.getClosestIndex(normal, vertices), nextIndex + 1); - } - break; - } - case UPPER_LEFT_CORNER: { - vertices.append(cornerPoints[0]); - glm::vec3 normal = glm::cross(cornerPoints[0].vertex - - vertices.at(index.indices[0]).vertex, glm::vec3(1.0f, 0.0f, 0.0f)); - int firstIndex = index.getClosestIndex(normal, vertices); - if (previousIndexX.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - nextIndex, previousIndexX.getClosestIndex(normal, vertices)); - } - if (previousIndexZ.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - previousIndexZ.getClosestIndex(normal, vertices), nextIndex); - } - break; - } - case UPPER_RIGHT_CORNER: { - vertices.append(cornerPoints[1]); - glm::vec3 normal = glm::cross(cornerPoints[1].vertex - - vertices.at(index.indices[0]).vertex, glm::vec3(1.0f, 0.0f, 0.0f)); - int firstIndex = index.getClosestIndex(normal, vertices); - if (previousIndexZ.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - nextIndex, previousIndexZ.getClosestIndex(normal, vertices)); - } - break; - } - case LOWER_LEFT_CORNER: { - vertices.append(cornerPoints[2]); - glm::vec3 normal = glm::cross(cornerPoints[2].vertex - - vertices.at(index.indices[0]).vertex, glm::vec3(1.0f, 0.0f, 0.0f)); - int firstIndex = index.getClosestIndex(normal, vertices); - if (previousIndexX.isValid()) { - appendIndices(indices, quadIndices, vertices, step, firstIndex, firstIndex, - previousIndexX.getClosestIndex(normal, vertices), nextIndex); - } - break; - } - } - } } // the first x, y, and z are repeated for the boundary edge; past that, we consider generating From 79e18b161d823ebe9f13247310eef2f0cd8c0f5e Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 20 Jan 2015 18:42:40 -0800 Subject: [PATCH 29/30] Simplification. --- interface/src/MetavoxelSystem.cpp | 54 ------------------------------- 1 file changed, 54 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index b9cce33828..dd67f27d79 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -1490,7 +1490,6 @@ public: void swap(IndexVector& other) { QVector::swap(other); qSwap(position, other.position); } const NormalIndex& get(int y) const; - const NormalIndex& getClosest(int y) const; }; const NormalIndex& IndexVector::get(int y) const { @@ -1499,56 +1498,6 @@ const NormalIndex& IndexVector::get(int y) const { return (relative >= 0 && relative < size()) ? at(relative) : invalidIndex; } -const NormalIndex& IndexVector::getClosest(int y) const { - static NormalIndex invalidIndex = { { -1, -1, -1, -1 } }; - int relative = y - position; - if (relative < 0 || relative >= size()) { - return invalidIndex; - } - const NormalIndex& first = at(relative); - if (first.isValid()) { - return first; - } - for (int distance = 1; relative - distance >= 0 || relative + distance < size(); distance++) { - int previous = relative - distance; - if (previous >= 0) { - const NormalIndex& previousIndex = at(previous); - if (previousIndex.isValid()) { - return previousIndex; - } - } - int next = relative + distance; - if (next < size()) { - const NormalIndex& nextIndex = at(next); - if (nextIndex.isValid()) { - return nextIndex; - } - } - } - return invalidIndex; -} - -static inline void appendIndices(QVector& indices, QMultiHash& quadIndices, - const QVector& vertices, float step, int i0, int i1, int i2, int i3) { - int newIndices[] = { i0, i1, i2, i3 }; - glm::vec3 minima(FLT_MAX, FLT_MAX, FLT_MAX), maxima(-FLT_MAX, -FLT_MAX, -FLT_MAX); - int indexIndex = indices.size(); - for (unsigned int i = 0; i < sizeof(newIndices) / sizeof(newIndices[0]); i++) { - int index = newIndices[i]; - indices.append(index); - const glm::vec3& vertex = vertices.at(index).vertex; - minima = glm::min(vertex, minima); - maxima = glm::max(vertex, maxima); - } - for (int z = (int)minima.z, endZ = (int)glm::ceil(maxima.z); z < endZ; z++) { - for (int y = (int)minima.x, endY = (int)glm::ceil(maxima.y); y < endY; y++) { - for (int x = (int)minima.x, endX = (int)glm::ceil(maxima.x); x < endX; x++) { - quadIndices.insert(qRgb(x, y, z), indexIndex); - } - } - } -} - void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const glm::vec3& translation, const glm::quat& rotation, const glm::vec3& scale, bool cursor) { if (!node->getHeight()) { @@ -1941,9 +1890,6 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g int offsetZ = (i & Y_MAXIMUM_FLAG) ? 1 : 0; const quint16* height = heightLineSrc + offsetZ * width + offsetX; float heightValue = *height * voxelScale; - if (heightValue >= y && heightValue < y + 1) { - crossings[crossingCount++] = cornerCrossings[i]; - } int nextIndex = NEXT_CORNERS[i]; if (!(corners & (1 << nextIndex))) { continue; From 10c4408d94edf009b2766f31162f12f4d04668d0 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Tue, 20 Jan 2015 21:52:56 -0800 Subject: [PATCH 30/30] Slight stitching tweak. --- interface/src/MetavoxelSystem.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index dd67f27d79..eeb1c84a4e 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -1738,7 +1738,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g cornerMinimumY = qMin(cornerMinimumY, y); cornerMaximumY = qMax(cornerMaximumY, y); EdgeCrossing& crossing = cornerCrossings[i]; - crossing.point = glm::vec3(offsetX, heightValue - y, offsetZ); + crossing.point = glm::vec3(offsetX, heightValue, offsetZ); int left = height[-1]; int right = height[1]; int down = height[-width]; @@ -1860,6 +1860,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g case LOWER_LEFT_CORNER | UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER: case UPPER_LEFT_CORNER | LOWER_RIGHT_CORNER: crossings[crossingCount++] = cornerCrossings[0]; + crossings[crossingCount - 1].point.y -= y; break; case UPPER_RIGHT_CORNER: @@ -1867,18 +1868,21 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g case UPPER_LEFT_CORNER | UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER: case UPPER_RIGHT_CORNER | LOWER_LEFT_CORNER: crossings[crossingCount++] = cornerCrossings[1]; + crossings[crossingCount - 1].point.y -= y; break; case LOWER_LEFT_CORNER: case LOWER_RIGHT_CORNER | LOWER_LEFT_CORNER: case LOWER_RIGHT_CORNER | LOWER_LEFT_CORNER | UPPER_LEFT_CORNER: crossings[crossingCount++] = cornerCrossings[2]; + crossings[crossingCount - 1].point.y -= y; break; case LOWER_RIGHT_CORNER: case UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER: case UPPER_RIGHT_CORNER | LOWER_RIGHT_CORNER | LOWER_LEFT_CORNER: crossings[crossingCount++] = cornerCrossings[3]; + crossings[crossingCount - 1].point.y -= y; break; case NO_CORNERS: @@ -1906,9 +1910,11 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g float t2 = (y + 1 - heightValue) / divisor; if (t1 >= 0.0f && t1 <= 1.0f) { crossings[crossingCount++].mix(cornerCrossings[i], cornerCrossings[nextIndex], t1); + crossings[crossingCount - 1].point.y -= y; } if (t2 >= 0.0f && t2 <= 1.0f) { crossings[crossingCount++].mix(cornerCrossings[i], cornerCrossings[nextIndex], t2); + crossings[crossingCount - 1].point.y -= y; } } break;