file_path
stringlengths
11
219
num_changed_lines
int64
0
58.4k
code
stringlengths
0
3.52M
repo_name
stringclasses
25 values
commit_date
stringclasses
5 values
sha
stringclasses
25 values
dist/vue.min.js
5
/*! * Vue.js v2.1.10 * (c) 2014-2017 Evan You * Released under the MIT License. */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Vue=t()}(this,function(){"use strict";function e(e){return null==e?"":"object"==typeof e?JSON.stringify(e,null,2):String(e)}function t(e){var t=parseFloat(e);return isNaN(t)?e:t}function n(e,t){for(var n=Object.create(null),r=e.split(","),i=0;i<r.length;i++)n[r[i]]=!0;return t?function(e){return n[e.toLowerCase()]}:function(e){return n[e]}}function r(e,t){if(e.length){var n=e.indexOf(t);if(n>-1)return e.splice(n,1)}}function i(e,t){return ii.call(e,t)}function o(e){return"string"==typeof e||"number"==typeof e}function a(e){var t=Object.create(null);return function(n){var r=t[n];return r||(t[n]=e(n))}}function s(e,t){function n(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}return n._length=e.length,n}function c(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function u(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return null!==e&&"object"==typeof e}function f(e){return li.call(e)===fi}function p(e){for(var t={},n=0;n<e.length;n++)e[n]&&u(t,e[n]);return t}function d(){}function v(e){return e.reduce(function(e,t){return e.concat(t.staticKeys||[])},[]).join(",")}function h(e,t){var n=l(e),r=l(t);return n&&r?JSON.stringify(e)===JSON.stringify(t):!n&&!r&&String(e)===String(t)}function m(e,t){for(var n=0;n<e.length;n++)if(h(e[n],t))return n;return-1}function g(e){var t=(e+"").charCodeAt(0);return 36===t||95===t}function y(e,t,n,r){Object.defineProperty(e,t,{value:n,enumerable:!!r,writable:!0,configurable:!0})}function _(e){if(!hi.test(e)){var t=e.split(".");return function(e){for(var n=0;n<t.length;n++){if(!e)return;e=e[t[n]]}return e}}}function b(e){return/native code/.test(e.toString())}function $(e){Ei.target&&Ii.push(Ei.target),Ei.target=e}function w(){Ei.target=Ii.pop()}function C(e,t){e.__proto__=t}function x(e,t,n){for(var r=0,i=n.length;r<i;r++){var o=n[r];y(e,o,t[o])}}function k(e,t){if(l(e)){var n;return i(e,"__ob__")&&e.__ob__ instanceof Di?n=e.__ob__:Mi.shouldConvert&&!xi()&&(Array.isArray(e)||f(e))&&Object.isExtensible(e)&&!e._isVue&&(n=new Di(e)),t&&n&&n.vmCount++,n}}function A(e,t,n,r){var i=new Ei,o=Object.getOwnPropertyDescriptor(e,t);if(!o||o.configurable!==!1){var a=o&&o.get,s=o&&o.set,c=k(n);Object.defineProperty(e,t,{enumerable:!0,configurable:!0,get:function(){var t=a?a.call(e):n;return Ei.target&&(i.depend(),c&&c.dep.depend(),Array.isArray(t)&&T(t)),t},set:function(t){var r=a?a.call(e):n;t===r||t!==t&&r!==r||(s?s.call(e,t):n=t,c=k(t),i.notify())}})}}function O(e,t,n){if(Array.isArray(e))return e.length=Math.max(e.length,t),e.splice(t,1,n),n;if(i(e,t))return void(e[t]=n);var r=e.__ob__;if(!(e._isVue||r&&r.vmCount))return r?(A(r.value,t,n),r.dep.notify(),n):void(e[t]=n)}function S(e,t){var n=e.__ob__;e._isVue||n&&n.vmCount||i(e,t)&&(delete e[t],n&&n.dep.notify())}function T(e){for(var t=void 0,n=0,r=e.length;n<r;n++)t=e[n],t&&t.__ob__&&t.__ob__.dep.depend(),Array.isArray(t)&&T(t)}function E(e,t){if(!t)return e;for(var n,r,o,a=Object.keys(t),s=0;s<a.length;s++)n=a[s],r=e[n],o=t[n],i(e,n)?f(r)&&f(o)&&E(r,o):O(e,n,o);return e}function I(e,t){return t?e?e.concat(t):Array.isArray(t)?t:[t]:e}function j(e,t){var n=Object.create(e||null);return t?u(n,t):n}function N(e){var t=e.props;if(t){var n,r,i,o={};if(Array.isArray(t))for(n=t.length;n--;)r=t[n],"string"==typeof r&&(i=ai(r),o[i]={type:null});else if(f(t))for(var a in t)r=t[a],i=ai(a),o[i]=f(r)?r:{type:r};e.props=o}}function L(e){var t=e.directives;if(t)for(var n in t){var r=t[n];"function"==typeof r&&(t[n]={bind:r,update:r})}}function M(e,t,n){function r(r){var i=Pi[r]||Ri;l[r]=i(e[r],t[r],n,r)}N(t),L(t);var o=t.extends;if(o&&(e="function"==typeof o?M(e,o.options,n):M(e,o,n)),t.mixins)for(var a=0,s=t.mixins.length;a<s;a++){var c=t.mixins[a];c.prototype instanceof Ue&&(c=c.options),e=M(e,c,n)}var u,l={};for(u in e)r(u);for(u in t)i(e,u)||r(u);return l}function D(e,t,n,r){if("string"==typeof n){var o=e[t];if(i(o,n))return o[n];var a=ai(n);if(i(o,a))return o[a];var s=si(a);if(i(o,s))return o[s];var c=o[n]||o[a]||o[s];return c}}function P(e,t,n,r){var o=t[e],a=!i(n,e),s=n[e];if(H(Boolean,o.type)&&(a&&!i(o,"default")?s=!1:H(String,o.type)||""!==s&&s!==ui(e)||(s=!0)),void 0===s){s=R(r,o,e);var c=Mi.shouldConvert;Mi.shouldConvert=!0,k(s),Mi.shouldConvert=c}return s}function R(e,t,n){if(i(t,"default")){var r=t.default;return l(r),e&&e.$options.propsData&&void 0===e.$options.propsData[n]&&void 0!==e[n]?e[n]:"function"==typeof r&&t.type!==Function?r.call(e):r}}function F(e){var t=e&&e.toString().match(/^\s*function (\w+)/);return t&&t[1]}function H(e,t){if(!Array.isArray(t))return F(t)===F(e);for(var n=0,r=t.length;n<r;n++)if(F(t[n])===F(e))return!0;return!1}function U(e){return new Hi(void 0,void 0,void 0,String(e))}function B(e){var t=new Hi(e.tag,e.data,e.children,e.text,e.elm,e.context,e.componentOptions);return t.ns=e.ns,t.isStatic=e.isStatic,t.key=e.key,t.isCloned=!0,t}function z(e){for(var t=new Array(e.length),n=0;n<e.length;n++)t[n]=B(e[n]);return t}function V(e,t,n,r,i){if(e){var o=n.$options._base;if(l(e)&&(e=o.extend(e)),"function"==typeof e){if(!e.cid)if(e.resolved)e=e.resolved;else if(e=Y(e,o,function(){n.$forceUpdate()}),!e)return;He(e),t=t||{};var a=Q(t,e);if(e.options.functional)return J(e,a,t,n,r);var s=t.on;t.on=t.nativeOn,e.options.abstract&&(t={}),ee(t);var c=e.options.name||i,u=new Hi("vue-component-"+e.cid+(c?"-"+c:""),t,void 0,void 0,void 0,n,{Ctor:e,propsData:a,listeners:s,tag:i,children:r});return u}}}function J(e,t,n,r,i){var o={},a=e.options.props;if(a)for(var s in a)o[s]=P(s,a,t);var c=Object.create(r),u=function(e,t,n,r){return ue(c,e,t,n,r,!0)},l=e.options.render.call(null,u,{props:o,data:n,parent:r,children:i,slots:function(){return ve(i,r)}});return l instanceof Hi&&(l.functionalContext=r,n.slot&&((l.data||(l.data={})).slot=n.slot)),l}function K(e,t,n,r){var i=e.componentOptions,o={_isComponent:!0,parent:t,propsData:i.propsData,_componentTag:i.tag,_parentVnode:e,_parentListeners:i.listeners,_renderChildren:i.children,_parentElm:n||null,_refElm:r||null},a=e.data.inlineTemplate;return a&&(o.render=a.render,o.staticRenderFns=a.staticRenderFns),new i.Ctor(o)}function q(e,t,n,r){if(!e.componentInstance||e.componentInstance._isDestroyed){var i=e.componentInstance=K(e,Zi,n,r);i.$mount(t?e.elm:void 0,t)}else if(e.data.keepAlive){var o=e;W(o,o)}}function W(e,t){var n=t.componentOptions,r=t.componentInstance=e.componentInstance;r._updateFromParent(n.propsData,n.listeners,t,n.children)}function Z(e){e.componentInstance._isMounted||(e.componentInstance._isMounted=!0,we(e.componentInstance,"mounted")),e.data.keepAlive&&(e.componentInstance._inactive=!1,we(e.componentInstance,"activated"))}function G(e){e.componentInstance._isDestroyed||(e.data.keepAlive?(e.componentInstance._inactive=!0,we(e.componentInstance,"deactivated")):e.componentInstance.$destroy())}function Y(e,t,n){if(!e.requested){e.requested=!0;var r=e.pendingCallbacks=[n],i=!0,o=function(n){if(l(n)&&(n=t.extend(n)),e.resolved=n,!i)for(var o=0,a=r.length;o<a;o++)r[o](n)},a=function(e){},s=e(o,a);return s&&"function"==typeof s.then&&!e.resolved&&s.then(o,a),i=!1,e.resolved}e.pendingCallbacks.push(n)}function Q(e,t){var n=t.options.props;if(n){var r={},i=e.attrs,o=e.props,a=e.domProps;if(i||o||a)for(var s in n){var c=ui(s);X(r,o,s,c,!0)||X(r,i,s,c)||X(r,a,s,c)}return r}}function X(e,t,n,r,o){if(t){if(i(t,n))return e[n]=t[n],o||delete t[n],!0;if(i(t,r))return e[n]=t[r],o||delete t[r],!0}return!1}function ee(e){e.hook||(e.hook={});for(var t=0;t<Ji.length;t++){var n=Ji[t],r=e.hook[n],i=Vi[n];e.hook[n]=r?te(i,r):i}}function te(e,t){return function(n,r,i,o){e(n,r,i,o),t(n,r,i,o)}}function ne(e,t,n,r){r+=t;var i=e.__injected||(e.__injected={});if(!i[r]){i[r]=!0;var o=e[t];o?e[t]=function(){o.apply(this,arguments),n.apply(this,arguments)}:e[t]=n}}function re(e){var t={fn:e,invoker:function(){var e=arguments,n=t.fn;if(Array.isArray(n))for(var r=0;r<n.length;r++)n[r].apply(null,e);else n.apply(null,arguments)}};return t}function ie(e,t,n,r,i){var o,a,s,c;for(o in e)a=e[o],s=t[o],c=Ki(o),a&&(s?a!==s&&(s.fn=a,e[o]=s):(a.invoker||(a=e[o]=re(a)),n(c.name,a.invoker,c.once,c.capture)));for(o in t)e[o]||(c=Ki(o),r(c.name,t[o].invoker,c.capture))}function oe(e){for(var t=0;t<e.length;t++)if(Array.isArray(e[t]))return Array.prototype.concat.apply([],e);return e}function ae(e){return o(e)?[U(e)]:Array.isArray(e)?se(e):void 0}function se(e,t){var n,r,i,a=[];for(n=0;n<e.length;n++)r=e[n],null!=r&&"boolean"!=typeof r&&(i=a[a.length-1],Array.isArray(r)?a.push.apply(a,se(r,(t||"")+"_"+n)):o(r)?i&&i.text?i.text+=String(r):""!==r&&a.push(U(r)):r.text&&i&&i.text?a[a.length-1]=U(i.text+r.text):(r.tag&&null==r.key&&null!=t&&(r.key="__vlist"+t+"_"+n+"__"),a.push(r)));return a}function ce(e){return e&&e.filter(function(e){return e&&e.componentOptions})[0]}function ue(e,t,n,r,i,a){return(Array.isArray(n)||o(n))&&(i=r,r=n,n=void 0),a&&(i=Wi),le(e,t,n,r,i)}function le(e,t,n,r,i){if(n&&n.__ob__)return zi();if(!t)return zi();Array.isArray(r)&&"function"==typeof r[0]&&(n=n||{},n.scopedSlots={default:r[0]},r.length=0),i===Wi?r=ae(r):i===qi&&(r=oe(r));var o,a;if("string"==typeof t){var s;a=vi.getTagNamespace(t),o=vi.isReservedTag(t)?new Hi(vi.parsePlatformTagName(t),n,r,void 0,void 0,e):(s=D(e.$options,"components",t))?V(s,n,e,r,t):new Hi(t,n,r,void 0,void 0,e)}else o=V(t,n,e,r);return o?(a&&fe(o,a),o):zi()}function fe(e,t){if(e.ns=t,"foreignObject"!==e.tag&&e.children)for(var n=0,r=e.children.length;n<r;n++){var i=e.children[n];i.tag&&!i.ns&&fe(i,t)}}function pe(e){e.$vnode=null,e._vnode=null,e._staticTrees=null;var t=e.$options._parentVnode,n=t&&t.context;e.$slots=ve(e.$options._renderChildren,n),e.$scopedSlots={},e._c=function(t,n,r,i){return ue(e,t,n,r,i,!1)},e.$createElement=function(t,n,r,i){return ue(e,t,n,r,i,!0)}}function de(n){function r(e,t,n){if(Array.isArray(e))for(var r=0;r<e.length;r++)e[r]&&"string"!=typeof e[r]&&i(e[r],t+"_"+r,n);else i(e,t,n)}function i(e,t,n){e.isStatic=!0,e.key=t,e.isOnce=n}n.prototype.$nextTick=function(e){return Ai(e,this)},n.prototype._render=function(){var e=this,t=e.$options,n=t.render,r=t.staticRenderFns,i=t._parentVnode;if(e._isMounted)for(var o in e.$slots)e.$slots[o]=z(e.$slots[o]);i&&i.data.scopedSlots&&(e.$scopedSlots=i.data.scopedSlots),r&&!e._staticTrees&&(e._staticTrees=[]),e.$vnode=i;var a;try{a=n.call(e._renderProxy,e.$createElement)}catch(t){if(!vi.errorHandler)throw t;vi.errorHandler.call(null,t,e),a=e._vnode}return a instanceof Hi||(a=zi()),a.parent=i,a},n.prototype._s=e,n.prototype._v=U,n.prototype._n=t,n.prototype._e=zi,n.prototype._q=h,n.prototype._i=m,n.prototype._m=function(e,t){var n=this._staticTrees[e];return n&&!t?Array.isArray(n)?z(n):B(n):(n=this._staticTrees[e]=this.$options.staticRenderFns[e].call(this._renderProxy),r(n,"__static__"+e,!1),n)},n.prototype._o=function(e,t,n){return r(e,"__once__"+t+(n?"_"+n:""),!0),e},n.prototype._f=function(e){return D(this.$options,"filters",e,!0)||di},n.prototype._l=function(e,t){var n,r,i,o,a;if(Array.isArray(e)||"string"==typeof e)for(n=new Array(e.length),r=0,i=e.length;r<i;r++)n[r]=t(e[r],r);else if("number"==typeof e)for(n=new Array(e),r=0;r<e;r++)n[r]=t(r+1,r);else if(l(e))for(o=Object.keys(e),n=new Array(o.length),r=0,i=o.length;r<i;r++)a=o[r],n[r]=t(e[a],a,r);return n},n.prototype._t=function(e,t,n,r){var i=this.$scopedSlots[e];if(i)return n=n||{},r&&u(n,r),i(n)||t;var o=this.$slots[e];return o||t},n.prototype._b=function(e,t,n,r){if(n)if(l(n)){Array.isArray(n)&&(n=p(n));for(var i in n)if("class"===i||"style"===i)e[i]=n[i];else{var o=e.attrs&&e.attrs.type,a=r||vi.mustUseProp(t,o,i)?e.domProps||(e.domProps={}):e.attrs||(e.attrs={});a[i]=n[i]}}else;return e},n.prototype._k=function(e,t,n){var r=vi.keyCodes[t]||n;return Array.isArray(r)?r.indexOf(e)===-1:r!==e}}function ve(e,t){var n={};if(!e)return n;for(var r,i,o=[],a=0,s=e.length;a<s;a++)if(i=e[a],(i.context===t||i.functionalContext===t)&&i.data&&(r=i.data.slot)){var c=n[r]||(n[r]=[]);"template"===i.tag?c.push.apply(c,i.children):c.push(i)}else o.push(i);return o.length&&(1!==o.length||" "!==o[0].text&&!o[0].isComment)&&(n.default=o),n}function he(e){e._events=Object.create(null),e._hasHookEvent=!1;var t=e.$options._parentListeners;t&&ye(e,t)}function me(e,t,n){n?Bi.$once(e,t):Bi.$on(e,t)}function ge(e,t){Bi.$off(e,t)}function ye(e,t,n){Bi=e,ie(t,n||{},me,ge,e)}function _e(e){var t=/^hook:/;e.prototype.$on=function(e,n){var r=this;return(r._events[e]||(r._events[e]=[])).push(n),t.test(e)&&(r._hasHookEvent=!0),r},e.prototype.$once=function(e,t){function n(){r.$off(e,n),t.apply(r,arguments)}var r=this;return n.fn=t,r.$on(e,n),r},e.prototype.$off=function(e,t){var n=this;if(!arguments.length)return n._events=Object.create(null),n;var r=n._events[e];if(!r)return n;if(1===arguments.length)return n._events[e]=null,n;for(var i,o=r.length;o--;)if(i=r[o],i===t||i.fn===t){r.splice(o,1);break}return n},e.prototype.$emit=function(e){var t=this,n=t._events[e];if(n){n=n.length>1?c(n):n;for(var r=c(arguments,1),i=0,o=n.length;i<o;i++)n[i].apply(t,r)}return t}}function be(e){var t=e.$options,n=t.parent;if(n&&!t.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(e)}e.$parent=n,e.$root=n?n.$root:e,e.$children=[],e.$refs={},e._watcher=null,e._inactive=!1,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1}function $e(e){e.prototype._mount=function(e,t){var n=this;return n.$el=e,n.$options.render||(n.$options.render=zi),we(n,"beforeMount"),n._watcher=new no(n,function(){n._update(n._render(),t)},d),t=!1,null==n.$vnode&&(n._isMounted=!0,we(n,"mounted")),n},e.prototype._update=function(e,t){var n=this;n._isMounted&&we(n,"beforeUpdate");var r=n.$el,i=n._vnode,o=Zi;Zi=n,n._vnode=e,i?n.$el=n.__patch__(i,e):n.$el=n.__patch__(n.$el,e,t,!1,n.$options._parentElm,n.$options._refElm),Zi=o,r&&(r.__vue__=null),n.$el&&(n.$el.__vue__=n),n.$vnode&&n.$parent&&n.$vnode===n.$parent._vnode&&(n.$parent.$el=n.$el)},e.prototype._updateFromParent=function(e,t,n,r){var i=this,o=!(!i.$options._renderChildren&&!r);if(i.$options._parentVnode=n,i.$vnode=n,i._vnode&&(i._vnode.parent=n),i.$options._renderChildren=r,e&&i.$options.props){Mi.shouldConvert=!1;for(var a=i.$options._propKeys||[],s=0;s<a.length;s++){var c=a[s];i[c]=P(c,i.$options.props,e,i)}Mi.shouldConvert=!0,i.$options.propsData=e}if(t){var u=i.$options._parentListeners;i.$options._parentListeners=t,ye(i,t,u)}o&&(i.$slots=ve(r,n.context),i.$forceUpdate())},e.prototype.$forceUpdate=function(){var e=this;e._watcher&&e._watcher.update()},e.prototype.$destroy=function(){var e=this;if(!e._isBeingDestroyed){we(e,"beforeDestroy"),e._isBeingDestroyed=!0;var t=e.$parent;!t||t._isBeingDestroyed||e.$options.abstract||r(t.$children,e),e._watcher&&e._watcher.teardown();for(var n=e._watchers.length;n--;)e._watchers[n].teardown();e._data.__ob__&&e._data.__ob__.vmCount--,e._isDestroyed=!0,we(e,"destroyed"),e.$off(),e.$el&&(e.$el.__vue__=null),e.__patch__(e._vnode,null)}}}function we(e,t){var n=e.$options[t];if(n)for(var r=0,i=n.length;r<i;r++)n[r].call(e);e._hasHookEvent&&e.$emit("hook:"+t)}function Ce(){Gi.length=0,Yi={},Qi=Xi=!1}function xe(){Xi=!0;var e,t,n;for(Gi.sort(function(e,t){return e.id-t.id}),eo=0;eo<Gi.length;eo++)e=Gi[eo],t=e.id,Yi[t]=null,e.run();for(eo=Gi.length;eo--;)e=Gi[eo],n=e.vm,n._watcher===e&&n._isMounted&&we(n,"updated");ki&&vi.devtools&&ki.emit("flush"),Ce()}function ke(e){var t=e.id;if(null==Yi[t]){if(Yi[t]=!0,Xi){for(var n=Gi.length-1;n>=0&&Gi[n].id>e.id;)n--;Gi.splice(Math.max(n,eo)+1,0,e)}else Gi.push(e);Qi||(Qi=!0,Ai(xe))}}function Ae(e){ro.clear(),Oe(e,ro)}function Oe(e,t){var n,r,i=Array.isArray(e);if((i||l(e))&&Object.isExtensible(e)){if(e.__ob__){var o=e.__ob__.dep.id;if(t.has(o))return;t.add(o)}if(i)for(n=e.length;n--;)Oe(e[n],t);else for(r=Object.keys(e),n=r.length;n--;)Oe(e[r[n]],t)}}function Se(e){e._watchers=[];var t=e.$options;t.props&&Te(e,t.props),t.methods&&Ne(e,t.methods),t.data?Ee(e):k(e._data={},!0),t.computed&&Ie(e,t.computed),t.watch&&Le(e,t.watch)}function Te(e,t){var n=e.$options.propsData||{},r=e.$options._propKeys=Object.keys(t),i=!e.$parent;Mi.shouldConvert=i;for(var o=function(i){var o=r[i];A(e,o,P(o,t,n,e))},a=0;a<r.length;a++)o(a);Mi.shouldConvert=!0}function Ee(e){var t=e.$options.data;t=e._data="function"==typeof t?t.call(e):t||{},f(t)||(t={});for(var n=Object.keys(t),r=e.$options.props,o=n.length;o--;)r&&i(r,n[o])||Pe(e,n[o]);k(t,!0)}function Ie(e,t){for(var n in t){var r=t[n];"function"==typeof r?(io.get=je(r,e),io.set=d):(io.get=r.get?r.cache!==!1?je(r.get,e):s(r.get,e):d,io.set=r.set?s(r.set,e):d),Object.defineProperty(e,n,io)}}function je(e,t){var n=new no(t,e,d,{lazy:!0});return function(){return n.dirty&&n.evaluate(),Ei.target&&n.depend(),n.value}}function Ne(e,t){for(var n in t)e[n]=null==t[n]?d:s(t[n],e)}function Le(e,t){for(var n in t){var r=t[n];if(Array.isArray(r))for(var i=0;i<r.length;i++)Me(e,n,r[i]);else Me(e,n,r)}}function Me(e,t,n){var r;f(n)&&(r=n,n=n.handler),"string"==typeof n&&(n=e[n]),e.$watch(t,n,r)}function De(e){var t={};t.get=function(){return this._data},Object.defineProperty(e.prototype,"$data",t),e.prototype.$set=O,e.prototype.$delete=S,e.prototype.$watch=function(e,t,n){var r=this;n=n||{},n.user=!0;var i=new no(r,e,t,n);return n.immediate&&t.call(r,i.value),function(){i.teardown()}}}function Pe(e,t){g(t)||Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return e._data[t]},set:function(n){e._data[t]=n}})}function Re(e){e.prototype._init=function(e){var t=this;t._uid=oo++,t._isVue=!0,e&&e._isComponent?Fe(t,e):t.$options=M(He(t.constructor),e||{},t),t._renderProxy=t,t._self=t,be(t),he(t),pe(t),we(t,"beforeCreate"),Se(t),we(t,"created"),t.$options.el&&t.$mount(t.$options.el)}}function Fe(e,t){var n=e.$options=Object.create(e.constructor.options);n.parent=t.parent,n.propsData=t.propsData,n._parentVnode=t._parentVnode,n._parentListeners=t._parentListeners,n._renderChildren=t._renderChildren,n._componentTag=t._componentTag,n._parentElm=t._parentElm,n._refElm=t._refElm,t.render&&(n.render=t.render,n.staticRenderFns=t.staticRenderFns)}function He(e){var t=e.options;if(e.super){var n=e.super.options,r=e.superOptions,i=e.extendOptions;n!==r&&(e.superOptions=n,i.render=t.render,i.staticRenderFns=t.staticRenderFns,i._scopeId=t._scopeId,t=e.options=M(n,i),t.name&&(t.components[t.name]=e))}return t}function Ue(e){this._init(e)}function Be(e){e.use=function(e){if(!e.installed){var t=c(arguments,1);return t.unshift(this),"function"==typeof e.install?e.install.apply(e,t):e.apply(null,t),e.installed=!0,this}}}function ze(e){e.mixin=function(e){this.options=M(this.options,e)}}function Ve(e){e.cid=0;var t=1;e.extend=function(e){e=e||{};var n=this,r=n.cid,i=e._Ctor||(e._Ctor={});if(i[r])return i[r];var o=e.name||n.options.name,a=function(e){this._init(e)};return a.prototype=Object.create(n.prototype),a.prototype.constructor=a,a.cid=t++,a.options=M(n.options,e),a.super=n,a.extend=n.extend,a.mixin=n.mixin,a.use=n.use,vi._assetTypes.forEach(function(e){a[e]=n[e]}),o&&(a.options.components[o]=a),a.superOptions=n.options,a.extendOptions=e,i[r]=a,a}}function Je(e){vi._assetTypes.forEach(function(t){e[t]=function(e,n){return n?("component"===t&&f(n)&&(n.name=n.name||e,n=this.options._base.extend(n)),"directive"===t&&"function"==typeof n&&(n={bind:n,update:n}),this.options[t+"s"][e]=n,n):this.options[t+"s"][e]}})}function Ke(e){return e&&(e.Ctor.options.name||e.tag)}function qe(e,t){return"string"==typeof e?e.split(",").indexOf(t)>-1:e.test(t)}function We(e,t){for(var n in e){var r=e[n];if(r){var i=Ke(r.componentOptions);i&&!t(i)&&(Ze(r),e[n]=null)}}}function Ze(e){e&&(e.componentInstance._inactive||we(e.componentInstance,"deactivated"),e.componentInstance.$destroy())}function Ge(e){var t={};t.get=function(){return vi},Object.defineProperty(e,"config",t),e.util=Fi,e.set=O,e.delete=S,e.nextTick=Ai,e.options=Object.create(null),vi._assetTypes.forEach(function(t){e.options[t+"s"]=Object.create(null)}),e.options._base=e,u(e.options.components,co),Be(e),ze(e),Ve(e),Je(e)}function Ye(e){for(var t=e.data,n=e,r=e;r.componentInstance;)r=r.componentInstance._vnode,r.data&&(t=Qe(r.data,t));for(;n=n.parent;)n.data&&(t=Qe(t,n.data));return Xe(t)}function Qe(e,t){return{staticClass:et(e.staticClass,t.staticClass),class:e.class?[e.class,t.class]:t.class}}function Xe(e){var t=e.class,n=e.staticClass;return n||t?et(n,tt(t)):""}function et(e,t){return e?t?e+" "+t:e:t||""}function tt(e){var t="";if(!e)return t;if("string"==typeof e)return e;if(Array.isArray(e)){for(var n,r=0,i=e.length;r<i;r++)e[r]&&(n=tt(e[r]))&&(t+=n+" ");return t.slice(0,-1)}if(l(e)){for(var o in e)e[o]&&(t+=o+" ");return t.slice(0,-1)}return t}function nt(e){return wo(e)?"svg":"math"===e?"math":void 0}function rt(e){if(!gi)return!0;if(xo(e))return!1;if(e=e.toLowerCase(),null!=ko[e])return ko[e];var t=document.createElement(e);return e.indexOf("-")>-1?ko[e]=t.constructor===window.HTMLUnknownElement||t.constructor===window.HTMLElement:ko[e]=/HTMLUnknownElement/.test(t.toString())}function it(e){if("string"==typeof e){if(e=document.querySelector(e),!e)return document.createElement("div")}return e}function ot(e,t){var n=document.createElement(e);return"select"!==e?n:(t.data&&t.data.attrs&&"multiple"in t.data.attrs&&n.setAttribute("multiple","multiple"),n)}function at(e,t){return document.createElementNS(bo[e],t)}function st(e){return document.createTextNode(e)}function ct(e){return document.createComment(e)}function ut(e,t,n){e.insertBefore(t,n)}function lt(e,t){e.removeChild(t)}function ft(e,t){e.appendChild(t)}function pt(e){return e.parentNode}function dt(e){return e.nextSibling}function vt(e){return e.tagName}function ht(e,t){e.textContent=t}function mt(e,t,n){e.setAttribute(t,n)}function gt(e,t){var n=e.data.ref;if(n){var i=e.context,o=e.componentInstance||e.elm,a=i.$refs;t?Array.isArray(a[n])?r(a[n],o):a[n]===o&&(a[n]=void 0):e.data.refInFor?Array.isArray(a[n])&&a[n].indexOf(o)<0?a[n].push(o):a[n]=[o]:a[n]=o}}function yt(e){return null==e}function _t(e){return null!=e}function bt(e,t){return e.key===t.key&&e.tag===t.tag&&e.isComment===t.isComment&&!e.data==!t.data}function $t(e,t,n){var r,i,o={};for(r=t;r<=n;++r)i=e[r].key,_t(i)&&(o[i]=r);return o}function wt(e){function t(e){return new Hi(O.tagName(e).toLowerCase(),{},[],void 0,e)}function r(e,t){function n(){0===--n.listeners&&i(e)}return n.listeners=t,n}function i(e){var t=O.parentNode(e);t&&O.removeChild(t,e)}function a(e,t,n,r,i){if(e.isRootInsert=!i,!s(e,t,n,r)){var o=e.data,a=e.children,c=e.tag;_t(c)?(e.elm=e.ns?O.createElementNS(e.ns,c):O.createElement(c,e),v(e),f(e,a,t),_t(o)&&d(e,t),l(n,e.elm,r)):e.isComment?(e.elm=O.createComment(e.text),l(n,e.elm,r)):(e.elm=O.createTextNode(e.text),l(n,e.elm,r))}}function s(e,t,n,r){var i=e.data;if(_t(i)){var o=_t(e.componentInstance)&&i.keepAlive;if(_t(i=i.hook)&&_t(i=i.init)&&i(e,!1,n,r),_t(e.componentInstance))return c(e,t),o&&u(e,t,n,r),!0}}function c(e,t){e.data.pendingInsert&&t.push.apply(t,e.data.pendingInsert),e.elm=e.componentInstance.$el,p(e)?(d(e,t),v(e)):(gt(e),t.push(e))}function u(e,t,n,r){for(var i,o=e;o.componentInstance;)if(o=o.componentInstance._vnode,_t(i=o.data)&&_t(i=i.transition)){for(i=0;i<k.activate.length;++i)k.activate[i](So,o);t.push(o);break}l(n,e.elm,r)}function l(e,t,n){e&&(n?O.insertBefore(e,t,n):O.appendChild(e,t))}function f(e,t,n){if(Array.isArray(t))for(var r=0;r<t.length;++r)a(t[r],n,e.elm,null,!0);else o(e.text)&&O.appendChild(e.elm,O.createTextNode(e.text))}function p(e){for(;e.componentInstance;)e=e.componentInstance._vnode;return _t(e.tag)}function d(e,t){for(var n=0;n<k.create.length;++n)k.create[n](So,e);C=e.data.hook,_t(C)&&(C.create&&C.create(So,e),C.insert&&t.push(e))}function v(e){var t;_t(t=e.context)&&_t(t=t.$options._scopeId)&&O.setAttribute(e.elm,t,""),_t(t=Zi)&&t!==e.context&&_t(t=t.$options._scopeId)&&O.setAttribute(e.elm,t,"")}function h(e,t,n,r,i,o){for(;r<=i;++r)a(n[r],o,e,t)}function m(e){var t,n,r=e.data;if(_t(r))for(_t(t=r.hook)&&_t(t=t.destroy)&&t(e),t=0;t<k.destroy.length;++t)k.destroy[t](e);if(_t(t=e.children))for(n=0;n<e.children.length;++n)m(e.children[n])}function g(e,t,n,r){for(;n<=r;++n){var o=t[n];_t(o)&&(_t(o.tag)?(y(o),m(o)):i(o.elm))}}function y(e,t){if(t||_t(e.data)){var n=k.remove.length+1;for(t?t.listeners+=n:t=r(e.elm,n),_t(C=e.componentInstance)&&_t(C=C._vnode)&&_t(C.data)&&y(C,t),C=0;C<k.remove.length;++C)k.remove[C](e,t);_t(C=e.data.hook)&&_t(C=C.remove)?C(e,t):t()}else i(e.elm)}function _(e,t,n,r,i){for(var o,s,c,u,l=0,f=0,p=t.length-1,d=t[0],v=t[p],m=n.length-1,y=n[0],_=n[m],$=!i;l<=p&&f<=m;)yt(d)?d=t[++l]:yt(v)?v=t[--p]:bt(d,y)?(b(d,y,r),d=t[++l],y=n[++f]):bt(v,_)?(b(v,_,r),v=t[--p],_=n[--m]):bt(d,_)?(b(d,_,r),$&&O.insertBefore(e,d.elm,O.nextSibling(v.elm)),d=t[++l],_=n[--m]):bt(v,y)?(b(v,y,r),$&&O.insertBefore(e,v.elm,d.elm),v=t[--p],y=n[++f]):(yt(o)&&(o=$t(t,l,p)),s=_t(y.key)?o[y.key]:null,yt(s)?(a(y,r,e,d.elm),y=n[++f]):(c=t[s],bt(c,y)?(b(c,y,r),t[s]=void 0,$&&O.insertBefore(e,y.elm,d.elm),y=n[++f]):(a(y,r,e,d.elm),y=n[++f])));l>p?(u=yt(n[m+1])?null:n[m+1].elm,h(e,u,n,f,m,r)):f>m&&g(e,t,l,p)}function b(e,t,n,r){if(e!==t){if(t.isStatic&&e.isStatic&&t.key===e.key&&(t.isCloned||t.isOnce))return t.elm=e.elm,void(t.componentInstance=e.componentInstance);var i,o=t.data,a=_t(o);a&&_t(i=o.hook)&&_t(i=i.prepatch)&&i(e,t);var s=t.elm=e.elm,c=e.children,u=t.children;if(a&&p(t)){for(i=0;i<k.update.length;++i)k.update[i](e,t);_t(i=o.hook)&&_t(i=i.update)&&i(e,t)}yt(t.text)?_t(c)&&_t(u)?c!==u&&_(s,c,u,n,r):_t(u)?(_t(e.text)&&O.setTextContent(s,""),h(s,null,u,0,u.length-1,n)):_t(c)?g(s,c,0,c.length-1):_t(e.text)&&O.setTextContent(s,""):e.text!==t.text&&O.setTextContent(s,t.text),a&&_t(i=o.hook)&&_t(i=i.postpatch)&&i(e,t)}}function $(e,t,n){if(n&&e.parent)e.parent.data.pendingInsert=t;else for(var r=0;r<t.length;++r)t[r].data.hook.insert(t[r])}function w(e,t,n){t.elm=e;var r=t.tag,i=t.data,o=t.children;if(_t(i)&&(_t(C=i.hook)&&_t(C=C.init)&&C(t,!0),_t(C=t.componentInstance)))return c(t,n),!0;if(_t(r)){if(_t(o))if(e.hasChildNodes()){for(var a=!0,s=e.firstChild,u=0;u<o.length;u++){if(!s||!w(s,o[u],n)){a=!1;break}s=s.nextSibling}if(!a||s)return!1}else f(t,o,n);if(_t(i))for(var l in i)if(!S(l)){d(t,n);break}}else e.data!==t.text&&(e.data=t.text);return!0}var C,x,k={},A=e.modules,O=e.nodeOps;for(C=0;C<To.length;++C)for(k[To[C]]=[],x=0;x<A.length;++x)void 0!==A[x][To[C]]&&k[To[C]].push(A[x][To[C]]);var S=n("attrs,style,class,staticClass,staticStyle,key");return function(e,n,r,i,o,s){if(!n)return void(e&&m(e));var c=!1,u=[];if(e){var l=_t(e.nodeType);if(!l&&bt(e,n))b(e,n,u,i);else{if(l){if(1===e.nodeType&&e.hasAttribute("server-rendered")&&(e.removeAttribute("server-rendered"),r=!0),r&&w(e,n,u))return $(n,u,!0),e;e=t(e)}var f=e.elm,d=O.parentNode(f);if(a(n,u,f._leaveCb?null:d,O.nextSibling(f)),n.parent){for(var v=n.parent;v;)v.elm=n.elm,v=v.parent;if(p(n))for(var h=0;h<k.create.length;++h)k.create[h](So,n.parent)}null!==d?g(d,[e],0,0):_t(e.tag)&&m(e)}}else c=!0,a(n,u,o,s);return $(n,u,c),n.elm}}function Ct(e,t){(e.data.directives||t.data.directives)&&xt(e,t)}function xt(e,t){var n,r,i,o=e===So,a=t===So,s=kt(e.data.directives,e.context),c=kt(t.data.directives,t.context),u=[],l=[];for(n in c)r=s[n],i=c[n],r?(i.oldValue=r.value,Ot(i,"update",t,e),i.def&&i.def.componentUpdated&&l.push(i)):(Ot(i,"bind",t,e),i.def&&i.def.inserted&&u.push(i));if(u.length){var f=function(){for(var n=0;n<u.length;n++)Ot(u[n],"inserted",t,e)};o?ne(t.data.hook||(t.data.hook={}),"insert",f,"dir-insert"):f()}if(l.length&&ne(t.data.hook||(t.data.hook={}),"postpatch",function(){for(var n=0;n<l.length;n++)Ot(l[n],"componentUpdated",t,e)},"dir-postpatch"),!o)for(n in s)c[n]||Ot(s[n],"unbind",e,e,a)}function kt(e,t){var n=Object.create(null);if(!e)return n;var r,i;for(r=0;r<e.length;r++)i=e[r],i.modifiers||(i.modifiers=Io),n[At(i)]=i,i.def=D(t.$options,"directives",i.name,!0);return n}function At(e){return e.rawName||e.name+"."+Object.keys(e.modifiers||{}).join(".")}function Ot(e,t,n,r,i){var o=e.def&&e.def[t];o&&o(n.elm,e,n,r,i)}function St(e,t){if(e.data.attrs||t.data.attrs){var n,r,i,o=t.elm,a=e.data.attrs||{},s=t.data.attrs||{};s.__ob__&&(s=t.data.attrs=u({},s));for(n in s)r=s[n],i=a[n],i!==r&&Tt(o,n,r);bi&&s.value!==a.value&&Tt(o,"value",s.value);for(n in a)null==s[n]&&(go(n)?o.removeAttributeNS(mo,yo(n)):vo(n)||o.removeAttribute(n))}}function Tt(e,t,n){ho(t)?_o(n)?e.removeAttribute(t):e.setAttribute(t,t):vo(t)?e.setAttribute(t,_o(n)||"false"===n?"false":"true"):go(t)?_o(n)?e.removeAttributeNS(mo,yo(t)):e.setAttributeNS(mo,t,n):_o(n)?e.removeAttribute(t):e.setAttribute(t,n)}function Et(e,t){var n=t.elm,r=t.data,i=e.data;if(r.staticClass||r.class||i&&(i.staticClass||i.class)){var o=Ye(t),a=n._transitionClasses;a&&(o=et(o,tt(a))),o!==n._prevClass&&(n.setAttribute("class",o),n._prevClass=o)}}function It(e,t,n,r){if(n){var i=t,o=uo;t=function(n){jt(e,t,r,o),1===arguments.length?i(n):i.apply(null,arguments)}}uo.addEventListener(e,t,r)}function jt(e,t,n,r){(r||uo).removeEventListener(e,t,n)}function Nt(e,t){if(e.data.on||t.data.on){var n=t.data.on||{},r=e.data.on||{};uo=t.elm,ie(n,r,It,jt,t.context)}}function Lt(e,t){if(e.data.domProps||t.data.domProps){var n,r,i=t.elm,o=e.data.domProps||{},a=t.data.domProps||{};a.__ob__&&(a=t.data.domProps=u({},a));for(n in o)null==a[n]&&(i[n]="");for(n in a)if(r=a[n],"textContent"!==n&&"innerHTML"!==n||(t.children&&(t.children.length=0),r!==o[n]))if("value"===n){i._value=r;var s=null==r?"":String(r);Mt(i,t,s)&&(i.value=s)}else i[n]=r}}function Mt(e,t,n){return!e.composing&&("option"===t.tag||Dt(e,n)||Pt(t,n))}function Dt(e,t){return document.activeElement!==e&&e.value!==t}function Pt(e,n){var r=e.elm.value,i=e.elm._vModifiers;return i&&i.number||"number"===e.elm.type?t(r)!==t(n):i&&i.trim?r.trim()!==n.trim():r!==n}function Rt(e){var t=Ft(e.style);return e.staticStyle?u(e.staticStyle,t):t}function Ft(e){return Array.isArray(e)?p(e):"string"==typeof e?Po(e):e}function Ht(e,t){var n,r={};if(t)for(var i=e;i.componentInstance;)i=i.componentInstance._vnode,i.data&&(n=Rt(i.data))&&u(r,n);(n=Rt(e.data))&&u(r,n);for(var o=e;o=o.parent;)o.data&&(n=Rt(o.data))&&u(r,n);return r}function Ut(e,t){var n=t.data,r=e.data;if(n.staticStyle||n.style||r.staticStyle||r.style){var i,o,a=t.elm,s=e.data.staticStyle,c=e.data.style||{},l=s||c,f=Ft(t.data.style)||{};t.data.style=f.__ob__?u({},f):f;var p=Ht(t,!0);for(o in l)null==p[o]&&Ho(a,o,"");for(o in p)i=p[o],i!==l[o]&&Ho(a,o,null==i?"":i)}}function Bt(e,t){if(t&&t.trim())if(e.classList)t.indexOf(" ")>-1?t.split(/\s+/).forEach(function(t){return e.classList.add(t)}):e.classList.add(t);else{var n=" "+e.getAttribute("class")+" ";n.indexOf(" "+t+" ")<0&&e.setAttribute("class",(n+t).trim())}}function zt(e,t){if(t&&t.trim())if(e.classList)t.indexOf(" ")>-1?t.split(/\s+/).forEach(function(t){return e.classList.remove(t)}):e.classList.remove(t);else{for(var n=" "+e.getAttribute("class")+" ",r=" "+t+" ";n.indexOf(r)>=0;)n=n.replace(r," ");e.setAttribute("class",n.trim())}}function Vt(e){Yo(function(){Yo(e)})}function Jt(e,t){(e._transitionClasses||(e._transitionClasses=[])).push(t),Bt(e,t)}function Kt(e,t){e._transitionClasses&&r(e._transitionClasses,t),zt(e,t)}function qt(e,t,n){var r=Wt(e,t),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===Jo?Wo:Go,c=0,u=function(){e.removeEventListener(s,l),n()},l=function(t){t.target===e&&++c>=a&&u()};setTimeout(function(){c<a&&u()},o+1),e.addEventListener(s,l)}function Wt(e,t){var n,r=window.getComputedStyle(e),i=r[qo+"Delay"].split(", "),o=r[qo+"Duration"].split(", "),a=Zt(i,o),s=r[Zo+"Delay"].split(", "),c=r[Zo+"Duration"].split(", "),u=Zt(s,c),l=0,f=0;t===Jo?a>0&&(n=Jo,l=a,f=o.length):t===Ko?u>0&&(n=Ko,l=u,f=c.length):(l=Math.max(a,u),n=l>0?a>u?Jo:Ko:null,f=n?n===Jo?o.length:c.length:0);var p=n===Jo&&Qo.test(r[qo+"Property"]);return{type:n,timeout:l,propCount:f,hasTransform:p}}function Zt(e,t){for(;e.length<t.length;)e=e.concat(e);return Math.max.apply(null,t.map(function(t,n){ return Gt(t)+Gt(e[n])}))}function Gt(e){return 1e3*Number(e.slice(0,-1))}function Yt(e,t){var n=e.elm;n._leaveCb&&(n._leaveCb.cancelled=!0,n._leaveCb());var r=Xt(e.data.transition);if(r&&!n._enterCb&&1===n.nodeType){for(var i=r.css,o=r.type,a=r.enterClass,s=r.enterToClass,c=r.enterActiveClass,u=r.appearClass,l=r.appearToClass,f=r.appearActiveClass,p=r.beforeEnter,d=r.enter,v=r.afterEnter,h=r.enterCancelled,m=r.beforeAppear,g=r.appear,y=r.afterAppear,_=r.appearCancelled,b=Zi,$=Zi.$vnode;$&&$.parent;)$=$.parent,b=$.context;var w=!b._isMounted||!e.isRootInsert;if(!w||g||""===g){var C=w?u:a,x=w?f:c,k=w?l:s,A=w?m||p:p,O=w&&"function"==typeof g?g:d,S=w?y||v:v,T=w?_||h:h,E=i!==!1&&!bi,I=O&&(O._length||O.length)>1,j=n._enterCb=en(function(){E&&(Kt(n,k),Kt(n,x)),j.cancelled?(E&&Kt(n,C),T&&T(n)):S&&S(n),n._enterCb=null});e.data.show||ne(e.data.hook||(e.data.hook={}),"insert",function(){var t=n.parentNode,r=t&&t._pending&&t._pending[e.key];r&&r.tag===e.tag&&r.elm._leaveCb&&r.elm._leaveCb(),O&&O(n,j)},"transition-insert"),A&&A(n),E&&(Jt(n,C),Jt(n,x),Vt(function(){Jt(n,k),Kt(n,C),j.cancelled||I||qt(n,o,j)})),e.data.show&&(t&&t(),O&&O(n,j)),E||I||j()}}}function Qt(e,t){function n(){g.cancelled||(e.data.show||((r.parentNode._pending||(r.parentNode._pending={}))[e.key]=e),l&&l(r),h&&(Jt(r,s),Jt(r,u),Vt(function(){Jt(r,c),Kt(r,s),g.cancelled||m||qt(r,a,g)})),f&&f(r,g),h||m||g())}var r=e.elm;r._enterCb&&(r._enterCb.cancelled=!0,r._enterCb());var i=Xt(e.data.transition);if(!i)return t();if(!r._leaveCb&&1===r.nodeType){var o=i.css,a=i.type,s=i.leaveClass,c=i.leaveToClass,u=i.leaveActiveClass,l=i.beforeLeave,f=i.leave,p=i.afterLeave,d=i.leaveCancelled,v=i.delayLeave,h=o!==!1&&!bi,m=f&&(f._length||f.length)>1,g=r._leaveCb=en(function(){r.parentNode&&r.parentNode._pending&&(r.parentNode._pending[e.key]=null),h&&(Kt(r,c),Kt(r,u)),g.cancelled?(h&&Kt(r,s),d&&d(r)):(t(),p&&p(r)),r._leaveCb=null});v?v(n):n()}}function Xt(e){if(e){if("object"==typeof e){var t={};return e.css!==!1&&u(t,Xo(e.name||"v")),u(t,e),t}return"string"==typeof e?Xo(e):void 0}}function en(e){var t=!1;return function(){t||(t=!0,e())}}function tn(e,t){t.data.show||Yt(t)}function nn(e,t,n){var r=t.value,i=e.multiple;if(!i||Array.isArray(r)){for(var o,a,s=0,c=e.options.length;s<c;s++)if(a=e.options[s],i)o=m(r,on(a))>-1,a.selected!==o&&(a.selected=o);else if(h(on(a),r))return void(e.selectedIndex!==s&&(e.selectedIndex=s));i||(e.selectedIndex=-1)}}function rn(e,t){for(var n=0,r=t.length;n<r;n++)if(h(on(t[n]),e))return!1;return!0}function on(e){return"_value"in e?e._value:e.value}function an(e){e.target.composing=!0}function sn(e){e.target.composing=!1,cn(e.target,"input")}function cn(e,t){var n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function un(e){return!e.componentInstance||e.data&&e.data.transition?e:un(e.componentInstance._vnode)}function ln(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?ln(ce(t.children)):e}function fn(e){var t={},n=e.$options;for(var r in n.propsData)t[r]=e[r];var i=n._parentListeners;for(var o in i)t[ai(o)]=i[o].fn;return t}function pn(e,t){return/\d-keep-alive$/.test(t.tag)?e("keep-alive"):null}function dn(e){for(;e=e.parent;)if(e.data.transition)return!0}function vn(e,t){return t.key===e.key&&t.tag===e.tag}function hn(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function mn(e){e.data.newPos=e.elm.getBoundingClientRect()}function gn(e){var t=e.data.pos,n=e.data.newPos,r=t.left-n.left,i=t.top-n.top;if(r||i){e.data.moved=!0;var o=e.elm.style;o.transform=o.WebkitTransform="translate("+r+"px,"+i+"px)",o.transitionDuration="0s"}}function yn(e,t){var n=document.createElement("div");return n.innerHTML='<div a="'+e+'">',n.innerHTML.indexOf(t)>0}function _n(e){return pa=pa||document.createElement("div"),pa.innerHTML=e,pa.textContent}function bn(e,t){return t&&(e=e.replace(os,"\n")),e.replace(rs,"<").replace(is,">").replace(as,"&").replace(ss,'"')}function $n(e,t){function n(t){f+=t,e=e.substring(t)}function r(){var t=e.match(Ca);if(t){var r={tagName:t[1],attrs:[],start:f};n(t[0].length);for(var i,o;!(i=e.match(xa))&&(o=e.match(ba));)n(o[0].length),r.attrs.push(o);if(i)return r.unarySlash=i[1],n(i[0].length),r.end=f,r}}function i(e){var n=e.tagName,r=e.unarySlash;u&&("p"===s&&ma(n)&&o(s),ha(n)&&s===n&&o(n));for(var i=l(n)||"html"===n&&"head"===s||!!r,a=e.attrs.length,f=new Array(a),p=0;p<a;p++){var d=e.attrs[p];Ta&&d[0].indexOf('""')===-1&&(""===d[3]&&delete d[3],""===d[4]&&delete d[4],""===d[5]&&delete d[5]);var v=d[3]||d[4]||d[5]||"";f[p]={name:d[1],value:bn(v,t.shouldDecodeNewlines)}}i||(c.push({tag:n,lowerCasedTag:n.toLowerCase(),attrs:f}),s=n,r=""),t.start&&t.start(n,f,i,e.start,e.end)}function o(e,n,r){var i,o;if(null==n&&(n=f),null==r&&(r=f),e&&(o=e.toLowerCase()),e)for(i=c.length-1;i>=0&&c[i].lowerCasedTag!==o;i--);else i=0;if(i>=0){for(var a=c.length-1;a>=i;a--)t.end&&t.end(c[a].tag,n,r);c.length=i,s=i&&c[i-1].tag}else"br"===o?t.start&&t.start(e,[],!0,n,r):"p"===o&&(t.start&&t.start(e,[],!1,n,r),t.end&&t.end(e,n,r))}for(var a,s,c=[],u=t.expectHTML,l=t.isUnaryTag||pi,f=0;e;){if(a=e,s&&ts(s)){var p=s.toLowerCase(),d=ns[p]||(ns[p]=new RegExp("([\\s\\S]*?)(</"+p+"[^>]*>)","i")),v=0,h=e.replace(d,function(e,n,r){return v=r.length,"script"!==p&&"style"!==p&&"noscript"!==p&&(n=n.replace(/<!--([\s\S]*?)-->/g,"$1").replace(/<!\[CDATA\[([\s\S]*?)]]>/g,"$1")),t.chars&&t.chars(n),""});f+=e.length-h.length,e=h,o(p,f-v,f)}else{var m=e.indexOf("<");if(0===m){if(Oa.test(e)){var g=e.indexOf("-->");if(g>=0){n(g+3);continue}}if(Sa.test(e)){var y=e.indexOf("]>");if(y>=0){n(y+2);continue}}var _=e.match(Aa);if(_){n(_[0].length);continue}var b=e.match(ka);if(b){var $=f;n(b[0].length),o(b[1],$,f);continue}var w=r();if(w){i(w);continue}}var C=void 0,x=void 0,k=void 0;if(m>0){for(x=e.slice(m);!(ka.test(x)||Ca.test(x)||Oa.test(x)||Sa.test(x)||(k=x.indexOf("<",1),k<0));)m+=k,x=e.slice(m);C=e.substring(0,m),n(m)}m<0&&(C=e,e=""),t.chars&&C&&t.chars(C)}if(e===a&&t.chars){t.chars(e);break}}o()}function wn(e){function t(){(a||(a=[])).push(e.slice(v,i).trim()),v=i+1}var n,r,i,o,a,s=!1,c=!1,u=!1,l=!1,f=0,p=0,d=0,v=0;for(i=0;i<e.length;i++)if(r=n,n=e.charCodeAt(i),s)39===n&&92!==r&&(s=!1);else if(c)34===n&&92!==r&&(c=!1);else if(u)96===n&&92!==r&&(u=!1);else if(l)47===n&&92!==r&&(l=!1);else if(124!==n||124===e.charCodeAt(i+1)||124===e.charCodeAt(i-1)||f||p||d){switch(n){case 34:c=!0;break;case 39:s=!0;break;case 96:u=!0;break;case 40:d++;break;case 41:d--;break;case 91:p++;break;case 93:p--;break;case 123:f++;break;case 125:f--}if(47===n){for(var h=i-1,m=void 0;h>=0&&(m=e.charAt(h)," "===m);h--);m&&/[\w$]/.test(m)||(l=!0)}}else void 0===o?(v=i+1,o=e.slice(0,i).trim()):t();if(void 0===o?o=e.slice(0,i).trim():0!==v&&t(),a)for(i=0;i<a.length;i++)o=Cn(o,a[i]);return o}function Cn(e,t){var n=t.indexOf("(");if(n<0)return'_f("'+t+'")('+e+")";var r=t.slice(0,n),i=t.slice(n+1);return'_f("'+r+'")('+e+","+i}function xn(e,t){var n=t?ls(t):cs;if(n.test(e)){for(var r,i,o=[],a=n.lastIndex=0;r=n.exec(e);){i=r.index,i>a&&o.push(JSON.stringify(e.slice(a,i)));var s=wn(r[1].trim());o.push("_s("+s+")"),a=i+r[0].length}return a<e.length&&o.push(JSON.stringify(e.slice(a))),o.join("+")}}function kn(e){console.error("[Vue parser]: "+e)}function An(e,t){return e?e.map(function(e){return e[t]}).filter(function(e){return e}):[]}function On(e,t,n){(e.props||(e.props=[])).push({name:t,value:n})}function Sn(e,t,n){(e.attrs||(e.attrs=[])).push({name:t,value:n})}function Tn(e,t,n,r,i,o){(e.directives||(e.directives=[])).push({name:t,rawName:n,value:r,arg:i,modifiers:o})}function En(e,t,n,r,i){r&&r.capture&&(delete r.capture,t="!"+t),r&&r.once&&(delete r.once,t="~"+t);var o;r&&r.native?(delete r.native,o=e.nativeEvents||(e.nativeEvents={})):o=e.events||(e.events={});var a={value:n,modifiers:r},s=o[t];Array.isArray(s)?i?s.unshift(a):s.push(a):s?o[t]=i?[a,s]:[s,a]:o[t]=a}function In(e,t,n){var r=jn(e,":"+t)||jn(e,"v-bind:"+t);if(null!=r)return wn(r);if(n!==!1){var i=jn(e,t);if(null!=i)return JSON.stringify(i)}}function jn(e,t){var n;if(null!=(n=e.attrsMap[t]))for(var r=e.attrsList,i=0,o=r.length;i<o;i++)if(r[i].name===t){r.splice(i,1);break}return n}function Nn(e){if(Ia=e,Ea=Ia.length,Na=La=Ma=0,e.indexOf("[")<0||e.lastIndexOf("]")<Ea-1)return{exp:e,idx:null};for(;!Mn();)ja=Ln(),Dn(ja)?Rn(ja):91===ja&&Pn(ja);return{exp:e.substring(0,La),idx:e.substring(La+1,Ma)}}function Ln(){return Ia.charCodeAt(++Na)}function Mn(){return Na>=Ea}function Dn(e){return 34===e||39===e}function Pn(e){var t=1;for(La=Na;!Mn();)if(e=Ln(),Dn(e))Rn(e);else if(91===e&&t++,93===e&&t--,0===t){Ma=Na;break}}function Rn(e){for(var t=e;!Mn()&&(e=Ln(),e!==t););}function Fn(e,t){Da=t.warn||kn,Pa=t.getTagNamespace||pi,Ra=t.mustUseProp||pi,Fa=t.isPreTag||pi,Ha=An(t.modules,"preTransformNode"),Ua=An(t.modules,"transformNode"),Ba=An(t.modules,"postTransformNode"),za=t.delimiters;var n,r,i=[],o=t.preserveWhitespace!==!1,a=!1,s=!1;return $n(e,{expectHTML:t.expectHTML,isUnaryTag:t.isUnaryTag,shouldDecodeNewlines:t.shouldDecodeNewlines,start:function(e,o,c){function u(e){}var l=r&&r.ns||Pa(e);_i&&"svg"===l&&(o=rr(o));var f={type:1,tag:e,attrsList:o,attrsMap:tr(o),parent:r,children:[]};l&&(f.ns=l),nr(f)&&!xi()&&(f.forbidden=!0);for(var p=0;p<Ha.length;p++)Ha[p](f,t);if(a||(Hn(f),f.pre&&(a=!0)),Fa(f.tag)&&(s=!0),a)Un(f);else{Vn(f),Jn(f),Zn(f),Bn(f),f.plain=!f.key&&!o.length,zn(f),Gn(f),Yn(f);for(var d=0;d<Ua.length;d++)Ua[d](f,t);Qn(f)}if(n?i.length||n.if&&(f.elseif||f.else)&&(u(f),Wn(n,{exp:f.elseif,block:f})):(n=f,u(n)),r&&!f.forbidden)if(f.elseif||f.else)Kn(f,r);else if(f.slotScope){r.plain=!1;var v=f.slotTarget||"default";(r.scopedSlots||(r.scopedSlots={}))[v]=f}else r.children.push(f),f.parent=r;c||(r=f,i.push(f));for(var h=0;h<Ba.length;h++)Ba[h](f,t)},end:function(){var e=i[i.length-1],t=e.children[e.children.length-1];t&&3===t.type&&" "===t.text&&e.children.pop(),i.length-=1,r=i[i.length-1],e.pre&&(a=!1),Fa(e.tag)&&(s=!1)},chars:function(e){if(r&&(!_i||"textarea"!==r.tag||r.attrsMap.placeholder!==e)){var t=r.children;if(e=s||e.trim()?ys(e):o&&t.length?" ":""){var n;!a&&" "!==e&&(n=xn(e,za))?t.push({type:2,expression:n,text:e}):" "===e&&" "===t[t.length-1].text||r.children.push({type:3,text:e})}}}}),n}function Hn(e){null!=jn(e,"v-pre")&&(e.pre=!0)}function Un(e){var t=e.attrsList.length;if(t)for(var n=e.attrs=new Array(t),r=0;r<t;r++)n[r]={name:e.attrsList[r].name,value:JSON.stringify(e.attrsList[r].value)};else e.pre||(e.plain=!0)}function Bn(e){var t=In(e,"key");t&&(e.key=t)}function zn(e){var t=In(e,"ref");t&&(e.ref=t,e.refInFor=Xn(e))}function Vn(e){var t;if(t=jn(e,"v-for")){var n=t.match(ps);if(!n)return;e.for=n[2].trim();var r=n[1].trim(),i=r.match(ds);i?(e.alias=i[1].trim(),e.iterator1=i[2].trim(),i[3]&&(e.iterator2=i[3].trim())):e.alias=r}}function Jn(e){var t=jn(e,"v-if");if(t)e.if=t,Wn(e,{exp:t,block:e});else{null!=jn(e,"v-else")&&(e.else=!0);var n=jn(e,"v-else-if");n&&(e.elseif=n)}}function Kn(e,t){var n=qn(t.children);n&&n.if&&Wn(n,{exp:e.elseif,block:e})}function qn(e){for(var t=e.length;t--;){if(1===e[t].type)return e[t];e.pop()}}function Wn(e,t){e.ifConditions||(e.ifConditions=[]),e.ifConditions.push(t)}function Zn(e){var t=jn(e,"v-once");null!=t&&(e.once=!0)}function Gn(e){if("slot"===e.tag)e.slotName=In(e,"name");else{var t=In(e,"slot");t&&(e.slotTarget='""'===t?'"default"':t),"template"===e.tag&&(e.slotScope=jn(e,"scope"))}}function Yn(e){var t;(t=In(e,"is"))&&(e.component=t),null!=jn(e,"inline-template")&&(e.inlineTemplate=!0)}function Qn(e){var t,n,r,i,o,a,s,c,u=e.attrsList;for(t=0,n=u.length;t<n;t++)if(r=i=u[t].name,o=u[t].value,fs.test(r))if(e.hasBindings=!0,s=er(r),s&&(r=r.replace(gs,"")),vs.test(r))r=r.replace(vs,""),o=wn(o),c=!1,s&&(s.prop&&(c=!0,r=ai(r),"innerHtml"===r&&(r="innerHTML")),s.camel&&(r=ai(r))),c||Ra(e.tag,e.attrsMap.type,r)?On(e,r,o):Sn(e,r,o);else if(hs.test(r))r=r.replace(hs,""),En(e,r,o,s);else{r=r.replace(fs,"");var l=r.match(ms);l&&(a=l[1])&&(r=r.slice(0,-(a.length+1))),Tn(e,r,i,o,a,s)}else Sn(e,r,JSON.stringify(o))}function Xn(e){for(var t=e;t;){if(void 0!==t.for)return!0;t=t.parent}return!1}function er(e){var t=e.match(gs);if(t){var n={};return t.forEach(function(e){n[e.slice(1)]=!0}),n}}function tr(e){for(var t={},n=0,r=e.length;n<r;n++)t[e[n].name]=e[n].value;return t}function nr(e){return"style"===e.tag||"script"===e.tag&&(!e.attrsMap.type||"text/javascript"===e.attrsMap.type)}function rr(e){for(var t=[],n=0;n<e.length;n++){var r=e[n];_s.test(r.name)||(r.name=r.name.replace(bs,""),t.push(r))}return t}function ir(e,t){e&&(Va=$s(t.staticKeys||""),Ja=t.isReservedTag||pi,ar(e),sr(e,!1))}function or(e){return n("type,tag,attrsList,attrsMap,plain,parent,children,attrs"+(e?","+e:""))}function ar(e){if(e.static=ur(e),1===e.type){if(!Ja(e.tag)&&"slot"!==e.tag&&null==e.attrsMap["inline-template"])return;for(var t=0,n=e.children.length;t<n;t++){var r=e.children[t];ar(r),r.static||(e.static=!1)}}}function sr(e,t){if(1===e.type){if((e.static||e.once)&&(e.staticInFor=t),e.static&&e.children.length&&(1!==e.children.length||3!==e.children[0].type))return void(e.staticRoot=!0);if(e.staticRoot=!1,e.children)for(var n=0,r=e.children.length;n<r;n++)sr(e.children[n],t||!!e.for);e.ifConditions&&cr(e.ifConditions,t)}}function cr(e,t){for(var n=1,r=e.length;n<r;n++)sr(e[n].block,t)}function ur(e){return 2!==e.type&&(3===e.type||!(!e.pre&&(e.hasBindings||e.if||e.for||ri(e.tag)||!Ja(e.tag)||lr(e)||!Object.keys(e).every(Va))))}function lr(e){for(;e.parent;){if(e=e.parent,"template"!==e.tag)return!1;if(e.for)return!0}return!1}function fr(e,t){var n=t?"nativeOn:{":"on:{";for(var r in e)n+='"'+r+'":'+pr(r,e[r])+",";return n.slice(0,-1)+"}"}function pr(e,t){if(t){if(Array.isArray(t))return"["+t.map(function(t){return pr(e,t)}).join(",")+"]";if(t.modifiers){var n="",r=[];for(var i in t.modifiers)ks[i]?n+=ks[i]:r.push(i);r.length&&(n=dr(r)+n);var o=Cs.test(t.value)?t.value+"($event)":t.value;return"function($event){"+n+o+"}"}return ws.test(t.value)||Cs.test(t.value)?t.value:"function($event){"+t.value+"}"}return"function(){}"}function dr(e){return"if("+e.map(vr).join("&&")+")return;"}function vr(e){var t=parseInt(e,10);if(t)return"$event.keyCode!=="+t;var n=xs[e];return"_k($event.keyCode,"+JSON.stringify(e)+(n?","+JSON.stringify(n):"")+")"}function hr(e,t){e.wrapData=function(n){return"_b("+n+",'"+e.tag+"',"+t.value+(t.modifiers&&t.modifiers.prop?",true":"")+")"}}function mr(e,t){var n=Ya,r=Ya=[],i=Qa;Qa=0,Xa=t,Ka=t.warn||kn,qa=An(t.modules,"transformCode"),Wa=An(t.modules,"genData"),Za=t.directives||{},Ga=t.isReservedTag||pi;var o=e?gr(e):'_c("div")';return Ya=n,Qa=i,{render:"with(this){return "+o+"}",staticRenderFns:r}}function gr(e){if(e.staticRoot&&!e.staticProcessed)return yr(e);if(e.once&&!e.onceProcessed)return _r(e);if(e.for&&!e.forProcessed)return wr(e);if(e.if&&!e.ifProcessed)return br(e);if("template"!==e.tag||e.slotTarget){if("slot"===e.tag)return Lr(e);var t;if(e.component)t=Mr(e.component,e);else{var n=e.plain?void 0:Cr(e),r=e.inlineTemplate?null:Sr(e,!0);t="_c('"+e.tag+"'"+(n?","+n:"")+(r?","+r:"")+")"}for(var i=0;i<qa.length;i++)t=qa[i](e,t);return t}return Sr(e)||"void 0"}function yr(e){return e.staticProcessed=!0,Ya.push("with(this){return "+gr(e)+"}"),"_m("+(Ya.length-1)+(e.staticInFor?",true":"")+")"}function _r(e){if(e.onceProcessed=!0,e.if&&!e.ifProcessed)return br(e);if(e.staticInFor){for(var t="",n=e.parent;n;){if(n.for){t=n.key;break}n=n.parent}return t?"_o("+gr(e)+","+Qa++ +(t?","+t:"")+")":gr(e)}return yr(e)}function br(e){return e.ifProcessed=!0,$r(e.ifConditions.slice())}function $r(e){function t(e){return e.once?_r(e):gr(e)}if(!e.length)return"_e()";var n=e.shift();return n.exp?"("+n.exp+")?"+t(n.block)+":"+$r(e):""+t(n.block)}function wr(e){var t=e.for,n=e.alias,r=e.iterator1?","+e.iterator1:"",i=e.iterator2?","+e.iterator2:"";return e.forProcessed=!0,"_l(("+t+"),function("+n+r+i+"){return "+gr(e)+"})"}function Cr(e){var t="{",n=xr(e);n&&(t+=n+","),e.key&&(t+="key:"+e.key+","),e.ref&&(t+="ref:"+e.ref+","),e.refInFor&&(t+="refInFor:true,"),e.pre&&(t+="pre:true,"),e.component&&(t+='tag:"'+e.tag+'",');for(var r=0;r<Wa.length;r++)t+=Wa[r](e);if(e.attrs&&(t+="attrs:{"+Dr(e.attrs)+"},"),e.props&&(t+="domProps:{"+Dr(e.props)+"},"),e.events&&(t+=fr(e.events)+","),e.nativeEvents&&(t+=fr(e.nativeEvents,!0)+","),e.slotTarget&&(t+="slot:"+e.slotTarget+","),e.scopedSlots&&(t+=Ar(e.scopedSlots)+","),e.inlineTemplate){var i=kr(e);i&&(t+=i+",")}return t=t.replace(/,$/,"")+"}",e.wrapData&&(t=e.wrapData(t)),t}function xr(e){var t=e.directives;if(t){var n,r,i,o,a="directives:[",s=!1;for(n=0,r=t.length;n<r;n++){i=t[n],o=!0;var c=Za[i.name]||As[i.name];c&&(o=!!c(e,i,Ka)),o&&(s=!0,a+='{name:"'+i.name+'",rawName:"'+i.rawName+'"'+(i.value?",value:("+i.value+"),expression:"+JSON.stringify(i.value):"")+(i.arg?',arg:"'+i.arg+'"':"")+(i.modifiers?",modifiers:"+JSON.stringify(i.modifiers):"")+"},")}return s?a.slice(0,-1)+"]":void 0}}function kr(e){var t=e.children[0];if(1===t.type){var n=mr(t,Xa);return"inlineTemplate:{render:function(){"+n.render+"},staticRenderFns:["+n.staticRenderFns.map(function(e){return"function(){"+e+"}"}).join(",")+"]}"}}function Ar(e){return"scopedSlots:{"+Object.keys(e).map(function(t){return Or(t,e[t])}).join(",")+"}"}function Or(e,t){return e+":function("+String(t.attrsMap.scope)+"){return "+("template"===t.tag?Sr(t)||"void 0":gr(t))+"}"}function Sr(e,t){var n=e.children;if(n.length){var r=n[0];if(1===n.length&&r.for&&"template"!==r.tag&&"slot"!==r.tag)return gr(r);var i=Tr(n);return"["+n.map(jr).join(",")+"]"+(t&&i?","+i:"")}}function Tr(e){for(var t=0,n=0;n<e.length;n++){var r=e[n];if(1===r.type){if(Er(r)||r.ifConditions&&r.ifConditions.some(function(e){return Er(e.block)})){t=2;break}(Ir(r)||r.ifConditions&&r.ifConditions.some(function(e){return Ir(e.block)}))&&(t=1)}}return t}function Er(e){return void 0!==e.for||"template"===e.tag||"slot"===e.tag}function Ir(e){return!Ga(e.tag)}function jr(e){return 1===e.type?gr(e):Nr(e)}function Nr(e){return"_v("+(2===e.type?e.expression:Pr(JSON.stringify(e.text)))+")"}function Lr(e){var t=e.slotName||'"default"',n=Sr(e),r="_t("+t+(n?","+n:""),i=e.attrs&&"{"+e.attrs.map(function(e){return ai(e.name)+":"+e.value}).join(",")+"}",o=e.attrsMap["v-bind"];return!i&&!o||n||(r+=",null"),i&&(r+=","+i),o&&(r+=(i?"":",null")+","+o),r+")"}function Mr(e,t){var n=t.inlineTemplate?null:Sr(t,!0);return"_c("+e+","+Cr(t)+(n?","+n:"")+")"}function Dr(e){for(var t="",n=0;n<e.length;n++){var r=e[n];t+='"'+r.name+'":'+Pr(r.value)+","}return t.slice(0,-1)}function Pr(e){return e.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function Rr(e,t){var n=Fn(e.trim(),t);ir(n,t);var r=mr(n,t);return{ast:n,render:r.render,staticRenderFns:r.staticRenderFns}}function Fr(e,t){var n=(t.warn||kn,jn(e,"class"));n&&(e.staticClass=JSON.stringify(n));var r=In(e,"class",!1);r&&(e.classBinding=r)}function Hr(e){var t="";return e.staticClass&&(t+="staticClass:"+e.staticClass+","),e.classBinding&&(t+="class:"+e.classBinding+","),t}function Ur(e,t){var n=(t.warn||kn,jn(e,"style"));n&&(e.staticStyle=JSON.stringify(Po(n)));var r=In(e,"style",!1);r&&(e.styleBinding=r)}function Br(e){var t="";return e.staticStyle&&(t+="staticStyle:"+e.staticStyle+","),e.styleBinding&&(t+="style:("+e.styleBinding+"),"),t}function zr(e,t,n){es=n;var r=t.value,i=t.modifiers,o=e.tag,a=e.attrsMap.type;return"select"===o?qr(e,r,i):"input"===o&&"checkbox"===a?Vr(e,r,i):"input"===o&&"radio"===a?Jr(e,r,i):Kr(e,r,i),!0}function Vr(e,t,n){var r=n&&n.number,i=In(e,"value")||"null",o=In(e,"true-value")||"true",a=In(e,"false-value")||"false";On(e,"checked","Array.isArray("+t+")?_i("+t+","+i+")>-1"+("true"===o?":("+t+")":":_q("+t+","+o+")")),En(e,"click","var $$a="+t+",$$el=$event.target,$$c=$$el.checked?("+o+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+i+")":i)+",$$i=_i($$a,$$v);if($$c){$$i<0&&("+t+"=$$a.concat($$v))}else{$$i>-1&&("+t+"=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}}else{"+t+"=$$c}",null,!0)}function Jr(e,t,n){var r=n&&n.number,i=In(e,"value")||"null";i=r?"_n("+i+")":i,On(e,"checked","_q("+t+","+i+")"),En(e,"click",Wr(t,i),null,!0)}function Kr(e,t,n){var r=e.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,c=o||_i&&"range"===r?"change":"input",u=!o&&"range"!==r,l="input"===e.tag||"textarea"===e.tag,f=l?"$event.target.value"+(s?".trim()":""):s?"(typeof $event === 'string' ? $event.trim() : $event)":"$event";f=a||"number"===r?"_n("+f+")":f;var p=Wr(t,f);l&&u&&(p="if($event.target.composing)return;"+p),On(e,"value",l?"_s("+t+")":"("+t+")"),En(e,c,p,null,!0),(s||a||"number"===r)&&En(e,"blur","$forceUpdate()")}function qr(e,t,n){var r=n&&n.number,i='Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = "_value" in o ? o._value : o.value;return '+(r?"_n(val)":"val")+"})"+(null==e.attrsMap.multiple?"[0]":""),o=Wr(t,i);En(e,"change",o,null,!0)}function Wr(e,t){var n=Nn(e);return null===n.idx?e+"="+t:"var $$exp = "+n.exp+", $$idx = "+n.idx+";if (!Array.isArray($$exp)){"+e+"="+t+"}else{$$exp.splice($$idx, 1, "+t+")}"}function Zr(e,t){t.value&&On(e,"textContent","_s("+t.value+")")}function Gr(e,t){t.value&&On(e,"innerHTML","_s("+t.value+")")}function Yr(e,t){return t=t?u(u({},js),t):js,Rr(e,t)}function Qr(e,t,n){var r=(t&&t.warn||Si,t&&t.delimiters?String(t.delimiters)+e:e);if(Is[r])return Is[r];var i={},o=Yr(e,t);i.render=Xr(o.render);var a=o.staticRenderFns.length;i.staticRenderFns=new Array(a);for(var s=0;s<a;s++)i.staticRenderFns[s]=Xr(o.staticRenderFns[s]);return Is[r]=i}function Xr(e){try{return new Function(e)}catch(e){return d}}function ei(e){if(e.outerHTML)return e.outerHTML;var t=document.createElement("div");return t.appendChild(e.cloneNode(!0)),t.innerHTML}var ti,ni,ri=n("slot,component",!0),ii=Object.prototype.hasOwnProperty,oi=/-(\w)/g,ai=a(function(e){return e.replace(oi,function(e,t){return t?t.toUpperCase():""})}),si=a(function(e){return e.charAt(0).toUpperCase()+e.slice(1)}),ci=/([^-])([A-Z])/g,ui=a(function(e){return e.replace(ci,"$1-$2").replace(ci,"$1-$2").toLowerCase()}),li=Object.prototype.toString,fi="[object Object]",pi=function(){return!1},di=function(e){return e},vi={optionMergeStrategies:Object.create(null),silent:!1,devtools:!1,errorHandler:null,ignoredElements:[],keyCodes:Object.create(null),isReservedTag:pi,isUnknownElement:pi,getTagNamespace:d,parsePlatformTagName:di,mustUseProp:pi,_assetTypes:["component","directive","filter"],_lifecycleHooks:["beforeCreate","created","beforeMount","mounted","beforeUpdate","updated","beforeDestroy","destroyed","activated","deactivated"],_maxUpdateCount:100},hi=/[^\w.$]/,mi="__proto__"in{},gi="undefined"!=typeof window,yi=gi&&window.navigator.userAgent.toLowerCase(),_i=yi&&/msie|trident/.test(yi),bi=yi&&yi.indexOf("msie 9.0")>0,$i=yi&&yi.indexOf("edge/")>0,wi=yi&&yi.indexOf("android")>0,Ci=yi&&/iphone|ipad|ipod|ios/.test(yi),xi=function(){return void 0===ti&&(ti=!gi&&"undefined"!=typeof global&&"server"===global.process.env.VUE_ENV),ti},ki=gi&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__,Ai=function(){function e(){r=!1;var e=n.slice(0);n.length=0;for(var t=0;t<e.length;t++)e[t]()}var t,n=[],r=!1;if("undefined"!=typeof Promise&&b(Promise)){var i=Promise.resolve(),o=function(e){console.error(e)};t=function(){i.then(e).catch(o),Ci&&setTimeout(d)}}else if("undefined"==typeof MutationObserver||!b(MutationObserver)&&"[object MutationObserverConstructor]"!==MutationObserver.toString())t=function(){setTimeout(e,0)};else{var a=1,s=new MutationObserver(e),c=document.createTextNode(String(a));s.observe(c,{characterData:!0}),t=function(){a=(a+1)%2,c.data=String(a)}}return function(e,i){var o;if(n.push(function(){e&&e.call(i),o&&o(i)}),r||(r=!0,t()),!e&&"undefined"!=typeof Promise)return new Promise(function(e){o=e})}}();ni="undefined"!=typeof Set&&b(Set)?Set:function(){function e(){this.set=Object.create(null)}return e.prototype.has=function(e){return this.set[e]===!0},e.prototype.add=function(e){this.set[e]=!0},e.prototype.clear=function(){this.set=Object.create(null)},e}();var Oi,Si=d,Ti=0,Ei=function(){this.id=Ti++,this.subs=[]};Ei.prototype.addSub=function(e){this.subs.push(e)},Ei.prototype.removeSub=function(e){r(this.subs,e)},Ei.prototype.depend=function(){Ei.target&&Ei.target.addDep(this)},Ei.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;t<n;t++)e[t].update()},Ei.target=null;var Ii=[],ji=Array.prototype,Ni=Object.create(ji);["push","pop","shift","unshift","splice","sort","reverse"].forEach(function(e){var t=ji[e];y(Ni,e,function(){for(var n=arguments,r=arguments.length,i=new Array(r);r--;)i[r]=n[r];var o,a=t.apply(this,i),s=this.__ob__;switch(e){case"push":o=i;break;case"unshift":o=i;break;case"splice":o=i.slice(2)}return o&&s.observeArray(o),s.dep.notify(),a})});var Li=Object.getOwnPropertyNames(Ni),Mi={shouldConvert:!0,isSettingProps:!1},Di=function(e){if(this.value=e,this.dep=new Ei,this.vmCount=0,y(e,"__ob__",this),Array.isArray(e)){var t=mi?C:x;t(e,Ni,Li),this.observeArray(e)}else this.walk(e)};Di.prototype.walk=function(e){for(var t=Object.keys(e),n=0;n<t.length;n++)A(e,t[n],e[t[n]])},Di.prototype.observeArray=function(e){for(var t=0,n=e.length;t<n;t++)k(e[t])};var Pi=vi.optionMergeStrategies;Pi.data=function(e,t,n){return n?e||t?function(){var r="function"==typeof t?t.call(n):t,i="function"==typeof e?e.call(n):void 0;return r?E(r,i):i}:void 0:t?"function"!=typeof t?e:e?function(){return E(t.call(this),e.call(this))}:t:e},vi._lifecycleHooks.forEach(function(e){Pi[e]=I}),vi._assetTypes.forEach(function(e){Pi[e+"s"]=j}),Pi.watch=function(e,t){if(!t)return e;if(!e)return t;var n={};u(n,e);for(var r in t){var i=n[r],o=t[r];i&&!Array.isArray(i)&&(i=[i]),n[r]=i?i.concat(o):[o]}return n},Pi.props=Pi.methods=Pi.computed=function(e,t){if(!t)return e;if(!e)return t;var n=Object.create(null);return u(n,e),u(n,t),n};var Ri=function(e,t){return void 0===t?e:t},Fi=Object.freeze({defineReactive:A,_toString:e,toNumber:t,makeMap:n,isBuiltInTag:ri,remove:r,hasOwn:i,isPrimitive:o,cached:a,camelize:ai,capitalize:si,hyphenate:ui,bind:s,toArray:c,extend:u,isObject:l,isPlainObject:f,toObject:p,noop:d,no:pi,identity:di,genStaticKeys:v,looseEqual:h,looseIndexOf:m,isReserved:g,def:y,parsePath:_,hasProto:mi,inBrowser:gi,UA:yi,isIE:_i,isIE9:bi,isEdge:$i,isAndroid:wi,isIOS:Ci,isServerRendering:xi,devtools:ki,nextTick:Ai,get _Set(){return ni},mergeOptions:M,resolveAsset:D,warn:Si,formatComponentName:Oi,validateProp:P}),Hi=function(e,t,n,r,i,o,a){this.tag=e,this.data=t,this.children=n,this.text=r,this.elm=i,this.ns=void 0,this.context=o,this.functionalContext=void 0,this.key=t&&t.key,this.componentOptions=a,this.componentInstance=void 0,this.parent=void 0,this.raw=!1,this.isStatic=!1,this.isRootInsert=!0,this.isComment=!1,this.isCloned=!1,this.isOnce=!1},Ui={child:{}};Ui.child.get=function(){return this.componentInstance},Object.defineProperties(Hi.prototype,Ui);var Bi,zi=function(){var e=new Hi;return e.text="",e.isComment=!0,e},Vi={init:q,prepatch:W,insert:Z,destroy:G},Ji=Object.keys(Vi),Ki=a(function(e){var t="~"===e.charAt(0);e=t?e.slice(1):e;var n="!"===e.charAt(0);return e=n?e.slice(1):e,{name:e,once:t,capture:n}}),qi=1,Wi=2,Zi=null,Gi=[],Yi={},Qi=!1,Xi=!1,eo=0,to=0,no=function(e,t,n,r){this.vm=e,e._watchers.push(this),r?(this.deep=!!r.deep,this.user=!!r.user,this.lazy=!!r.lazy,this.sync=!!r.sync):this.deep=this.user=this.lazy=this.sync=!1,this.cb=n,this.id=++to,this.active=!0,this.dirty=this.lazy,this.deps=[],this.newDeps=[],this.depIds=new ni,this.newDepIds=new ni,this.expression="","function"==typeof t?this.getter=t:(this.getter=_(t),this.getter||(this.getter=function(){})),this.value=this.lazy?void 0:this.get()};no.prototype.get=function(){$(this);var e=this.getter.call(this.vm,this.vm);return this.deep&&Ae(e),w(),this.cleanupDeps(),e},no.prototype.addDep=function(e){var t=e.id;this.newDepIds.has(t)||(this.newDepIds.add(t),this.newDeps.push(e),this.depIds.has(t)||e.addSub(this))},no.prototype.cleanupDeps=function(){for(var e=this,t=this.deps.length;t--;){var n=e.deps[t];e.newDepIds.has(n.id)||n.removeSub(e)}var r=this.depIds;this.depIds=this.newDepIds,this.newDepIds=r,this.newDepIds.clear(),r=this.deps,this.deps=this.newDeps,this.newDeps=r,this.newDeps.length=0},no.prototype.update=function(){this.lazy?this.dirty=!0:this.sync?this.run():ke(this)},no.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||l(e)||this.deep){var t=this.value;if(this.value=e,this.user)try{this.cb.call(this.vm,e,t)}catch(e){if(!vi.errorHandler)throw e;vi.errorHandler.call(null,e,this.vm)}else this.cb.call(this.vm,e,t)}}},no.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},no.prototype.depend=function(){for(var e=this,t=this.deps.length;t--;)e.deps[t].depend()},no.prototype.teardown=function(){var e=this;if(this.active){this.vm._isBeingDestroyed||r(this.vm._watchers,this);for(var t=this.deps.length;t--;)e.deps[t].removeSub(e);this.active=!1}};var ro=new ni,io={enumerable:!0,configurable:!0,get:d,set:d},oo=0;Re(Ue),De(Ue),_e(Ue),$e(Ue),de(Ue);var ao=[String,RegExp],so={name:"keep-alive",abstract:!0,props:{include:ao,exclude:ao},created:function(){this.cache=Object.create(null)},destroyed:function(){var e=this;for(var t in this.cache)Ze(e.cache[t])},watch:{include:function(e){We(this.cache,function(t){return qe(e,t)})},exclude:function(e){We(this.cache,function(t){return!qe(e,t)})}},render:function(){var e=ce(this.$slots.default),t=e&&e.componentOptions;if(t){var n=Ke(t);if(n&&(this.include&&!qe(this.include,n)||this.exclude&&qe(this.exclude,n)))return e;var r=null==e.key?t.Ctor.cid+(t.tag?"::"+t.tag:""):e.key;this.cache[r]?e.componentInstance=this.cache[r].componentInstance:this.cache[r]=e,e.data.keepAlive=!0}return e}},co={KeepAlive:so};Ge(Ue),Object.defineProperty(Ue.prototype,"$isServer",{get:xi}),Ue.version="2.1.10";var uo,lo,fo=n("input,textarea,option,select"),po=function(e,t,n){return"value"===n&&fo(e)&&"button"!==t||"selected"===n&&"option"===e||"checked"===n&&"input"===e||"muted"===n&&"video"===e},vo=n("contenteditable,draggable,spellcheck"),ho=n("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),mo="http://www.w3.org/1999/xlink",go=function(e){return":"===e.charAt(5)&&"xlink"===e.slice(0,5)},yo=function(e){return go(e)?e.slice(6,e.length):""},_o=function(e){return null==e||e===!1},bo={svg:"http://www.w3.org/2000/svg",math:"http://www.w3.org/1998/Math/MathML"},$o=n("html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template"),wo=n("svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view",!0),Co=function(e){return"pre"===e},xo=function(e){return $o(e)||wo(e)},ko=Object.create(null),Ao=Object.freeze({createElement:ot,createElementNS:at,createTextNode:st,createComment:ct,insertBefore:ut,removeChild:lt,appendChild:ft,parentNode:pt,nextSibling:dt,tagName:vt,setTextContent:ht,setAttribute:mt}),Oo={create:function(e,t){gt(t)},update:function(e,t){e.data.ref!==t.data.ref&&(gt(e,!0),gt(t))},destroy:function(e){gt(e,!0)}},So=new Hi("",{},[]),To=["create","activate","update","remove","destroy"],Eo={create:Ct, update:Ct,destroy:function(e){Ct(e,So)}},Io=Object.create(null),jo=[Oo,Eo],No={create:St,update:St},Lo={create:Et,update:Et},Mo={create:Nt,update:Nt},Do={create:Lt,update:Lt},Po=a(function(e){var t={},n=/;(?![^(]*\))/g,r=/:(.+)/;return e.split(n).forEach(function(e){if(e){var n=e.split(r);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}),Ro=/^--/,Fo=/\s*!important$/,Ho=function(e,t,n){Ro.test(t)?e.style.setProperty(t,n):Fo.test(n)?e.style.setProperty(t,n.replace(Fo,""),"important"):e.style[Bo(t)]=n},Uo=["Webkit","Moz","ms"],Bo=a(function(e){if(lo=lo||document.createElement("div"),e=ai(e),"filter"!==e&&e in lo.style)return e;for(var t=e.charAt(0).toUpperCase()+e.slice(1),n=0;n<Uo.length;n++){var r=Uo[n]+t;if(r in lo.style)return r}}),zo={create:Ut,update:Ut},Vo=gi&&!bi,Jo="transition",Ko="animation",qo="transition",Wo="transitionend",Zo="animation",Go="animationend";Vo&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(qo="WebkitTransition",Wo="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Zo="WebkitAnimation",Go="webkitAnimationEnd"));var Yo=gi&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout,Qo=/\b(transform|all)(,|$)/,Xo=a(function(e){return{enterClass:e+"-enter",leaveClass:e+"-leave",appearClass:e+"-enter",enterToClass:e+"-enter-to",leaveToClass:e+"-leave-to",appearToClass:e+"-enter-to",enterActiveClass:e+"-enter-active",leaveActiveClass:e+"-leave-active",appearActiveClass:e+"-enter-active"}}),ea=gi?{create:tn,activate:tn,remove:function(e,t){e.data.show?t():Qt(e,t)}}:{},ta=[No,Lo,Mo,Do,zo,ea],na=ta.concat(jo),ra=wt({nodeOps:Ao,modules:na});bi&&document.addEventListener("selectionchange",function(){var e=document.activeElement;e&&e.vmodel&&cn(e,"input")});var ia={inserted:function(e,t,n){if("select"===n.tag){var r=function(){nn(e,t,n.context)};r(),(_i||$i)&&setTimeout(r,0)}else"textarea"!==n.tag&&"text"!==e.type||(e._vModifiers=t.modifiers,t.modifiers.lazy||(wi||(e.addEventListener("compositionstart",an),e.addEventListener("compositionend",sn)),bi&&(e.vmodel=!0)))},componentUpdated:function(e,t,n){if("select"===n.tag){nn(e,t,n.context);var r=e.multiple?t.value.some(function(t){return rn(t,e.options)}):t.value!==t.oldValue&&rn(t.value,e.options);r&&cn(e,"change")}}},oa={bind:function(e,t,n){var r=t.value;n=un(n);var i=n.data&&n.data.transition,o=e.__vOriginalDisplay="none"===e.style.display?"":e.style.display;r&&i&&!bi?(n.data.show=!0,Yt(n,function(){e.style.display=o})):e.style.display=r?o:"none"},update:function(e,t,n){var r=t.value,i=t.oldValue;if(r!==i){n=un(n);var o=n.data&&n.data.transition;o&&!bi?(n.data.show=!0,r?Yt(n,function(){e.style.display=e.__vOriginalDisplay}):Qt(n,function(){e.style.display="none"})):e.style.display=r?e.__vOriginalDisplay:"none"}},unbind:function(e,t,n,r,i){i||(e.style.display=e.__vOriginalDisplay)}},aa={model:ia,show:oa},sa={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String},ca={name:"transition",props:sa,abstract:!0,render:function(e){var t=this,n=this.$slots.default;if(n&&(n=n.filter(function(e){return e.tag}),n.length)){var r=this.mode,i=n[0];if(dn(this.$vnode))return i;var a=ln(i);if(!a)return i;if(this._leaving)return pn(e,i);var s="__transition-"+this._uid+"-",c=a.key=null==a.key?s+a.tag:o(a.key)?0===String(a.key).indexOf(s)?a.key:s+a.key:a.key,l=(a.data||(a.data={})).transition=fn(this),f=this._vnode,p=ln(f);if(a.data.directives&&a.data.directives.some(function(e){return"show"===e.name})&&(a.data.show=!0),p&&p.data&&!vn(a,p)){var d=p&&(p.data.transition=u({},l));if("out-in"===r)return this._leaving=!0,ne(d,"afterLeave",function(){t._leaving=!1,t.$forceUpdate()},c),pn(e,i);if("in-out"===r){var v,h=function(){v()};ne(l,"afterEnter",h,c),ne(l,"enterCancelled",h,c),ne(d,"delayLeave",function(e){v=e},c)}}return i}}},ua=u({tag:String,moveClass:String},sa);delete ua.mode;var la={props:ua,render:function(e){for(var t=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=fn(this),s=0;s<i.length;s++){var c=i[s];c.tag&&null!=c.key&&0!==String(c.key).indexOf("__vlist")&&(o.push(c),n[c.key]=c,(c.data||(c.data={})).transition=a)}if(r){for(var u=[],l=[],f=0;f<r.length;f++){var p=r[f];p.data.transition=a,p.data.pos=p.elm.getBoundingClientRect(),n[p.key]?u.push(p):l.push(p)}this.kept=e(t,null,u),this.removed=l}return e(t,null,o)},beforeUpdate:function(){this.__patch__(this._vnode,this.kept,!1,!0),this._vnode=this.kept},updated:function(){var e=this.prevChildren,t=this.moveClass||(this.name||"v")+"-move";if(e.length&&this.hasMove(e[0].elm,t)){e.forEach(hn),e.forEach(mn),e.forEach(gn);document.body.offsetHeight;e.forEach(function(e){if(e.data.moved){var n=e.elm,r=n.style;Jt(n,t),r.transform=r.WebkitTransform=r.transitionDuration="",n.addEventListener(Wo,n._moveCb=function e(r){r&&!/transform$/.test(r.propertyName)||(n.removeEventListener(Wo,e),n._moveCb=null,Kt(n,t))})}})}},methods:{hasMove:function(e,t){if(!Vo)return!1;if(null!=this._hasMove)return this._hasMove;Jt(e,t);var n=Wt(e);return Kt(e,t),this._hasMove=n.hasTransform}}},fa={Transition:ca,TransitionGroup:la};Ue.config.isUnknownElement=rt,Ue.config.isReservedTag=xo,Ue.config.getTagNamespace=nt,Ue.config.mustUseProp=po,u(Ue.options.directives,aa),u(Ue.options.components,fa),Ue.prototype.__patch__=gi?ra:d,Ue.prototype.$mount=function(e,t){return e=e&&gi?it(e):void 0,this._mount(e,t)},setTimeout(function(){vi.devtools&&ki&&ki.emit("init",Ue)},0);var pa,da=!!gi&&yn("\n","&#10;"),va=n("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr",!0),ha=n("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source",!0),ma=n("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track",!0),ga=/([^\s"'<>\/=]+)/,ya=/(?:=)/,_a=[/"([^"]*)"+/.source,/'([^']*)'+/.source,/([^\s"'=<>`]+)/.source],ba=new RegExp("^\\s*"+ga.source+"(?:\\s*("+ya.source+")\\s*(?:"+_a.join("|")+"))?"),$a="[a-zA-Z_][\\w\\-\\.]*",wa="((?:"+$a+"\\:)?"+$a+")",Ca=new RegExp("^<"+wa),xa=/^\s*(\/?)>/,ka=new RegExp("^<\\/"+wa+"[^>]*>"),Aa=/^<!DOCTYPE [^>]+>/i,Oa=/^<!--/,Sa=/^<!\[/,Ta=!1;"x".replace(/x(.)?/g,function(e,t){Ta=""===t});var Ea,Ia,ja,Na,La,Ma,Da,Pa,Ra,Fa,Ha,Ua,Ba,za,Va,Ja,Ka,qa,Wa,Za,Ga,Ya,Qa,Xa,es,ts=n("script,style",!0),ns={},rs=/&lt;/g,is=/&gt;/g,os=/&#10;/g,as=/&amp;/g,ss=/&quot;/g,cs=/\{\{((?:.|\n)+?)\}\}/g,us=/[-.*+?^${}()|[\]\/\\]/g,ls=a(function(e){var t=e[0].replace(us,"\\$&"),n=e[1].replace(us,"\\$&");return new RegExp(t+"((?:.|\\n)+?)"+n,"g")}),fs=/^v-|^@|^:/,ps=/(.*?)\s+(?:in|of)\s+(.*)/,ds=/\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/,vs=/^:|^v-bind:/,hs=/^@|^v-on:/,ms=/:(.*)$/,gs=/\.[^.]+/g,ys=a(_n),_s=/^xmlns:NS\d+/,bs=/^NS\d+:/,$s=a(or),ws=/^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/,Cs=/^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/,xs={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},ks={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:"if($event.target !== $event.currentTarget)return;",ctrl:"if(!$event.ctrlKey)return;",shift:"if(!$event.shiftKey)return;",alt:"if(!$event.altKey)return;",meta:"if(!$event.metaKey)return;"},As={bind:hr,cloak:d},Os={staticKeys:["staticClass"],transformNode:Fr,genData:Hr},Ss={staticKeys:["staticStyle"],transformNode:Ur,genData:Br},Ts=[Os,Ss],Es={model:zr,text:Zr,html:Gr},Is=Object.create(null),js={expectHTML:!0,modules:Ts,staticKeys:v(Ts),directives:Es,isReservedTag:xo,isUnaryTag:va,mustUseProp:po,getTagNamespace:nt,isPreTag:Co},Ns=a(function(e){var t=it(e);return t&&t.innerHTML}),Ls=Ue.prototype.$mount;return Ue.prototype.$mount=function(e,t){if(e=e&&it(e),e===document.body||e===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=Ns(r));else{if(!r.nodeType)return this;r=r.innerHTML}else e&&(r=ei(e));if(r){var i=Qr(r,{warn:Si,shouldDecodeNewlines:da,delimiters:n.delimiters},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return Ls.call(this,e,t)},Ue.compile=Qr,Ue});
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/compiler/directives/model.js
127
/* @flow */ /** * Cross-platform code generation for component v-model */ export function genComponentModel ( el: ASTElement, value: string, modifiers: ?ASTModifiers ): ?boolean { const { number, trim } = modifiers || {} let valueExpression = 'value' if (trim) { valueExpression = `(typeof value === 'string' ? value.trim() : value)` } if (number) { valueExpression = `_n(${valueExpression})` } el.model = { value: `(${value})`, callback: `function (value) {${genAssignmentCode(value, valueExpression)}}` } } /** * Cross-platform codegen helper for generating v-model value assignment code. */ export function genAssignmentCode ( value: string, assignment: string ): string { const modelRs = parseModel(value) if (modelRs.idx === null) { return `${value}=${assignment}` } else { return `var $$exp = ${modelRs.exp}, $$idx = ${modelRs.idx};` + `if (!Array.isArray($$exp)){` + `${value}=${assignment}}` + `else{$$exp.splice($$idx, 1, ${assignment})}` } } /** * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val) * * for loop possible cases: * * - test * - test[idx] * - test[test1[idx]] * - test["a"][idx] * - xxx.test[a[a].test1[idx]] * - test.xxx.a["asa"][test1[idx]] * */ let len, str, chr, index, expressionPos, expressionEndPos export function parseModel (val: string): Object { str = val len = str.length index = expressionPos = expressionEndPos = 0 if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { return { exp: val, idx: null } } while (!eof()) { chr = next() /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr) } else if (chr === 0x5B) { parseBracket(chr) } } return { exp: val.substring(0, expressionPos), idx: val.substring(expressionPos + 1, expressionEndPos) } } function next (): number { return str.charCodeAt(++index) } function eof (): boolean { return index >= len } function isStringStart (chr: number): boolean { return chr === 0x22 || chr === 0x27 } function parseBracket (chr: number): void { let inBracket = 1 expressionPos = index while (!eof()) { chr = next() if (isStringStart(chr)) { parseString(chr) continue } if (chr === 0x5B) inBracket++ if (chr === 0x5D) inBracket-- if (inBracket === 0) { expressionEndPos = index break } } } function parseString (chr: number): void { const stringQuote = chr while (!eof()) { chr = next() if (chr === stringQuote) { break } } }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/platforms/weex/runtime/modules/transition.js
265
import { warn } from 'core/util/debug' import { extend, once, noop } from 'shared/util' import { activeInstance } from 'core/instance/lifecycle' import { resolveTransition } from 'web/runtime/transition-util' export default { create: enter, activate: enter, remove: leave } function enter (_, vnode) { const el = vnode.elm // call leave callback now if (el._leaveCb) { el._leaveCb.cancelled = true el._leaveCb() } const data = resolveTransition(vnode.data.transition) if (!data) { return } /* istanbul ignore if */ if (el._enterCb) { return } const { enterClass, enterToClass, enterActiveClass, appearClass, appearToClass, appearActiveClass, beforeEnter, enter, afterEnter, enterCancelled, beforeAppear, appear, afterAppear, appearCancelled } = data let context = activeInstance let transitionNode = activeInstance.$vnode while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent context = transitionNode.context } const isAppear = !context._isMounted || !vnode.isRootInsert if (isAppear && !appear && appear !== '') { return } const startClass = isAppear ? appearClass : enterClass const toClass = isAppear ? appearToClass : enterToClass const activeClass = isAppear ? appearActiveClass : enterActiveClass const beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter const enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter const afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter const enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled const userWantsControl = enterHook && // enterHook may be a bound method which exposes // the length of original fn as _length (enterHook._length || enterHook.length) > 1 const stylesheet = vnode.context.$options.style || {} const startState = stylesheet[startClass] const transitionProperties = (stylesheet['@TRANSITION'] && stylesheet['@TRANSITION'][activeClass]) || {} const endState = getEnterTargetState(el, stylesheet, startClass, toClass, activeClass, vnode.context) const needAnimation = Object.keys(endState).length > 0 const cb = el._enterCb = once(() => { if (cb.cancelled) { enterCancelledHook && enterCancelledHook(el) } else { afterEnterHook && afterEnterHook(el) } el._enterCb = null }) // We need to wait until the native element has been inserted, but currently // there's no API to do that. So we have to wait "one frame" - not entirely // sure if this is guaranteed to be enough (e.g. on slow devices?) setTimeout(() => { const parent = el.parentNode const pendingNode = parent && parent._pending && parent._pending[vnode.key] if (pendingNode && pendingNode.context === vnode.context && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb) { pendingNode.elm._leaveCb() } enterHook && enterHook(el, cb) if (needAnimation) { const animation = vnode.context.$requireWeexModule('animation') animation.transition(el.ref, { styles: endState, duration: transitionProperties.duration || 0, delay: transitionProperties.delay || 0, timingFunction: transitionProperties.timingFunction || 'linear' }, userWantsControl ? noop : cb) } else if (!userWantsControl) { cb() } }, 16) // start enter transition beforeEnterHook && beforeEnterHook(el) if (startState) { for (const key in startState) { el.setStyle(key, startState[key]) } } if (!needAnimation && !userWantsControl) { cb() } } function leave (vnode, rm) { const el = vnode.elm // call enter callback now if (el._enterCb) { el._enterCb.cancelled = true el._enterCb() } const data = resolveTransition(vnode.data.transition) if (!data) { return rm() } if (el._leaveCb) { return } const { leaveClass, leaveToClass, leaveActiveClass, beforeLeave, leave, afterLeave, leaveCancelled, delayLeave } = data const userWantsControl = leave && // leave hook may be a bound method which exposes // the length of original fn as _length (leave._length || leave.length) > 1 const stylesheet = vnode.context.$options.style || {} const startState = stylesheet[leaveClass] const endState = stylesheet[leaveToClass] || stylesheet[leaveActiveClass] const transitionProperties = (stylesheet['@TRANSITION'] && stylesheet['@TRANSITION'][leaveActiveClass]) || {} const cb = el._leaveCb = once(() => { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null } if (cb.cancelled) { leaveCancelled && leaveCancelled(el) } else { rm() afterLeave && afterLeave(el) } el._leaveCb = null }) if (delayLeave) { delayLeave(performLeave) } else { performLeave() } function performLeave () { const animation = vnode.context.$requireWeexModule('animation') // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode } beforeLeave && beforeLeave(el) if (startState) { animation.transition(el.ref, { styles: startState }, next) } else { next() } function next () { animation.transition(el.ref, { styles: endState, duration: transitionProperties.duration || 0, delay: transitionProperties.delay || 0, timingFunction: transitionProperties.timingFunction || 'linear' }, userWantsControl ? noop : cb) } leave && leave(el, cb) if (!endState && !userWantsControl) { cb() } } } // determine the target animation style for an entering transition. function getEnterTargetState (el, stylesheet, startClass, endClass, activeClass, vm) { const targetState = {} const startState = stylesheet[startClass] const endState = stylesheet[endClass] const activeState = stylesheet[activeClass] // 1. fallback to element's default styling if (startState) { for (const key in startState) { targetState[key] = el.style[key] if ( process.env.NODE_ENV !== 'production' && targetState[key] == null && (!activeState || activeState[key] == null) && (!endState || endState[key] == null) ) { warn( `transition property "${key}" is declared in enter starting class (.${startClass}), ` + `but not declared anywhere in enter ending class (.${endClass}), ` + `enter active cass (.${activeClass}) or the element's default styling. ` + `Note in Weex, CSS properties need explicit values to be transitionable.` ) } } } // 2. if state is mixed in active state, extract them while excluding // transition properties if (activeState) { for (const key in activeState) { if (key.indexOf('transition') !== 0) { targetState[key] = activeState[key] } } } // 3. explicit endState has highest priority if (endState) { extend(targetState, endState) } return targetState }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/platforms/weex/runtime/components/transition-group.js
148
import { warn, extend } from 'core/util/index' import { transitionProps, extractTransitionData } from './transition' const props = extend({ tag: String, moveClass: String }, transitionProps) delete props.mode export default { props, created () { const dom = this.$requireWeexModule('dom') this.getPosition = el => new Promise((resolve, reject) => { dom.getComponentRect(el.ref, res => { if (!res.result) { reject(new Error(`failed to get rect for element: ${el.tag}`)) } else { resolve(res.size) } }) }) const animation = this.$requireWeexModule('animation') this.animate = (el, options) => new Promise(resolve => { animation.transition(el.ref, options, resolve) }) }, render (h) { const tag = this.tag || this.$vnode.data.tag || 'span' const map = Object.create(null) const prevChildren = this.prevChildren = this.children const rawChildren = this.$slots.default || [] const children = this.children = [] const transitionData = extractTransitionData(this) for (let i = 0; i < rawChildren.length; i++) { const c = rawChildren[i] if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c) map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData } else if (process.env.NODE_ENV !== 'production') { const opts = c.componentOptions const name = opts ? (opts.Ctor.options.name || opts.tag) : c.tag warn(`<transition-group> children must be keyed: <${name}>`) } } } if (prevChildren) { const kept = [] const removed = [] prevChildren.forEach(c => { c.data.transition = transitionData // TODO: record before patch positions if (map[c.key]) { kept.push(c) } else { removed.push(c) } }) this.kept = h(tag, null, kept) this.removed = removed } return h(tag, null, children) }, beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ) this._vnode = this.kept }, updated () { const children = this.prevChildren const moveClass = this.moveClass || ((this.name || 'v') + '-move') const moveData = children.length && this.getMoveData(children[0].context, moveClass) if (!moveData) { return } // TODO: finish implementing move animations once // we have access to sync getComponentRect() // children.forEach(callPendingCbs) // Promise.all(children.map(c => { // const oldPos = c.data.pos // const newPos = c.data.newPos // const dx = oldPos.left - newPos.left // const dy = oldPos.top - newPos.top // if (dx || dy) { // c.data.moved = true // return this.animate(c.elm, { // styles: { // transform: `translate(${dx}px,${dy}px)` // } // }) // } // })).then(() => { // children.forEach(c => { // if (c.data.moved) { // this.animate(c.elm, { // styles: { // transform: '' // }, // duration: moveData.duration || 0, // delay: moveData.delay || 0, // timingFunction: moveData.timingFunction || 'linear' // }) // } // }) // }) }, methods: { getMoveData (context, moveClass) { const stylesheet = context.$options.style || {} return stylesheet['@TRANSITION'] && stylesheet['@TRANSITION'][moveClass] } } } // function callPendingCbs (c) { // /* istanbul ignore if */ // if (c.elm._moveCb) { // c.elm._moveCb() // } // /* istanbul ignore if */ // if (c.elm._enterCb) { // c.elm._enterCb() // } // }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/entries/weex-factory.js
6
// this entry is built and wrapped with a factory function // used to generate a fresh copy of Vue for every Weex instance. import Vue from 'weex/runtime/index' exports.Vue = Vue
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
test/unit/modules/vdom/modules/events.spec.js
99
import { patch } from 'web/runtime/patch' import VNode from 'core/vdom/vnode' describe('vdom events module', () => { it('should attach event handler to element', () => { const click = jasmine.createSpy() const vnode = new VNode('a', { on: { click }}) const elm = patch(null, vnode) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) }) it('should not duplicate the same listener', () => { const click = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click }}) const vnode2 = new VNode('a', { on: { click }}) const elm = patch(null, vnode1) patch(vnode1, vnode2) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) }) it('should update different listener', () => { const click = jasmine.createSpy() const click2 = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click }}) const vnode2 = new VNode('a', { on: { click: click2 }}) const elm = patch(null, vnode1) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) expect(click2.calls.count()).toBe(0) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) expect(click2.calls.count()).toBe(1) }) it('should attach Array of multiple handlers', () => { const click = jasmine.createSpy() const vnode = new VNode('a', { on: { click: [click, click] }}) const elm = patch(null, vnode) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) }) it('should update Array of multiple handlers', () => { const click = jasmine.createSpy() const click2 = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click: [click, click2] }}) const vnode2 = new VNode('a', { on: { click: [click] }}) const elm = patch(null, vnode1) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) expect(click2.calls.count()).toBe(1) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) expect(click2.calls.count()).toBe(1) }) it('should remove handlers that are no longer present', () => { const click = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click }}) const vnode2 = new VNode('a', {}) const elm = patch(null, vnode1) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) }) it('should remove Array handlers that are no longer present', () => { const click = jasmine.createSpy() const vnode1 = new VNode('a', { on: { click: [click, click] }}) const vnode2 = new VNode('a', {}) const elm = patch(null, vnode1) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) }) // #4650 it('should handle single -> array or array -> single handler changes', () => { const click = jasmine.createSpy() const click2 = jasmine.createSpy() const click3 = jasmine.createSpy() const vnode0 = new VNode('a', { on: { click: click }}) const vnode1 = new VNode('a', { on: { click: [click, click2] }}) const vnode2 = new VNode('a', { on: { click: click }}) const vnode3 = new VNode('a', { on: { click: [click2, click3] }}) const elm = patch(null, vnode0) document.body.appendChild(elm) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(1) expect(click2.calls.count()).toBe(0) patch(vnode0, vnode1) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(2) expect(click2.calls.count()).toBe(1) patch(vnode1, vnode2) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(3) expect(click2.calls.count()).toBe(1) patch(vnode2, vnode3) triggerEvent(elm, 'click') expect(click.calls.count()).toBe(3) expect(click2.calls.count()).toBe(2) expect(click3.calls.count()).toBe(1) }) })
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
dist/vue.runtime.min.js
4
/*! * Vue.js v2.1.10 * (c) 2014-2017 Evan You * Released under the MIT License. */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.Vue=e()}(this,function(){"use strict";function t(t){return null==t?"":"object"==typeof t?JSON.stringify(t,null,2):String(t)}function e(t){var e=parseFloat(t);return isNaN(e)?t:e}function n(t,e){for(var n=Object.create(null),r=t.split(","),o=0;o<r.length;o++)n[r[o]]=!0;return e?function(t){return n[t.toLowerCase()]}:function(t){return n[t]}}function r(t,e){if(t.length){var n=t.indexOf(e);if(n>-1)return t.splice(n,1)}}function o(t,e){return Cn.call(t,e)}function i(t){return"string"==typeof t||"number"==typeof t}function a(t){var e=Object.create(null);return function(n){var r=e[n];return r||(e[n]=t(n))}}function s(t,e){function n(n){var r=arguments.length;return r?r>1?t.apply(e,arguments):t.call(e,n):t.call(e)}return n._length=t.length,n}function c(t,e){e=e||0;for(var n=t.length-e,r=new Array(n);n--;)r[n]=t[n+e];return r}function u(t,e){for(var n in e)t[n]=e[n];return t}function l(t){return null!==t&&"object"==typeof t}function f(t){return On.call(t)===Sn}function p(t){for(var e={},n=0;n<t.length;n++)t[n]&&u(e,t[n]);return e}function d(){}function v(t){return t.reduce(function(t,e){return t.concat(e.staticKeys||[])},[]).join(",")}function h(t,e){var n=l(t),r=l(e);return n&&r?JSON.stringify(t)===JSON.stringify(e):!n&&!r&&String(t)===String(e)}function m(t,e){for(var n=0;n<t.length;n++)if(h(t[n],e))return n;return-1}function y(t){var e=(t+"").charCodeAt(0);return 36===e||95===e}function _(t,e,n,r){Object.defineProperty(t,e,{value:n,enumerable:!!r,writable:!0,configurable:!0})}function g(t){if(!jn.test(t)){var e=t.split(".");return function(t){for(var n=0;n<e.length;n++){if(!t)return;t=t[e[n]]}return t}}}function b(t){return/native code/.test(t.toString())}function C(t){Wn.target&&Jn.push(Wn.target),Wn.target=t}function w(){Wn.target=Jn.pop()}function $(t,e){t.__proto__=e}function k(t,e,n){for(var r=0,o=n.length;r<o;r++){var i=n[r];_(t,i,e[i])}}function A(t,e){if(l(t)){var n;return o(t,"__ob__")&&t.__ob__ instanceof Yn?n=t.__ob__:Xn.shouldConvert&&!Vn()&&(Array.isArray(t)||f(t))&&Object.isExtensible(t)&&!t._isVue&&(n=new Yn(t)),e&&n&&n.vmCount++,n}}function x(t,e,n,r){var o=new Wn,i=Object.getOwnPropertyDescriptor(t,e);if(!i||i.configurable!==!1){var a=i&&i.get,s=i&&i.set,c=A(n);Object.defineProperty(t,e,{enumerable:!0,configurable:!0,get:function(){var e=a?a.call(t):n;return Wn.target&&(o.depend(),c&&c.dep.depend(),Array.isArray(e)&&E(e)),e},set:function(e){var r=a?a.call(t):n;e===r||e!==e&&r!==r||(s?s.call(t,e):n=e,c=A(e),o.notify())}})}}function O(t,e,n){if(Array.isArray(t))return t.length=Math.max(t.length,e),t.splice(e,1,n),n;if(o(t,e))return void(t[e]=n);var r=t.__ob__;if(!(t._isVue||r&&r.vmCount))return r?(x(r.value,e,n),r.dep.notify(),n):void(t[e]=n)}function S(t,e){var n=t.__ob__;t._isVue||n&&n.vmCount||o(t,e)&&(delete t[e],n&&n.dep.notify())}function E(t){for(var e=void 0,n=0,r=t.length;n<r;n++)e=t[n],e&&e.__ob__&&e.__ob__.dep.depend(),Array.isArray(e)&&E(e)}function I(t,e){if(!e)return t;for(var n,r,i,a=Object.keys(e),s=0;s<a.length;s++)n=a[s],r=t[n],i=e[n],o(t,n)?f(r)&&f(i)&&I(r,i):O(t,n,i);return t}function T(t,e){return e?t?t.concat(e):Array.isArray(e)?e:[e]:t}function j(t,e){var n=Object.create(t||null);return e?u(n,e):n}function D(t){var e=t.props;if(e){var n,r,o,i={};if(Array.isArray(e))for(n=e.length;n--;)r=e[n],"string"==typeof r&&(o=$n(r),i[o]={type:null});else if(f(e))for(var a in e)r=e[a],o=$n(a),i[o]=f(r)?r:{type:r};t.props=i}}function P(t){var e=t.directives;if(e)for(var n in e){var r=e[n];"function"==typeof r&&(e[n]={bind:r,update:r})}}function N(t,e,n){function r(r){var o=tr[r]||er;l[r]=o(t[r],e[r],n,r)}D(e),P(e);var i=e.extends;if(i&&(t="function"==typeof i?N(t,i.options,n):N(t,i,n)),e.mixins)for(var a=0,s=e.mixins.length;a<s;a++){var c=e.mixins[a];c.prototype instanceof Vt&&(c=c.options),t=N(t,c,n)}var u,l={};for(u in t)r(u);for(u in e)o(t,u)||r(u);return l}function L(t,e,n,r){if("string"==typeof n){var i=t[e];if(o(i,n))return i[n];var a=$n(n);if(o(i,a))return i[a];var s=kn(a);if(o(i,s))return i[s];var c=i[n]||i[a]||i[s];return c}}function M(t,e,n,r){var i=e[t],a=!o(n,t),s=n[t];if(B(Boolean,i.type)&&(a&&!o(i,"default")?s=!1:B(String,i.type)||""!==s&&s!==xn(t)||(s=!0)),void 0===s){s=U(r,i,t);var c=Xn.shouldConvert;Xn.shouldConvert=!0,A(s),Xn.shouldConvert=c}return s}function U(t,e,n){if(o(e,"default")){var r=e.default;return l(r),t&&t.$options.propsData&&void 0===t.$options.propsData[n]&&void 0!==t[n]?t[n]:"function"==typeof r&&e.type!==Function?r.call(t):r}}function R(t){var e=t&&t.toString().match(/^\s*function (\w+)/);return e&&e[1]}function B(t,e){if(!Array.isArray(e))return R(e)===R(t);for(var n=0,r=e.length;n<r;n++)if(R(e[n])===R(t))return!0;return!1}function V(t){return new rr(void 0,void 0,void 0,String(t))}function H(t){var e=new rr(t.tag,t.data,t.children,t.text,t.elm,t.context,t.componentOptions);return e.ns=t.ns,e.isStatic=t.isStatic,e.key=t.key,e.isCloned=!0,e}function F(t){for(var e=new Array(t.length),n=0;n<t.length;n++)e[n]=H(t[n]);return e}function z(t,e,n,r,o){if(t){var i=n.$options._base;if(l(t)&&(t=i.extend(t)),"function"==typeof t){if(!t.cid)if(t.resolved)t=t.resolved;else if(t=Q(t,i,function(){n.$forceUpdate()}),!t)return;Bt(t),e=e||{};var a=X(e,t);if(t.options.functional)return q(t,a,e,n,r);var s=e.on;e.on=e.nativeOn,t.options.abstract&&(e={}),tt(e);var c=t.options.name||o,u=new rr("vue-component-"+t.cid+(c?"-"+c:""),e,void 0,void 0,void 0,n,{Ctor:t,propsData:a,listeners:s,tag:o,children:r});return u}}}function q(t,e,n,r,o){var i={},a=t.options.props;if(a)for(var s in a)i[s]=M(s,a,e);var c=Object.create(r),u=function(t,e,n,r){return ut(c,t,e,n,r,!0)},l=t.options.render.call(null,u,{props:i,data:n,parent:r,children:o,slots:function(){return vt(o,r)}});return l instanceof rr&&(l.functionalContext=r,n.slot&&((l.data||(l.data={})).slot=n.slot)),l}function K(t,e,n,r){var o=t.componentOptions,i={_isComponent:!0,parent:e,propsData:o.propsData,_componentTag:o.tag,_parentVnode:t,_parentListeners:o.listeners,_renderChildren:o.children,_parentElm:n||null,_refElm:r||null},a=t.data.inlineTemplate;return a&&(i.render=a.render,i.staticRenderFns=a.staticRenderFns),new o.Ctor(i)}function W(t,e,n,r){if(!t.componentInstance||t.componentInstance._isDestroyed){var o=t.componentInstance=K(t,pr,n,r);o.$mount(e?t.elm:void 0,e)}else if(t.data.keepAlive){var i=t;J(i,i)}}function J(t,e){var n=e.componentOptions,r=e.componentInstance=t.componentInstance;r._updateFromParent(n.propsData,n.listeners,e,n.children)}function G(t){t.componentInstance._isMounted||(t.componentInstance._isMounted=!0,wt(t.componentInstance,"mounted")),t.data.keepAlive&&(t.componentInstance._inactive=!1,wt(t.componentInstance,"activated"))}function Z(t){t.componentInstance._isDestroyed||(t.data.keepAlive?(t.componentInstance._inactive=!0,wt(t.componentInstance,"deactivated")):t.componentInstance.$destroy())}function Q(t,e,n){if(!t.requested){t.requested=!0;var r=t.pendingCallbacks=[n],o=!0,i=function(n){if(l(n)&&(n=e.extend(n)),t.resolved=n,!o)for(var i=0,a=r.length;i<a;i++)r[i](n)},a=function(t){},s=t(i,a);return s&&"function"==typeof s.then&&!t.resolved&&s.then(i,a),o=!1,t.resolved}t.pendingCallbacks.push(n)}function X(t,e){var n=e.options.props;if(n){var r={},o=t.attrs,i=t.props,a=t.domProps;if(o||i||a)for(var s in n){var c=xn(s);Y(r,i,s,c,!0)||Y(r,o,s,c)||Y(r,a,s,c)}return r}}function Y(t,e,n,r,i){if(e){if(o(e,n))return t[n]=e[n],i||delete e[n],!0;if(o(e,r))return t[n]=e[r],i||delete e[r],!0}return!1}function tt(t){t.hook||(t.hook={});for(var e=0;e<cr.length;e++){var n=cr[e],r=t.hook[n],o=sr[n];t.hook[n]=r?et(o,r):o}}function et(t,e){return function(n,r,o,i){t(n,r,o,i),e(n,r,o,i)}}function nt(t,e,n,r){r+=e;var o=t.__injected||(t.__injected={});if(!o[r]){o[r]=!0;var i=t[e];i?t[e]=function(){i.apply(this,arguments),n.apply(this,arguments)}:t[e]=n}}function rt(t){var e={fn:t,invoker:function(){var t=arguments,n=e.fn;if(Array.isArray(n))for(var r=0;r<n.length;r++)n[r].apply(null,t);else n.apply(null,arguments)}};return e}function ot(t,e,n,r,o){var i,a,s,c;for(i in t)a=t[i],s=e[i],c=ur(i),a&&(s?a!==s&&(s.fn=a,t[i]=s):(a.invoker||(a=t[i]=rt(a)),n(c.name,a.invoker,c.once,c.capture)));for(i in e)t[i]||(c=ur(i),r(c.name,e[i].invoker,c.capture))}function it(t){for(var e=0;e<t.length;e++)if(Array.isArray(t[e]))return Array.prototype.concat.apply([],t);return t}function at(t){return i(t)?[V(t)]:Array.isArray(t)?st(t):void 0}function st(t,e){var n,r,o,a=[];for(n=0;n<t.length;n++)r=t[n],null!=r&&"boolean"!=typeof r&&(o=a[a.length-1],Array.isArray(r)?a.push.apply(a,st(r,(e||"")+"_"+n)):i(r)?o&&o.text?o.text+=String(r):""!==r&&a.push(V(r)):r.text&&o&&o.text?a[a.length-1]=V(o.text+r.text):(r.tag&&null==r.key&&null!=e&&(r.key="__vlist"+e+"_"+n+"__"),a.push(r)));return a}function ct(t){return t&&t.filter(function(t){return t&&t.componentOptions})[0]}function ut(t,e,n,r,o,a){return(Array.isArray(n)||i(n))&&(o=r,r=n,n=void 0),a&&(o=fr),lt(t,e,n,r,o)}function lt(t,e,n,r,o){if(n&&n.__ob__)return ar();if(!e)return ar();Array.isArray(r)&&"function"==typeof r[0]&&(n=n||{},n.scopedSlots={default:r[0]},r.length=0),o===fr?r=at(r):o===lr&&(r=it(r));var i,a;if("string"==typeof e){var s;a=Tn.getTagNamespace(e),i=Tn.isReservedTag(e)?new rr(Tn.parsePlatformTagName(e),n,r,void 0,void 0,t):(s=L(t.$options,"components",e))?z(s,n,t,r,e):new rr(e,n,r,void 0,void 0,t)}else i=z(e,n,t,r);return i?(a&&ft(i,a),i):ar()}function ft(t,e){if(t.ns=e,"foreignObject"!==t.tag&&t.children)for(var n=0,r=t.children.length;n<r;n++){var o=t.children[n];o.tag&&!o.ns&&ft(o,e)}}function pt(t){t.$vnode=null,t._vnode=null,t._staticTrees=null;var e=t.$options._parentVnode,n=e&&e.context;t.$slots=vt(t.$options._renderChildren,n),t.$scopedSlots={},t._c=function(e,n,r,o){return ut(t,e,n,r,o,!1)},t.$createElement=function(e,n,r,o){return ut(t,e,n,r,o,!0)}}function dt(n){function r(t,e,n){if(Array.isArray(t))for(var r=0;r<t.length;r++)t[r]&&"string"!=typeof t[r]&&o(t[r],e+"_"+r,n);else o(t,e,n)}function o(t,e,n){t.isStatic=!0,t.key=e,t.isOnce=n}n.prototype.$nextTick=function(t){return Fn(t,this)},n.prototype._render=function(){var t=this,e=t.$options,n=e.render,r=e.staticRenderFns,o=e._parentVnode;if(t._isMounted)for(var i in t.$slots)t.$slots[i]=F(t.$slots[i]);o&&o.data.scopedSlots&&(t.$scopedSlots=o.data.scopedSlots),r&&!t._staticTrees&&(t._staticTrees=[]),t.$vnode=o;var a;try{a=n.call(t._renderProxy,t.$createElement)}catch(e){if(!Tn.errorHandler)throw e;Tn.errorHandler.call(null,e,t),a=t._vnode}return a instanceof rr||(a=ar()),a.parent=o,a},n.prototype._s=t,n.prototype._v=V,n.prototype._n=e,n.prototype._e=ar,n.prototype._q=h,n.prototype._i=m,n.prototype._m=function(t,e){var n=this._staticTrees[t];return n&&!e?Array.isArray(n)?F(n):H(n):(n=this._staticTrees[t]=this.$options.staticRenderFns[t].call(this._renderProxy),r(n,"__static__"+t,!1),n)},n.prototype._o=function(t,e,n){return r(t,"__once__"+e+(n?"_"+n:""),!0),t},n.prototype._f=function(t){return L(this.$options,"filters",t,!0)||In},n.prototype._l=function(t,e){var n,r,o,i,a;if(Array.isArray(t)||"string"==typeof t)for(n=new Array(t.length),r=0,o=t.length;r<o;r++)n[r]=e(t[r],r);else if("number"==typeof t)for(n=new Array(t),r=0;r<t;r++)n[r]=e(r+1,r);else if(l(t))for(i=Object.keys(t),n=new Array(i.length),r=0,o=i.length;r<o;r++)a=i[r],n[r]=e(t[a],a,r);return n},n.prototype._t=function(t,e,n,r){var o=this.$scopedSlots[t];if(o)return n=n||{},r&&u(n,r),o(n)||e;var i=this.$slots[t];return i||e},n.prototype._b=function(t,e,n,r){if(n)if(l(n)){Array.isArray(n)&&(n=p(n));for(var o in n)if("class"===o||"style"===o)t[o]=n[o];else{var i=t.attrs&&t.attrs.type,a=r||Tn.mustUseProp(e,i,o)?t.domProps||(t.domProps={}):t.attrs||(t.attrs={});a[o]=n[o]}}else;return t},n.prototype._k=function(t,e,n){var r=Tn.keyCodes[e]||n;return Array.isArray(r)?r.indexOf(t)===-1:r!==t}}function vt(t,e){var n={};if(!t)return n;for(var r,o,i=[],a=0,s=t.length;a<s;a++)if(o=t[a],(o.context===e||o.functionalContext===e)&&o.data&&(r=o.data.slot)){var c=n[r]||(n[r]=[]);"template"===o.tag?c.push.apply(c,o.children):c.push(o)}else i.push(o);return i.length&&(1!==i.length||" "!==i[0].text&&!i[0].isComment)&&(n.default=i),n}function ht(t){t._events=Object.create(null),t._hasHookEvent=!1;var e=t.$options._parentListeners;e&&_t(t,e)}function mt(t,e,n){n?ir.$once(t,e):ir.$on(t,e)}function yt(t,e){ir.$off(t,e)}function _t(t,e,n){ir=t,ot(e,n||{},mt,yt,t)}function gt(t){var e=/^hook:/;t.prototype.$on=function(t,n){var r=this;return(r._events[t]||(r._events[t]=[])).push(n),e.test(t)&&(r._hasHookEvent=!0),r},t.prototype.$once=function(t,e){function n(){r.$off(t,n),e.apply(r,arguments)}var r=this;return n.fn=e,r.$on(t,n),r},t.prototype.$off=function(t,e){var n=this;if(!arguments.length)return n._events=Object.create(null),n;var r=n._events[t];if(!r)return n;if(1===arguments.length)return n._events[t]=null,n;for(var o,i=r.length;i--;)if(o=r[i],o===e||o.fn===e){r.splice(i,1);break}return n},t.prototype.$emit=function(t){var e=this,n=e._events[t];if(n){n=n.length>1?c(n):n;for(var r=c(arguments,1),o=0,i=n.length;o<i;o++)n[o].apply(e,r)}return e}}function bt(t){var e=t.$options,n=e.parent;if(n&&!e.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(t)}t.$parent=n,t.$root=n?n.$root:t,t.$children=[],t.$refs={},t._watcher=null,t._inactive=!1,t._isMounted=!1,t._isDestroyed=!1,t._isBeingDestroyed=!1}function Ct(t){t.prototype._mount=function(t,e){var n=this;return n.$el=t,n.$options.render||(n.$options.render=ar),wt(n,"beforeMount"),n._watcher=new gr(n,function(){n._update(n._render(),e)},d),e=!1,null==n.$vnode&&(n._isMounted=!0,wt(n,"mounted")),n},t.prototype._update=function(t,e){var n=this;n._isMounted&&wt(n,"beforeUpdate");var r=n.$el,o=n._vnode,i=pr;pr=n,n._vnode=t,o?n.$el=n.__patch__(o,t):n.$el=n.__patch__(n.$el,t,e,!1,n.$options._parentElm,n.$options._refElm),pr=i,r&&(r.__vue__=null),n.$el&&(n.$el.__vue__=n),n.$vnode&&n.$parent&&n.$vnode===n.$parent._vnode&&(n.$parent.$el=n.$el)},t.prototype._updateFromParent=function(t,e,n,r){var o=this,i=!(!o.$options._renderChildren&&!r);if(o.$options._parentVnode=n,o.$vnode=n,o._vnode&&(o._vnode.parent=n),o.$options._renderChildren=r,t&&o.$options.props){Xn.shouldConvert=!1;for(var a=o.$options._propKeys||[],s=0;s<a.length;s++){var c=a[s];o[c]=M(c,o.$options.props,t,o)}Xn.shouldConvert=!0,o.$options.propsData=t}if(e){var u=o.$options._parentListeners;o.$options._parentListeners=e,_t(o,e,u)}i&&(o.$slots=vt(r,n.context),o.$forceUpdate())},t.prototype.$forceUpdate=function(){var t=this;t._watcher&&t._watcher.update()},t.prototype.$destroy=function(){var t=this;if(!t._isBeingDestroyed){wt(t,"beforeDestroy"),t._isBeingDestroyed=!0;var e=t.$parent;!e||e._isBeingDestroyed||t.$options.abstract||r(e.$children,t),t._watcher&&t._watcher.teardown();for(var n=t._watchers.length;n--;)t._watchers[n].teardown();t._data.__ob__&&t._data.__ob__.vmCount--,t._isDestroyed=!0,wt(t,"destroyed"),t.$off(),t.$el&&(t.$el.__vue__=null),t.__patch__(t._vnode,null)}}}function wt(t,e){var n=t.$options[e];if(n)for(var r=0,o=n.length;r<o;r++)n[r].call(t);t._hasHookEvent&&t.$emit("hook:"+e)}function $t(){dr.length=0,vr={},hr=mr=!1}function kt(){mr=!0;var t,e,n;for(dr.sort(function(t,e){return t.id-e.id}),yr=0;yr<dr.length;yr++)t=dr[yr],e=t.id,vr[e]=null,t.run();for(yr=dr.length;yr--;)t=dr[yr],n=t.vm,n._watcher===t&&n._isMounted&&wt(n,"updated");Hn&&Tn.devtools&&Hn.emit("flush"),$t()}function At(t){var e=t.id;if(null==vr[e]){if(vr[e]=!0,mr){for(var n=dr.length-1;n>=0&&dr[n].id>t.id;)n--;dr.splice(Math.max(n,yr)+1,0,t)}else dr.push(t);hr||(hr=!0,Fn(kt))}}function xt(t){br.clear(),Ot(t,br)}function Ot(t,e){var n,r,o=Array.isArray(t);if((o||l(t))&&Object.isExtensible(t)){if(t.__ob__){var i=t.__ob__.dep.id;if(e.has(i))return;e.add(i)}if(o)for(n=t.length;n--;)Ot(t[n],e);else for(r=Object.keys(t),n=r.length;n--;)Ot(t[r[n]],e)}}function St(t){t._watchers=[];var e=t.$options;e.props&&Et(t,e.props),e.methods&&Dt(t,e.methods),e.data?It(t):A(t._data={},!0),e.computed&&Tt(t,e.computed),e.watch&&Pt(t,e.watch)}function Et(t,e){var n=t.$options.propsData||{},r=t.$options._propKeys=Object.keys(e),o=!t.$parent;Xn.shouldConvert=o;for(var i=function(o){var i=r[o];x(t,i,M(i,e,n,t))},a=0;a<r.length;a++)i(a);Xn.shouldConvert=!0}function It(t){var e=t.$options.data;e=t._data="function"==typeof e?e.call(t):e||{},f(e)||(e={});for(var n=Object.keys(e),r=t.$options.props,i=n.length;i--;)r&&o(r,n[i])||Mt(t,n[i]);A(e,!0)}function Tt(t,e){for(var n in e){var r=e[n];"function"==typeof r?(Cr.get=jt(r,t),Cr.set=d):(Cr.get=r.get?r.cache!==!1?jt(r.get,t):s(r.get,t):d,Cr.set=r.set?s(r.set,t):d),Object.defineProperty(t,n,Cr)}}function jt(t,e){var n=new gr(e,t,d,{lazy:!0});return function(){return n.dirty&&n.evaluate(),Wn.target&&n.depend(),n.value}}function Dt(t,e){for(var n in e)t[n]=null==e[n]?d:s(e[n],t)}function Pt(t,e){for(var n in e){var r=e[n];if(Array.isArray(r))for(var o=0;o<r.length;o++)Nt(t,n,r[o]);else Nt(t,n,r)}}function Nt(t,e,n){var r;f(n)&&(r=n,n=n.handler),"string"==typeof n&&(n=t[n]),t.$watch(e,n,r)}function Lt(t){var e={};e.get=function(){return this._data},Object.defineProperty(t.prototype,"$data",e),t.prototype.$set=O,t.prototype.$delete=S,t.prototype.$watch=function(t,e,n){var r=this;n=n||{},n.user=!0;var o=new gr(r,t,e,n);return n.immediate&&e.call(r,o.value),function(){o.teardown()}}}function Mt(t,e){y(e)||Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get:function(){return t._data[e]},set:function(n){t._data[e]=n}})}function Ut(t){t.prototype._init=function(t){var e=this;e._uid=wr++,e._isVue=!0,t&&t._isComponent?Rt(e,t):e.$options=N(Bt(e.constructor),t||{},e),e._renderProxy=e,e._self=e,bt(e),ht(e),pt(e),wt(e,"beforeCreate"),St(e),wt(e,"created"),e.$options.el&&e.$mount(e.$options.el)}}function Rt(t,e){var n=t.$options=Object.create(t.constructor.options);n.parent=e.parent,n.propsData=e.propsData,n._parentVnode=e._parentVnode,n._parentListeners=e._parentListeners,n._renderChildren=e._renderChildren,n._componentTag=e._componentTag,n._parentElm=e._parentElm,n._refElm=e._refElm,e.render&&(n.render=e.render,n.staticRenderFns=e.staticRenderFns)}function Bt(t){var e=t.options;if(t.super){var n=t.super.options,r=t.superOptions,o=t.extendOptions;n!==r&&(t.superOptions=n,o.render=e.render,o.staticRenderFns=e.staticRenderFns,o._scopeId=e._scopeId,e=t.options=N(n,o),e.name&&(e.components[e.name]=t))}return e}function Vt(t){this._init(t)}function Ht(t){t.use=function(t){if(!t.installed){var e=c(arguments,1);return e.unshift(this),"function"==typeof t.install?t.install.apply(t,e):t.apply(null,e),t.installed=!0,this}}}function Ft(t){t.mixin=function(t){this.options=N(this.options,t)}}function zt(t){t.cid=0;var e=1;t.extend=function(t){t=t||{};var n=this,r=n.cid,o=t._Ctor||(t._Ctor={});if(o[r])return o[r];var i=t.name||n.options.name,a=function(t){this._init(t)};return a.prototype=Object.create(n.prototype),a.prototype.constructor=a,a.cid=e++,a.options=N(n.options,t),a.super=n,a.extend=n.extend,a.mixin=n.mixin,a.use=n.use,Tn._assetTypes.forEach(function(t){a[t]=n[t]}),i&&(a.options.components[i]=a),a.superOptions=n.options,a.extendOptions=t,o[r]=a,a}}function qt(t){Tn._assetTypes.forEach(function(e){t[e]=function(t,n){return n?("component"===e&&f(n)&&(n.name=n.name||t,n=this.options._base.extend(n)),"directive"===e&&"function"==typeof n&&(n={bind:n,update:n}),this.options[e+"s"][t]=n,n):this.options[e+"s"][t]}})}function Kt(t){return t&&(t.Ctor.options.name||t.tag)}function Wt(t,e){return"string"==typeof t?t.split(",").indexOf(e)>-1:t.test(e)}function Jt(t,e){for(var n in t){var r=t[n];if(r){var o=Kt(r.componentOptions);o&&!e(o)&&(Gt(r),t[n]=null)}}}function Gt(t){t&&(t.componentInstance._inactive||wt(t.componentInstance,"deactivated"),t.componentInstance.$destroy())}function Zt(t){var e={};e.get=function(){return Tn},Object.defineProperty(t,"config",e),t.util=nr,t.set=O,t.delete=S,t.nextTick=Fn,t.options=Object.create(null),Tn._assetTypes.forEach(function(e){t.options[e+"s"]=Object.create(null)}),t.options._base=t,u(t.options.components,Ar),Ht(t),Ft(t),zt(t),qt(t)}function Qt(t){for(var e=t.data,n=t,r=t;r.componentInstance;)r=r.componentInstance._vnode,r.data&&(e=Xt(r.data,e));for(;n=n.parent;)n.data&&(e=Xt(e,n.data));return Yt(e)}function Xt(t,e){return{staticClass:te(t.staticClass,e.staticClass),class:t.class?[t.class,e.class]:e.class}}function Yt(t){var e=t.class,n=t.staticClass;return n||e?te(n,ee(e)):""}function te(t,e){return t?e?t+" "+e:t:e||""}function ee(t){var e="";if(!t)return e;if("string"==typeof t)return t;if(Array.isArray(t)){for(var n,r=0,o=t.length;r<o;r++)t[r]&&(n=ee(t[r]))&&(e+=n+" ");return e.slice(0,-1)}if(l(t)){for(var i in t)t[i]&&(e+=i+" ");return e.slice(0,-1)}return e}function ne(t){return Ur(t)?"svg":"math"===t?"math":void 0}function re(t){if(!Pn)return!0;if(Rr(t))return!1;if(t=t.toLowerCase(),null!=Br[t])return Br[t];var e=document.createElement(t);return t.indexOf("-")>-1?Br[t]=e.constructor===window.HTMLUnknownElement||e.constructor===window.HTMLElement:Br[t]=/HTMLUnknownElement/.test(e.toString())}function oe(t){if("string"==typeof t){if(t=document.querySelector(t),!t)return document.createElement("div")}return t}function ie(t,e){var n=document.createElement(t);return"select"!==t?n:(e.data&&e.data.attrs&&"multiple"in e.data.attrs&&n.setAttribute("multiple","multiple"),n)}function ae(t,e){return document.createElementNS(Lr[t],e)}function se(t){return document.createTextNode(t)}function ce(t){return document.createComment(t)}function ue(t,e,n){t.insertBefore(e,n)}function le(t,e){t.removeChild(e)}function fe(t,e){t.appendChild(e)}function pe(t){return t.parentNode}function de(t){return t.nextSibling}function ve(t){return t.tagName}function he(t,e){t.textContent=e}function me(t,e,n){t.setAttribute(e,n)}function ye(t,e){var n=t.data.ref;if(n){var o=t.context,i=t.componentInstance||t.elm,a=o.$refs;e?Array.isArray(a[n])?r(a[n],i):a[n]===i&&(a[n]=void 0):t.data.refInFor?Array.isArray(a[n])&&a[n].indexOf(i)<0?a[n].push(i):a[n]=[i]:a[n]=i}}function _e(t){return null==t}function ge(t){return null!=t}function be(t,e){return t.key===e.key&&t.tag===e.tag&&t.isComment===e.isComment&&!t.data==!e.data}function Ce(t,e,n){var r,o,i={};for(r=e;r<=n;++r)o=t[r].key,ge(o)&&(i[o]=r);return i}function we(t){function e(t){return new rr(O.tagName(t).toLowerCase(),{},[],void 0,t)}function r(t,e){function n(){0===--n.listeners&&o(t)}return n.listeners=e,n}function o(t){var e=O.parentNode(t);e&&O.removeChild(e,t)}function a(t,e,n,r,o){if(t.isRootInsert=!o,!s(t,e,n,r)){var i=t.data,a=t.children,c=t.tag;ge(c)?(t.elm=t.ns?O.createElementNS(t.ns,c):O.createElement(c,t),v(t),f(t,a,e),ge(i)&&d(t,e),l(n,t.elm,r)):t.isComment?(t.elm=O.createComment(t.text),l(n,t.elm,r)):(t.elm=O.createTextNode(t.text),l(n,t.elm,r))}}function s(t,e,n,r){var o=t.data;if(ge(o)){var i=ge(t.componentInstance)&&o.keepAlive;if(ge(o=o.hook)&&ge(o=o.init)&&o(t,!1,n,r),ge(t.componentInstance))return c(t,e),i&&u(t,e,n,r),!0}}function c(t,e){t.data.pendingInsert&&e.push.apply(e,t.data.pendingInsert),t.elm=t.componentInstance.$el,p(t)?(d(t,e),v(t)):(ye(t),e.push(t))}function u(t,e,n,r){for(var o,i=t;i.componentInstance;)if(i=i.componentInstance._vnode,ge(o=i.data)&&ge(o=o.transition)){for(o=0;o<A.activate.length;++o)A.activate[o](Fr,i);e.push(i);break}l(n,t.elm,r)}function l(t,e,n){t&&(n?O.insertBefore(t,e,n):O.appendChild(t,e))}function f(t,e,n){if(Array.isArray(e))for(var r=0;r<e.length;++r)a(e[r],n,t.elm,null,!0);else i(t.text)&&O.appendChild(t.elm,O.createTextNode(t.text))}function p(t){for(;t.componentInstance;)t=t.componentInstance._vnode;return ge(t.tag)}function d(t,e){for(var n=0;n<A.create.length;++n)A.create[n](Fr,t);$=t.data.hook,ge($)&&($.create&&$.create(Fr,t),$.insert&&e.push(t))}function v(t){var e;ge(e=t.context)&&ge(e=e.$options._scopeId)&&O.setAttribute(t.elm,e,""),ge(e=pr)&&e!==t.context&&ge(e=e.$options._scopeId)&&O.setAttribute(t.elm,e,"")}function h(t,e,n,r,o,i){for(;r<=o;++r)a(n[r],i,t,e)}function m(t){var e,n,r=t.data;if(ge(r))for(ge(e=r.hook)&&ge(e=e.destroy)&&e(t),e=0;e<A.destroy.length;++e)A.destroy[e](t);if(ge(e=t.children))for(n=0;n<t.children.length;++n)m(t.children[n])}function y(t,e,n,r){for(;n<=r;++n){var i=e[n];ge(i)&&(ge(i.tag)?(_(i),m(i)):o(i.elm))}}function _(t,e){if(e||ge(t.data)){var n=A.remove.length+1;for(e?e.listeners+=n:e=r(t.elm,n),ge($=t.componentInstance)&&ge($=$._vnode)&&ge($.data)&&_($,e),$=0;$<A.remove.length;++$)A.remove[$](t,e);ge($=t.data.hook)&&ge($=$.remove)?$(t,e):e()}else o(t.elm)}function g(t,e,n,r,o){for(var i,s,c,u,l=0,f=0,p=e.length-1,d=e[0],v=e[p],m=n.length-1,_=n[0],g=n[m],C=!o;l<=p&&f<=m;)_e(d)?d=e[++l]:_e(v)?v=e[--p]:be(d,_)?(b(d,_,r),d=e[++l],_=n[++f]):be(v,g)?(b(v,g,r),v=e[--p],g=n[--m]):be(d,g)?(b(d,g,r),C&&O.insertBefore(t,d.elm,O.nextSibling(v.elm)),d=e[++l],g=n[--m]):be(v,_)?(b(v,_,r),C&&O.insertBefore(t,v.elm,d.elm),v=e[--p],_=n[++f]):(_e(i)&&(i=Ce(e,l,p)),s=ge(_.key)?i[_.key]:null,_e(s)?(a(_,r,t,d.elm),_=n[++f]):(c=e[s],be(c,_)?(b(c,_,r),e[s]=void 0,C&&O.insertBefore(t,_.elm,d.elm),_=n[++f]):(a(_,r,t,d.elm),_=n[++f])));l>p?(u=_e(n[m+1])?null:n[m+1].elm,h(t,u,n,f,m,r)):f>m&&y(t,e,l,p)}function b(t,e,n,r){if(t!==e){if(e.isStatic&&t.isStatic&&e.key===t.key&&(e.isCloned||e.isOnce))return e.elm=t.elm,void(e.componentInstance=t.componentInstance);var o,i=e.data,a=ge(i);a&&ge(o=i.hook)&&ge(o=o.prepatch)&&o(t,e);var s=e.elm=t.elm,c=t.children,u=e.children;if(a&&p(e)){for(o=0;o<A.update.length;++o)A.update[o](t,e);ge(o=i.hook)&&ge(o=o.update)&&o(t,e)}_e(e.text)?ge(c)&&ge(u)?c!==u&&g(s,c,u,n,r):ge(u)?(ge(t.text)&&O.setTextContent(s,""),h(s,null,u,0,u.length-1,n)):ge(c)?y(s,c,0,c.length-1):ge(t.text)&&O.setTextContent(s,""):t.text!==e.text&&O.setTextContent(s,e.text),a&&ge(o=i.hook)&&ge(o=o.postpatch)&&o(t,e)}}function C(t,e,n){if(n&&t.parent)t.parent.data.pendingInsert=e;else for(var r=0;r<e.length;++r)e[r].data.hook.insert(e[r])}function w(t,e,n){e.elm=t;var r=e.tag,o=e.data,i=e.children;if(ge(o)&&(ge($=o.hook)&&ge($=$.init)&&$(e,!0),ge($=e.componentInstance)))return c(e,n),!0;if(ge(r)){if(ge(i))if(t.hasChildNodes()){for(var a=!0,s=t.firstChild,u=0;u<i.length;u++){if(!s||!w(s,i[u],n)){a=!1;break}s=s.nextSibling}if(!a||s)return!1}else f(e,i,n);if(ge(o))for(var l in o)if(!S(l)){d(e,n);break}}else t.data!==e.text&&(t.data=e.text);return!0}var $,k,A={},x=t.modules,O=t.nodeOps;for($=0;$<zr.length;++$)for(A[zr[$]]=[],k=0;k<x.length;++k)void 0!==x[k][zr[$]]&&A[zr[$]].push(x[k][zr[$]]);var S=n("attrs,style,class,staticClass,staticStyle,key");return function(t,n,r,o,i,s){if(!n)return void(t&&m(t));var c=!1,u=[];if(t){var l=ge(t.nodeType);if(!l&&be(t,n))b(t,n,u,o);else{if(l){if(1===t.nodeType&&t.hasAttribute("server-rendered")&&(t.removeAttribute("server-rendered"),r=!0),r&&w(t,n,u))return C(n,u,!0),t;t=e(t)}var f=t.elm,d=O.parentNode(f);if(a(n,u,f._leaveCb?null:d,O.nextSibling(f)),n.parent){for(var v=n.parent;v;)v.elm=n.elm,v=v.parent;if(p(n))for(var h=0;h<A.create.length;++h)A.create[h](Fr,n.parent)}null!==d?y(d,[t],0,0):ge(t.tag)&&m(t)}}else c=!0,a(n,u,i,s);return C(n,u,c),n.elm}}function $e(t,e){(t.data.directives||e.data.directives)&&ke(t,e)}function ke(t,e){var n,r,o,i=t===Fr,a=e===Fr,s=Ae(t.data.directives,t.context),c=Ae(e.data.directives,e.context),u=[],l=[];for(n in c)r=s[n],o=c[n],r?(o.oldValue=r.value,Oe(o,"update",e,t),o.def&&o.def.componentUpdated&&l.push(o)):(Oe(o,"bind",e,t),o.def&&o.def.inserted&&u.push(o));if(u.length){var f=function(){for(var n=0;n<u.length;n++)Oe(u[n],"inserted",e,t)};i?nt(e.data.hook||(e.data.hook={}),"insert",f,"dir-insert"):f()}if(l.length&&nt(e.data.hook||(e.data.hook={}),"postpatch",function(){for(var n=0;n<l.length;n++)Oe(l[n],"componentUpdated",e,t)},"dir-postpatch"),!i)for(n in s)c[n]||Oe(s[n],"unbind",t,t,a)}function Ae(t,e){var n=Object.create(null);if(!t)return n;var r,o;for(r=0;r<t.length;r++)o=t[r],o.modifiers||(o.modifiers=Kr),n[xe(o)]=o,o.def=L(e.$options,"directives",o.name,!0);return n}function xe(t){return t.rawName||t.name+"."+Object.keys(t.modifiers||{}).join(".")}function Oe(t,e,n,r,o){var i=t.def&&t.def[e];i&&i(n.elm,t,n,r,o)}function Se(t,e){if(t.data.attrs||e.data.attrs){var n,r,o,i=e.elm,a=t.data.attrs||{},s=e.data.attrs||{};s.__ob__&&(s=e.data.attrs=u({},s));for(n in s)r=s[n],o=a[n],o!==r&&Ee(i,n,r);Mn&&s.value!==a.value&&Ee(i,"value",s.value);for(n in a)null==s[n]&&(Dr(n)?i.removeAttributeNS(jr,Pr(n)):Ir(n)||i.removeAttribute(n))}}function Ee(t,e,n){Tr(e)?Nr(n)?t.removeAttribute(e):t.setAttribute(e,e):Ir(e)?t.setAttribute(e,Nr(n)||"false"===n?"false":"true"):Dr(e)?Nr(n)?t.removeAttributeNS(jr,Pr(e)):t.setAttributeNS(jr,e,n):Nr(n)?t.removeAttribute(e):t.setAttribute(e,n)}function Ie(t,e){var n=e.elm,r=e.data,o=t.data;if(r.staticClass||r.class||o&&(o.staticClass||o.class)){var i=Qt(e),a=n._transitionClasses;a&&(i=te(i,ee(a))),i!==n._prevClass&&(n.setAttribute("class",i),n._prevClass=i)}}function Te(t,e,n,r){if(n){var o=e,i=xr;e=function(n){je(t,e,r,i),1===arguments.length?o(n):o.apply(null,arguments)}}xr.addEventListener(t,e,r)}function je(t,e,n,r){(r||xr).removeEventListener(t,e,n)}function De(t,e){if(t.data.on||e.data.on){var n=e.data.on||{},r=t.data.on||{};xr=e.elm,ot(n,r,Te,je,e.context)}}function Pe(t,e){if(t.data.domProps||e.data.domProps){var n,r,o=e.elm,i=t.data.domProps||{},a=e.data.domProps||{};a.__ob__&&(a=e.data.domProps=u({},a));for(n in i)null==a[n]&&(o[n]="");for(n in a)if(r=a[n],"textContent"!==n&&"innerHTML"!==n||(e.children&&(e.children.length=0),r!==i[n]))if("value"===n){o._value=r;var s=null==r?"":String(r);Ne(o,e,s)&&(o.value=s)}else o[n]=r}}function Ne(t,e,n){return!t.composing&&("option"===e.tag||Le(t,n)||Me(e,n))}function Le(t,e){return document.activeElement!==t&&t.value!==e}function Me(t,n){var r=t.elm.value,o=t.elm._vModifiers;return o&&o.number||"number"===t.elm.type?e(r)!==e(n):o&&o.trim?r.trim()!==n.trim():r!==n}function Ue(t){var e=Re(t.style);return t.staticStyle?u(t.staticStyle,e):e}function Re(t){return Array.isArray(t)?p(t):"string"==typeof t?Xr(t):t}function Be(t,e){var n,r={};if(e)for(var o=t;o.componentInstance;)o=o.componentInstance._vnode,o.data&&(n=Ue(o.data))&&u(r,n);(n=Ue(t.data))&&u(r,n);for(var i=t;i=i.parent;)i.data&&(n=Ue(i.data))&&u(r,n);return r}function Ve(t,e){var n=e.data,r=t.data;if(n.staticStyle||n.style||r.staticStyle||r.style){var o,i,a=e.elm,s=t.data.staticStyle,c=t.data.style||{},l=s||c,f=Re(e.data.style)||{};e.data.style=f.__ob__?u({},f):f;var p=Be(e,!0);for(i in l)null==p[i]&&eo(a,i,"");for(i in p)o=p[i],o!==l[i]&&eo(a,i,null==o?"":o)}}function He(t,e){if(e&&e.trim())if(t.classList)e.indexOf(" ")>-1?e.split(/\s+/).forEach(function(e){return t.classList.add(e)}):t.classList.add(e);else{var n=" "+t.getAttribute("class")+" ";n.indexOf(" "+e+" ")<0&&t.setAttribute("class",(n+e).trim())}}function Fe(t,e){if(e&&e.trim())if(t.classList)e.indexOf(" ")>-1?e.split(/\s+/).forEach(function(e){return t.classList.remove(e)}):t.classList.remove(e);else{for(var n=" "+t.getAttribute("class")+" ",r=" "+e+" ";n.indexOf(r)>=0;)n=n.replace(r," ");t.setAttribute("class",n.trim())}}function ze(t){po(function(){po(t)})}function qe(t,e){(t._transitionClasses||(t._transitionClasses=[])).push(e),He(t,e)}function Ke(t,e){t._transitionClasses&&r(t._transitionClasses,e),Fe(t,e)}function We(t,e,n){var r=Je(t,e),o=r.type,i=r.timeout,a=r.propCount;if(!o)return n();var s=o===ao?uo:fo,c=0,u=function(){t.removeEventListener(s,l),n()},l=function(e){e.target===t&&++c>=a&&u()};setTimeout(function(){c<a&&u()},i+1),t.addEventListener(s,l)}function Je(t,e){var n,r=window.getComputedStyle(t),o=r[co+"Delay"].split(", "),i=r[co+"Duration"].split(", "),a=Ge(o,i),s=r[lo+"Delay"].split(", "),c=r[lo+"Duration"].split(", "),u=Ge(s,c),l=0,f=0;e===ao?a>0&&(n=ao,l=a,f=i.length):e===so?u>0&&(n=so,l=u,f=c.length):(l=Math.max(a,u),n=l>0?a>u?ao:so:null,f=n?n===ao?i.length:c.length:0);var p=n===ao&&vo.test(r[co+"Property"]);return{type:n,timeout:l,propCount:f,hasTransform:p}}function Ge(t,e){for(;t.length<e.length;)t=t.concat(t);return Math.max.apply(null,e.map(function(e,n){ return Ze(e)+Ze(t[n])}))}function Ze(t){return 1e3*Number(t.slice(0,-1))}function Qe(t,e){var n=t.elm;n._leaveCb&&(n._leaveCb.cancelled=!0,n._leaveCb());var r=Ye(t.data.transition);if(r&&!n._enterCb&&1===n.nodeType){for(var o=r.css,i=r.type,a=r.enterClass,s=r.enterToClass,c=r.enterActiveClass,u=r.appearClass,l=r.appearToClass,f=r.appearActiveClass,p=r.beforeEnter,d=r.enter,v=r.afterEnter,h=r.enterCancelled,m=r.beforeAppear,y=r.appear,_=r.afterAppear,g=r.appearCancelled,b=pr,C=pr.$vnode;C&&C.parent;)C=C.parent,b=C.context;var w=!b._isMounted||!t.isRootInsert;if(!w||y||""===y){var $=w?u:a,k=w?f:c,A=w?l:s,x=w?m||p:p,O=w&&"function"==typeof y?y:d,S=w?_||v:v,E=w?g||h:h,I=o!==!1&&!Mn,T=O&&(O._length||O.length)>1,j=n._enterCb=tn(function(){I&&(Ke(n,A),Ke(n,k)),j.cancelled?(I&&Ke(n,$),E&&E(n)):S&&S(n),n._enterCb=null});t.data.show||nt(t.data.hook||(t.data.hook={}),"insert",function(){var e=n.parentNode,r=e&&e._pending&&e._pending[t.key];r&&r.tag===t.tag&&r.elm._leaveCb&&r.elm._leaveCb(),O&&O(n,j)},"transition-insert"),x&&x(n),I&&(qe(n,$),qe(n,k),ze(function(){qe(n,A),Ke(n,$),j.cancelled||T||We(n,i,j)})),t.data.show&&(e&&e(),O&&O(n,j)),I||T||j()}}}function Xe(t,e){function n(){y.cancelled||(t.data.show||((r.parentNode._pending||(r.parentNode._pending={}))[t.key]=t),l&&l(r),h&&(qe(r,s),qe(r,u),ze(function(){qe(r,c),Ke(r,s),y.cancelled||m||We(r,a,y)})),f&&f(r,y),h||m||y())}var r=t.elm;r._enterCb&&(r._enterCb.cancelled=!0,r._enterCb());var o=Ye(t.data.transition);if(!o)return e();if(!r._leaveCb&&1===r.nodeType){var i=o.css,a=o.type,s=o.leaveClass,c=o.leaveToClass,u=o.leaveActiveClass,l=o.beforeLeave,f=o.leave,p=o.afterLeave,d=o.leaveCancelled,v=o.delayLeave,h=i!==!1&&!Mn,m=f&&(f._length||f.length)>1,y=r._leaveCb=tn(function(){r.parentNode&&r.parentNode._pending&&(r.parentNode._pending[t.key]=null),h&&(Ke(r,c),Ke(r,u)),y.cancelled?(h&&Ke(r,s),d&&d(r)):(e(),p&&p(r)),r._leaveCb=null});v?v(n):n()}}function Ye(t){if(t){if("object"==typeof t){var e={};return t.css!==!1&&u(e,ho(t.name||"v")),u(e,t),e}return"string"==typeof t?ho(t):void 0}}function tn(t){var e=!1;return function(){e||(e=!0,t())}}function en(t,e){e.data.show||Qe(e)}function nn(t,e,n){var r=e.value,o=t.multiple;if(!o||Array.isArray(r)){for(var i,a,s=0,c=t.options.length;s<c;s++)if(a=t.options[s],o)i=m(r,on(a))>-1,a.selected!==i&&(a.selected=i);else if(h(on(a),r))return void(t.selectedIndex!==s&&(t.selectedIndex=s));o||(t.selectedIndex=-1)}}function rn(t,e){for(var n=0,r=e.length;n<r;n++)if(h(on(e[n]),t))return!1;return!0}function on(t){return"_value"in t?t._value:t.value}function an(t){t.target.composing=!0}function sn(t){t.target.composing=!1,cn(t.target,"input")}function cn(t,e){var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0),t.dispatchEvent(n)}function un(t){return!t.componentInstance||t.data&&t.data.transition?t:un(t.componentInstance._vnode)}function ln(t){var e=t&&t.componentOptions;return e&&e.Ctor.options.abstract?ln(ct(e.children)):t}function fn(t){var e={},n=t.$options;for(var r in n.propsData)e[r]=t[r];var o=n._parentListeners;for(var i in o)e[$n(i)]=o[i].fn;return e}function pn(t,e){return/\d-keep-alive$/.test(e.tag)?t("keep-alive"):null}function dn(t){for(;t=t.parent;)if(t.data.transition)return!0}function vn(t,e){return e.key===t.key&&e.tag===t.tag}function hn(t){t.elm._moveCb&&t.elm._moveCb(),t.elm._enterCb&&t.elm._enterCb()}function mn(t){t.data.newPos=t.elm.getBoundingClientRect()}function yn(t){var e=t.data.pos,n=t.data.newPos,r=e.left-n.left,o=e.top-n.top;if(r||o){t.data.moved=!0;var i=t.elm.style;i.transform=i.WebkitTransform="translate("+r+"px,"+o+"px)",i.transitionDuration="0s"}}var _n,gn,bn=n("slot,component",!0),Cn=Object.prototype.hasOwnProperty,wn=/-(\w)/g,$n=a(function(t){return t.replace(wn,function(t,e){return e?e.toUpperCase():""})}),kn=a(function(t){return t.charAt(0).toUpperCase()+t.slice(1)}),An=/([^-])([A-Z])/g,xn=a(function(t){return t.replace(An,"$1-$2").replace(An,"$1-$2").toLowerCase()}),On=Object.prototype.toString,Sn="[object Object]",En=function(){return!1},In=function(t){return t},Tn={optionMergeStrategies:Object.create(null),silent:!1,devtools:!1,errorHandler:null,ignoredElements:[],keyCodes:Object.create(null),isReservedTag:En,isUnknownElement:En,getTagNamespace:d,parsePlatformTagName:In,mustUseProp:En,_assetTypes:["component","directive","filter"],_lifecycleHooks:["beforeCreate","created","beforeMount","mounted","beforeUpdate","updated","beforeDestroy","destroyed","activated","deactivated"],_maxUpdateCount:100},jn=/[^\w.$]/,Dn="__proto__"in{},Pn="undefined"!=typeof window,Nn=Pn&&window.navigator.userAgent.toLowerCase(),Ln=Nn&&/msie|trident/.test(Nn),Mn=Nn&&Nn.indexOf("msie 9.0")>0,Un=Nn&&Nn.indexOf("edge/")>0,Rn=Nn&&Nn.indexOf("android")>0,Bn=Nn&&/iphone|ipad|ipod|ios/.test(Nn),Vn=function(){return void 0===_n&&(_n=!Pn&&"undefined"!=typeof global&&"server"===global.process.env.VUE_ENV),_n},Hn=Pn&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__,Fn=function(){function t(){r=!1;var t=n.slice(0);n.length=0;for(var e=0;e<t.length;e++)t[e]()}var e,n=[],r=!1;if("undefined"!=typeof Promise&&b(Promise)){var o=Promise.resolve(),i=function(t){console.error(t)};e=function(){o.then(t).catch(i),Bn&&setTimeout(d)}}else if("undefined"==typeof MutationObserver||!b(MutationObserver)&&"[object MutationObserverConstructor]"!==MutationObserver.toString())e=function(){setTimeout(t,0)};else{var a=1,s=new MutationObserver(t),c=document.createTextNode(String(a));s.observe(c,{characterData:!0}),e=function(){a=(a+1)%2,c.data=String(a)}}return function(t,o){var i;if(n.push(function(){t&&t.call(o),i&&i(o)}),r||(r=!0,e()),!t&&"undefined"!=typeof Promise)return new Promise(function(t){i=t})}}();gn="undefined"!=typeof Set&&b(Set)?Set:function(){function t(){this.set=Object.create(null)}return t.prototype.has=function(t){return this.set[t]===!0},t.prototype.add=function(t){this.set[t]=!0},t.prototype.clear=function(){this.set=Object.create(null)},t}();var zn,qn=d,Kn=0,Wn=function(){this.id=Kn++,this.subs=[]};Wn.prototype.addSub=function(t){this.subs.push(t)},Wn.prototype.removeSub=function(t){r(this.subs,t)},Wn.prototype.depend=function(){Wn.target&&Wn.target.addDep(this)},Wn.prototype.notify=function(){for(var t=this.subs.slice(),e=0,n=t.length;e<n;e++)t[e].update()},Wn.target=null;var Jn=[],Gn=Array.prototype,Zn=Object.create(Gn);["push","pop","shift","unshift","splice","sort","reverse"].forEach(function(t){var e=Gn[t];_(Zn,t,function(){for(var n=arguments,r=arguments.length,o=new Array(r);r--;)o[r]=n[r];var i,a=e.apply(this,o),s=this.__ob__;switch(t){case"push":i=o;break;case"unshift":i=o;break;case"splice":i=o.slice(2)}return i&&s.observeArray(i),s.dep.notify(),a})});var Qn=Object.getOwnPropertyNames(Zn),Xn={shouldConvert:!0,isSettingProps:!1},Yn=function(t){if(this.value=t,this.dep=new Wn,this.vmCount=0,_(t,"__ob__",this),Array.isArray(t)){var e=Dn?$:k;e(t,Zn,Qn),this.observeArray(t)}else this.walk(t)};Yn.prototype.walk=function(t){for(var e=Object.keys(t),n=0;n<e.length;n++)x(t,e[n],t[e[n]])},Yn.prototype.observeArray=function(t){for(var e=0,n=t.length;e<n;e++)A(t[e])};var tr=Tn.optionMergeStrategies;tr.data=function(t,e,n){return n?t||e?function(){var r="function"==typeof e?e.call(n):e,o="function"==typeof t?t.call(n):void 0;return r?I(r,o):o}:void 0:e?"function"!=typeof e?t:t?function(){return I(e.call(this),t.call(this))}:e:t},Tn._lifecycleHooks.forEach(function(t){tr[t]=T}),Tn._assetTypes.forEach(function(t){tr[t+"s"]=j}),tr.watch=function(t,e){if(!e)return t;if(!t)return e;var n={};u(n,t);for(var r in e){var o=n[r],i=e[r];o&&!Array.isArray(o)&&(o=[o]),n[r]=o?o.concat(i):[i]}return n},tr.props=tr.methods=tr.computed=function(t,e){if(!e)return t;if(!t)return e;var n=Object.create(null);return u(n,t),u(n,e),n};var er=function(t,e){return void 0===e?t:e},nr=Object.freeze({defineReactive:x,_toString:t,toNumber:e,makeMap:n,isBuiltInTag:bn,remove:r,hasOwn:o,isPrimitive:i,cached:a,camelize:$n,capitalize:kn,hyphenate:xn,bind:s,toArray:c,extend:u,isObject:l,isPlainObject:f,toObject:p,noop:d,no:En,identity:In,genStaticKeys:v,looseEqual:h,looseIndexOf:m,isReserved:y,def:_,parsePath:g,hasProto:Dn,inBrowser:Pn,UA:Nn,isIE:Ln,isIE9:Mn,isEdge:Un,isAndroid:Rn,isIOS:Bn,isServerRendering:Vn,devtools:Hn,nextTick:Fn,get _Set(){return gn},mergeOptions:N,resolveAsset:L,warn:qn,formatComponentName:zn,validateProp:M}),rr=function(t,e,n,r,o,i,a){this.tag=t,this.data=e,this.children=n,this.text=r,this.elm=o,this.ns=void 0,this.context=i,this.functionalContext=void 0,this.key=e&&e.key,this.componentOptions=a,this.componentInstance=void 0,this.parent=void 0,this.raw=!1,this.isStatic=!1,this.isRootInsert=!0,this.isComment=!1,this.isCloned=!1,this.isOnce=!1},or={child:{}};or.child.get=function(){return this.componentInstance},Object.defineProperties(rr.prototype,or);var ir,ar=function(){var t=new rr;return t.text="",t.isComment=!0,t},sr={init:W,prepatch:J,insert:G,destroy:Z},cr=Object.keys(sr),ur=a(function(t){var e="~"===t.charAt(0);t=e?t.slice(1):t;var n="!"===t.charAt(0);return t=n?t.slice(1):t,{name:t,once:e,capture:n}}),lr=1,fr=2,pr=null,dr=[],vr={},hr=!1,mr=!1,yr=0,_r=0,gr=function(t,e,n,r){this.vm=t,t._watchers.push(this),r?(this.deep=!!r.deep,this.user=!!r.user,this.lazy=!!r.lazy,this.sync=!!r.sync):this.deep=this.user=this.lazy=this.sync=!1,this.cb=n,this.id=++_r,this.active=!0,this.dirty=this.lazy,this.deps=[],this.newDeps=[],this.depIds=new gn,this.newDepIds=new gn,this.expression="","function"==typeof e?this.getter=e:(this.getter=g(e),this.getter||(this.getter=function(){})),this.value=this.lazy?void 0:this.get()};gr.prototype.get=function(){C(this);var t=this.getter.call(this.vm,this.vm);return this.deep&&xt(t),w(),this.cleanupDeps(),t},gr.prototype.addDep=function(t){var e=t.id;this.newDepIds.has(e)||(this.newDepIds.add(e),this.newDeps.push(t),this.depIds.has(e)||t.addSub(this))},gr.prototype.cleanupDeps=function(){for(var t=this,e=this.deps.length;e--;){var n=t.deps[e];t.newDepIds.has(n.id)||n.removeSub(t)}var r=this.depIds;this.depIds=this.newDepIds,this.newDepIds=r,this.newDepIds.clear(),r=this.deps,this.deps=this.newDeps,this.newDeps=r,this.newDeps.length=0},gr.prototype.update=function(){this.lazy?this.dirty=!0:this.sync?this.run():At(this)},gr.prototype.run=function(){if(this.active){var t=this.get();if(t!==this.value||l(t)||this.deep){var e=this.value;if(this.value=t,this.user)try{this.cb.call(this.vm,t,e)}catch(t){if(!Tn.errorHandler)throw t;Tn.errorHandler.call(null,t,this.vm)}else this.cb.call(this.vm,t,e)}}},gr.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},gr.prototype.depend=function(){for(var t=this,e=this.deps.length;e--;)t.deps[e].depend()},gr.prototype.teardown=function(){var t=this;if(this.active){this.vm._isBeingDestroyed||r(this.vm._watchers,this);for(var e=this.deps.length;e--;)t.deps[e].removeSub(t);this.active=!1}};var br=new gn,Cr={enumerable:!0,configurable:!0,get:d,set:d},wr=0;Ut(Vt),Lt(Vt),gt(Vt),Ct(Vt),dt(Vt);var $r=[String,RegExp],kr={name:"keep-alive",abstract:!0,props:{include:$r,exclude:$r},created:function(){this.cache=Object.create(null)},destroyed:function(){var t=this;for(var e in this.cache)Gt(t.cache[e])},watch:{include:function(t){Jt(this.cache,function(e){return Wt(t,e)})},exclude:function(t){Jt(this.cache,function(e){return!Wt(t,e)})}},render:function(){var t=ct(this.$slots.default),e=t&&t.componentOptions;if(e){var n=Kt(e);if(n&&(this.include&&!Wt(this.include,n)||this.exclude&&Wt(this.exclude,n)))return t;var r=null==t.key?e.Ctor.cid+(e.tag?"::"+e.tag:""):t.key;this.cache[r]?t.componentInstance=this.cache[r].componentInstance:this.cache[r]=t,t.data.keepAlive=!0}return t}},Ar={KeepAlive:kr};Zt(Vt),Object.defineProperty(Vt.prototype,"$isServer",{get:Vn}),Vt.version="2.1.10";var xr,Or,Sr=n("input,textarea,option,select"),Er=function(t,e,n){return"value"===n&&Sr(t)&&"button"!==e||"selected"===n&&"option"===t||"checked"===n&&"input"===t||"muted"===n&&"video"===t},Ir=n("contenteditable,draggable,spellcheck"),Tr=n("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),jr="http://www.w3.org/1999/xlink",Dr=function(t){return":"===t.charAt(5)&&"xlink"===t.slice(0,5)},Pr=function(t){return Dr(t)?t.slice(6,t.length):""},Nr=function(t){return null==t||t===!1},Lr={svg:"http://www.w3.org/2000/svg",math:"http://www.w3.org/1998/Math/MathML"},Mr=n("html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template"),Ur=n("svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view",!0),Rr=function(t){return Mr(t)||Ur(t)},Br=Object.create(null),Vr=Object.freeze({createElement:ie,createElementNS:ae,createTextNode:se,createComment:ce,insertBefore:ue,removeChild:le,appendChild:fe,parentNode:pe,nextSibling:de,tagName:ve,setTextContent:he,setAttribute:me}),Hr={create:function(t,e){ye(e)},update:function(t,e){t.data.ref!==e.data.ref&&(ye(t,!0),ye(e))},destroy:function(t){ye(t,!0)}},Fr=new rr("",{},[]),zr=["create","activate","update","remove","destroy"],qr={create:$e,update:$e,destroy:function(t){$e(t,Fr)}},Kr=Object.create(null),Wr=[Hr,qr],Jr={create:Se,update:Se},Gr={create:Ie,update:Ie},Zr={create:De,update:De},Qr={create:Pe,update:Pe},Xr=a(function(t){var e={},n=/;(?![^(]*\))/g,r=/:(.+)/;return t.split(n).forEach(function(t){if(t){var n=t.split(r);n.length>1&&(e[n[0].trim()]=n[1].trim())}}),e}),Yr=/^--/,to=/\s*!important$/,eo=function(t,e,n){Yr.test(e)?t.style.setProperty(e,n):to.test(n)?t.style.setProperty(e,n.replace(to,""),"important"):t.style[ro(e)]=n},no=["Webkit","Moz","ms"],ro=a(function(t){if(Or=Or||document.createElement("div"),t=$n(t),"filter"!==t&&t in Or.style)return t;for(var e=t.charAt(0).toUpperCase()+t.slice(1),n=0;n<no.length;n++){var r=no[n]+e;if(r in Or.style)return r}}),oo={create:Ve,update:Ve},io=Pn&&!Mn,ao="transition",so="animation",co="transition",uo="transitionend",lo="animation",fo="animationend";io&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(co="WebkitTransition",uo="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(lo="WebkitAnimation",fo="webkitAnimationEnd"));var po=Pn&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout,vo=/\b(transform|all)(,|$)/,ho=a(function(t){return{enterClass:t+"-enter",leaveClass:t+"-leave",appearClass:t+"-enter",enterToClass:t+"-enter-to",leaveToClass:t+"-leave-to",appearToClass:t+"-enter-to",enterActiveClass:t+"-enter-active",leaveActiveClass:t+"-leave-active",appearActiveClass:t+"-enter-active"}}),mo=Pn?{create:en,activate:en,remove:function(t,e){t.data.show?e():Xe(t,e)}}:{},yo=[Jr,Gr,Zr,Qr,oo,mo],_o=yo.concat(Wr),go=we({nodeOps:Vr,modules:_o});Mn&&document.addEventListener("selectionchange",function(){var t=document.activeElement;t&&t.vmodel&&cn(t,"input")});var bo={inserted:function(t,e,n){if("select"===n.tag){var r=function(){nn(t,e,n.context)};r(),(Ln||Un)&&setTimeout(r,0)}else"textarea"!==n.tag&&"text"!==t.type||(t._vModifiers=e.modifiers,e.modifiers.lazy||(Rn||(t.addEventListener("compositionstart",an),t.addEventListener("compositionend",sn)),Mn&&(t.vmodel=!0)))},componentUpdated:function(t,e,n){if("select"===n.tag){nn(t,e,n.context);var r=t.multiple?e.value.some(function(e){return rn(e,t.options)}):e.value!==e.oldValue&&rn(e.value,t.options);r&&cn(t,"change")}}},Co={bind:function(t,e,n){var r=e.value;n=un(n);var o=n.data&&n.data.transition,i=t.__vOriginalDisplay="none"===t.style.display?"":t.style.display;r&&o&&!Mn?(n.data.show=!0,Qe(n,function(){t.style.display=i})):t.style.display=r?i:"none"},update:function(t,e,n){var r=e.value,o=e.oldValue;if(r!==o){n=un(n);var i=n.data&&n.data.transition;i&&!Mn?(n.data.show=!0,r?Qe(n,function(){t.style.display=t.__vOriginalDisplay}):Xe(n,function(){t.style.display="none"})):t.style.display=r?t.__vOriginalDisplay:"none"}},unbind:function(t,e,n,r,o){o||(t.style.display=t.__vOriginalDisplay)}},wo={model:bo,show:Co},$o={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String},ko={name:"transition",props:$o,abstract:!0,render:function(t){var e=this,n=this.$slots.default;if(n&&(n=n.filter(function(t){return t.tag}),n.length)){var r=this.mode,o=n[0];if(dn(this.$vnode))return o;var a=ln(o);if(!a)return o;if(this._leaving)return pn(t,o);var s="__transition-"+this._uid+"-",c=a.key=null==a.key?s+a.tag:i(a.key)?0===String(a.key).indexOf(s)?a.key:s+a.key:a.key,l=(a.data||(a.data={})).transition=fn(this),f=this._vnode,p=ln(f);if(a.data.directives&&a.data.directives.some(function(t){return"show"===t.name})&&(a.data.show=!0),p&&p.data&&!vn(a,p)){var d=p&&(p.data.transition=u({},l));if("out-in"===r)return this._leaving=!0,nt(d,"afterLeave",function(){e._leaving=!1,e.$forceUpdate()},c),pn(t,o);if("in-out"===r){var v,h=function(){v()};nt(l,"afterEnter",h,c),nt(l,"enterCancelled",h,c),nt(d,"delayLeave",function(t){v=t},c)}}return o}}},Ao=u({tag:String,moveClass:String},$o);delete Ao.mode;var xo={props:Ao,render:function(t){for(var e=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,o=this.$slots.default||[],i=this.children=[],a=fn(this),s=0;s<o.length;s++){var c=o[s];c.tag&&null!=c.key&&0!==String(c.key).indexOf("__vlist")&&(i.push(c),n[c.key]=c,(c.data||(c.data={})).transition=a)}if(r){for(var u=[],l=[],f=0;f<r.length;f++){var p=r[f];p.data.transition=a,p.data.pos=p.elm.getBoundingClientRect(),n[p.key]?u.push(p):l.push(p)}this.kept=t(e,null,u),this.removed=l}return t(e,null,i)},beforeUpdate:function(){this.__patch__(this._vnode,this.kept,!1,!0),this._vnode=this.kept},updated:function(){var t=this.prevChildren,e=this.moveClass||(this.name||"v")+"-move";if(t.length&&this.hasMove(t[0].elm,e)){t.forEach(hn),t.forEach(mn),t.forEach(yn);document.body.offsetHeight;t.forEach(function(t){if(t.data.moved){var n=t.elm,r=n.style;qe(n,e),r.transform=r.WebkitTransform=r.transitionDuration="",n.addEventListener(uo,n._moveCb=function t(r){r&&!/transform$/.test(r.propertyName)||(n.removeEventListener(uo,t),n._moveCb=null,Ke(n,e))})}})}},methods:{hasMove:function(t,e){if(!io)return!1;if(null!=this._hasMove)return this._hasMove;qe(t,e);var n=Je(t);return Ke(t,e),this._hasMove=n.hasTransform}}},Oo={Transition:ko,TransitionGroup:xo};return Vt.config.isUnknownElement=re,Vt.config.isReservedTag=Rr,Vt.config.getTagNamespace=ne,Vt.config.mustUseProp=Er,u(Vt.options.directives,wo),u(Vt.options.components,Oo),Vt.prototype.__patch__=Pn?go:d,Vt.prototype.$mount=function(t,e){return t=t&&Pn?oe(t):void 0,this._mount(t,e)},setTimeout(function(){Tn.devtools&&Hn&&Hn.emit("init",Vt)},0),Vt});
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/instance/render-helpers/render-static.js
60
/* @flow */ import { cloneVNode, cloneVNodes } from 'core/vdom/vnode' /** * Runtime helper for rendering static trees. */ export function renderStatic ( index: number, isInFor?: boolean ): VNode | Array<VNode> { let tree = this._staticTrees[index] // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree) } // otherwise, render a fresh tree. tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy) markStatic(tree, `__static__${index}`, false) return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ export function markOnce ( tree: VNode | Array<VNode>, index: number, key: string ) { markStatic(tree, `__once__${index}${key ? `_${key}` : ``}`, true) return tree } function markStatic ( tree: VNode | Array<VNode>, key: string, isOnce: boolean ) { if (Array.isArray(tree)) { for (let i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], `${key}_${i}`, isOnce) } } } else { markStaticNode(tree, key, isOnce) } } function markStaticNode (node, key, isOnce) { node.isStatic = true node.key = key node.isOnce = isOnce }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/server/render-context.js
109
/* @flow */ type RenderState = { type: 'Element'; rendered: number; total: number; endTag: string; children: Array<VNode>; } | { type: 'Component'; prevActive: Component; } | { type: 'ComponentWithCache'; buffer: Array<string>; bufferIndex: number; key: string; }; export class RenderContext { activeInstance: Component; renderStates: Array<RenderState>; write: (text: string, next: Function) => void; renderNode: (node: VNode, isRoot: boolean, context: RenderContext) => void; next: () => void; done: () => void; modules: Array<() => ?string>; directives: Object; isUnaryTag: (tag: string) => boolean; cache: any; get: ?(key: string, cb: Function) => void; has: ?(key: string, cb: Function) => void; constructor (options: Object) { this.activeInstance = options.activeInstance this.renderStates = [] this.write = options.write this.done = options.done this.renderNode = options.renderNode this.isUnaryTag = options.isUnaryTag this.modules = options.modules this.directives = options.directives const cache = options.cache if (cache && (!cache.get || !cache.set)) { throw new Error('renderer cache must implement at least get & set.') } this.cache = cache this.get = cache && normalizeAsync(cache, 'get') this.has = cache && normalizeAsync(cache, 'has') this.next = this.next.bind(this) } next () { const lastState = this.renderStates[this.renderStates.length - 1] if (!lastState) { return this.done() } switch (lastState.type) { case 'Element': const { children, total } = lastState const rendered = lastState.rendered++ if (rendered < total) { this.renderNode(children[rendered], false, this) } else { this.renderStates.pop() this.write(lastState.endTag, this.next) } break case 'Component': this.renderStates.pop() this.activeInstance = lastState.prevActive this.next() break case 'ComponentWithCache': this.renderStates.pop() const { buffer, bufferIndex, key } = lastState const result = buffer[bufferIndex] this.cache.set(key, result) if (bufferIndex === 0) { // this is a top-level cached component, // exit caching mode. this.write.caching = false } else { // parent component is also being cached, // merge self into parent's result buffer[bufferIndex - 1] += result } buffer.length = bufferIndex this.next() break } } } function normalizeAsync (cache, method) { const fn = cache[method] if (!fn) { return } else if (fn.length > 1) { return (key, cb) => fn.call(cache, key, cb) } else { return (key, cb) => cb(fn.call(cache, key)) } }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/components/keep-alive.js
52
/* @flow */ import { callHook } from 'core/instance/lifecycle' import { getFirstComponentChild } from 'core/vdom/helpers/index' const patternTypes = [String, RegExp] function getComponentName (opts: ?VNodeComponentOptions): ?string { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern: string | RegExp, name: string): boolean { if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (pattern instanceof RegExp) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (cache, filter) { for (const key in cache) { const cachedNode = cache[key] if (cachedNode) { const name = getComponentName(cachedNode.componentOptions) if (name && !filter(name)) { pruneCacheEntry(cachedNode) cache[key] = null } } } } function pruneCacheEntry (vnode: ?MountedComponentVNode) { if (vnode) { if (!vnode.componentInstance._inactive) { callHook(vnode.componentInstance, 'deactivated') } vnode.componentInstance.$destroy() } } export default { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes }, created () { this.cache = Object.create(null) }, destroyed () { for (const key in this.cache) { pruneCacheEntry(this.cache[key]) } }, watch: { include (val: string | RegExp) { pruneCache(this.cache, name => matches(val, name)) }, exclude (val: string | RegExp) { pruneCache(this.cache, name => !matches(val, name)) } }, render () { const vnode: VNode = getFirstComponentChild(this.$slots.default) const componentOptions = vnode && vnode.componentOptions if (componentOptions) { // check pattern const name = getComponentName(componentOptions) if (name && ( (this.include && !matches(this.include, name)) || (this.exclude && matches(this.exclude, name)) )) { return vnode } const key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? `::${componentOptions.tag}` : '') : vnode.key if (this.cache[key]) { vnode.componentInstance = this.cache[key].componentInstance } else { this.cache[key] = vnode } vnode.data.keepAlive = true } return vnode } }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/instance/render-helpers/bind-object-props.js
39
/* @flow */ import config from 'core/config' import { isObject, warn, toObject } from 'core/util/index' /** * Runtime helper for merging v-bind="object" into a VNode's data. */ export function bindObjectProps ( data: any, tag: string, value: any, asProp?: boolean ): VNodeData { if (value) { if (!isObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ) } else { if (Array.isArray(value)) { value = toObject(value) } for (const key in value) { if (key === 'class' || key === 'style') { data[key] = value[key] } else { const type = data.attrs && data.attrs.type const hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}) hash[key] = value[key] } } } } return data }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
test/unit/features/options/_scopeId.spec.js
28
import Vue from 'vue' describe('Options _scopeId', () => { it('should add scopeId attributes', () => { const vm = new Vue({ _scopeId: 'foo', template: '<div><p><span></span></p></div>' }).$mount() expect(vm.$el.hasAttribute('foo')).toBe(true) expect(vm.$el.children[0].hasAttribute('foo')).toBe(true) expect(vm.$el.children[0].children[0].hasAttribute('foo')).toBe(true) }) it('should add scopedId attributes from both parent and child on child root', () => { const vm = new Vue({ _scopeId: 'foo', template: '<div><child></child></div>', components: { child: { _scopeId: 'bar', template: '<div></div>' } } }).$mount() expect(vm.$el.children[0].hasAttribute('foo')).toBe(true) expect(vm.$el.children[0].hasAttribute('bar')).toBe(true) }) it('should add scopedId attributes from both parent and child on slot contents', () => { const vm = new Vue({ _scopeId: 'foo', template: '<div><child><p>hi</p></child></div>', components: { child: { _scopeId: 'bar', template: '<div><slot></slot></div>' } } }).$mount() expect(vm.$el.children[0].children[0].hasAttribute('foo')).toBe(true) expect(vm.$el.children[0].children[0].hasAttribute('bar')).toBe(true) }) // #4774 it('should not discard parent scopeId when component root element is replaced', done => { const vm = new Vue({ _scopeId: 'data-1', template: `<div><child ref="child" /></div>`, components: { child: { _scopeId: 'data-2', data: () => ({ show: true }), template: '<div v-if="show"></div>' } } }).$mount() const child = vm.$refs.child expect(child.$el.hasAttribute('data-1')).toBe(true) expect(child.$el.hasAttribute('data-2')).toBe(true) child.show = false waitForUpdate(() => { child.show = true }).then(() => { expect(child.$el.hasAttribute('data-1')).toBe(true) expect(child.$el.hasAttribute('data-2')).toBe(true) }).then(done) }) })
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/vdom/helpers/update-listeners.js
47
/* @flow */ import { cached } from 'shared/util' import { warn } from 'core/util/index' const normalizeEvent = cached((name: string): { name: string, once: boolean, capture: boolean } => { const once = name.charAt(0) === '~' // Prefixed last, checked first name = once ? name.slice(1) : name const capture = name.charAt(0) === '!' name = capture ? name.slice(1) : name return { name, once, capture } }) function createEventHandle (fn: Function | Array<Function>): { fn: Function | Array<Function>; invoker: Function; } { const handle = { fn, invoker: function () { const fn = handle.fn if (Array.isArray(fn)) { for (let i = 0; i < fn.length; i++) { fn[i].apply(null, arguments) } } else { fn.apply(null, arguments) } } } return handle } export function updateListeners ( on: Object, oldOn: Object, add: Function, remove: Function, vm: Component ) { let name, cur, old, event for (name in on) { cur = on[name] old = oldOn[name] event = normalizeEvent(name) if (!cur) { process.env.NODE_ENV !== 'production' && warn( `Invalid handler for event "${event.name}": got ` + String(cur), vm ) } else if (!old) { if (!cur.invoker) { cur = on[name] = createEventHandle(cur) } add(event.name, cur.invoker, event.once, event.capture) } else if (cur !== old) { old.fn = cur on[name] = old } } for (name in oldOn) { if (!on[name]) { event = normalizeEvent(name) remove(event.name, oldOn[name].invoker, event.capture) } } }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/instance/render-helpers/render-slot.js
34
/* @flow */ import { extend, warn } from 'core/util/index' /** * Runtime helper for rendering <slot> */ export function renderSlot ( name: string, fallback: ?Array<VNode>, props: ?Object, bindObject: ?Object ): ?Array<VNode> { const scopedSlotFn = this.$scopedSlots[name] if (scopedSlotFn) { // scoped slot props = props || {} if (bindObject) { extend(props, bindObject) } return scopedSlotFn(props) || fallback } else { const slotNodes = this.$slots[name] // warn duplicate slot usage if (slotNodes && process.env.NODE_ENV !== 'production') { slotNodes._rendered && warn( `Duplicate presence of slot "${name}" found in the same render tree ` + `- this will likely cause render errors.`, this ) slotNodes._rendered = true } return slotNodes || fallback } }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/instance/render-helpers/resolve-slots.js
50
/* @flow */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ export function resolveSlots ( children: ?Array<VNode>, context: ?Component ): { [key: string]: Array<VNode> } { const slots = {} if (!children) { return slots } const defaultSlot = [] let name, child for (let i = 0, l = children.length; i < l; i++) { child = children[i] // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && child.data && (name = child.data.slot)) { const slot = (slots[name] || (slots[name] = [])) if (child.tag === 'template') { slot.push.apply(slot, child.children) } else { slot.push(child) } } else { defaultSlot.push(child) } } // ignore single whitespace if (defaultSlot.length && !( defaultSlot.length === 1 && (defaultSlot[0].text === ' ' || defaultSlot[0].isComment) )) { slots.default = defaultSlot } return slots } export function resolveScopedSlots ( fns: Array<[string, Function]> ): { [key: string]: Function } { const res = {} for (let i = 0; i < fns.length; i++) { res[fns[i][0]] = fns[i][1] } return res }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/instance/render-helpers/render-list.js
32
/* @flow */ import { isObject } from 'core/util/index' /** * Runtime helper for rendering v-for lists. */ export function renderList ( val: any, render: () => VNode ): ?Array<VNode> { let ret: ?Array<VNode>, i, l, keys, key if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length) for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i) } } else if (typeof val === 'number') { ret = new Array(val) for (i = 0; i < val; i++) { ret[i] = render(i + 1, i) } } else if (isObject(val)) { keys = Object.keys(val) ret = new Array(keys.length) for (i = 0, l = keys.length; i < l; i++) { key = keys[i] ret[i] = render(val[key], key, i) } } return ret }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/instance/render-helpers/resolve-filter.js
10
/* @flow */ import { identity, resolveAsset } from 'core/util/index' /** * Runtime helper for resolving filters */ export function resolveFilter (id: string): Function { return resolveAsset(this.$options, 'filters', id, true) || identity }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/platforms/weex/runtime/components/transition.js
9
// reuse same transition component logic from web export { transitionProps, extractTransitionData } from 'web/runtime/components/transition' import Transition from 'web/runtime/components/transition' export default Transition
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/core/instance/render-helpers/check-keycodes.js
19
/* @flow */ import config from 'core/config' /** * Runtime helper for checking keyCodes from config. */ export function checkKeyCodes ( eventKeyCode: number, key: string, builtInAlias: number | Array<number> | void ): boolean { const keyCodes = config.keyCodes[key] || builtInAlias if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
src/platforms/weex/runtime/components/index.js
7
import Transition from './transition' import TransitionGroup from './transition-group' export default { Transition, TransitionGroup }
vuejs_vue
2017-01-25
af1ec1ba99b8312777770d21e9b2aded6e5944e3
drivers/gles3/rasterizer_storage_gles3.cpp
6,501
#include "rasterizer_storage_gles3.h" #include "rasterizer_canvas_gles3.h" #include "rasterizer_scene_gles3.h" #include "globals.h" /* TEXTURE API */ #define _EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 #define _EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG 0x8C01 #define _EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 #define _EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG 0x8C03 #define _EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT 0x8A54 #define _EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT 0x8A55 #define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT 0x8A56 #define _EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT 0x8A57 #define _EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 #define _EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 #define _EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 #define _EXT_COMPRESSED_LUMINANCE_LATC1_EXT 0x8C70 #define _EXT_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT 0x8C71 #define _EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT 0x8C72 #define _EXT_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT 0x8C73 #define _EXT_COMPRESSED_RED_RGTC1_EXT 0x8DBB #define _EXT_COMPRESSED_RED_RGTC1 0x8DBB #define _EXT_COMPRESSED_SIGNED_RED_RGTC1 0x8DBC #define _EXT_COMPRESSED_RG_RGTC2 0x8DBD #define _EXT_COMPRESSED_SIGNED_RG_RGTC2 0x8DBE #define _EXT_COMPRESSED_SIGNED_RED_RGTC1_EXT 0x8DBC #define _EXT_COMPRESSED_RED_GREEN_RGTC2_EXT 0x8DBD #define _EXT_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT 0x8DBE #define _EXT_ETC1_RGB8_OES 0x8D64 #define _EXT_SLUMINANCE_NV 0x8C46 #define _EXT_SLUMINANCE_ALPHA_NV 0x8C44 #define _EXT_SRGB8_NV 0x8C41 #define _EXT_SLUMINANCE8_NV 0x8C47 #define _EXT_SLUMINANCE8_ALPHA8_NV 0x8C45 #define _EXT_COMPRESSED_SRGB_S3TC_DXT1_NV 0x8C4C #define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV 0x8C4D #define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV 0x8C4E #define _EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV 0x8C4F #define _EXT_ATC_RGB_AMD 0x8C92 #define _EXT_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93 #define _EXT_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE #define _EXT_TEXTURE_CUBE_MAP_SEAMLESS 0x884F #define _GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE #define _GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF #define _EXT_COMPRESSED_R11_EAC 0x9270 #define _EXT_COMPRESSED_SIGNED_R11_EAC 0x9271 #define _EXT_COMPRESSED_RG11_EAC 0x9272 #define _EXT_COMPRESSED_SIGNED_RG11_EAC 0x9273 #define _EXT_COMPRESSED_RGB8_ETC2 0x9274 #define _EXT_COMPRESSED_SRGB8_ETC2 0x9275 #define _EXT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9276 #define _EXT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 0x9277 #define _EXT_COMPRESSED_RGBA8_ETC2_EAC 0x9278 #define _EXT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC 0x9279 #define _EXT_COMPRESSED_RGBA_BPTC_UNORM 0x8E8C #define _EXT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM 0x8E8D #define _EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT 0x8E8E #define _EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT 0x8E8F GLuint RasterizerStorageGLES3::system_fbo = 0; Image RasterizerStorageGLES3::_get_gl_image_and_format(const Image& p_image, Image::Format p_format, uint32_t p_flags,GLenum& r_gl_format,GLenum& r_gl_internal_format,GLenum &r_gl_type,bool &r_compressed,bool &srgb) { r_compressed=false; r_gl_format=0; Image image=p_image; srgb=false; bool need_decompress=false; switch(p_format) { case Image::FORMAT_L8: { r_gl_internal_format=GL_R8; r_gl_format=GL_RED; r_gl_type=GL_UNSIGNED_BYTE; } break; case Image::FORMAT_LA8: { r_gl_internal_format=GL_RG8; r_gl_format=GL_RG; r_gl_type=GL_UNSIGNED_BYTE; } break; case Image::FORMAT_R8: { r_gl_internal_format=GL_R8; r_gl_format=GL_RED; r_gl_type=GL_UNSIGNED_BYTE; } break; case Image::FORMAT_RG8: { r_gl_internal_format=GL_RG8; r_gl_format=GL_RG; r_gl_type=GL_UNSIGNED_BYTE; } break; case Image::FORMAT_RGB8: { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?GL_SRGB8:GL_RGB8; r_gl_format=GL_RGB; r_gl_type=GL_UNSIGNED_BYTE; srgb=true; } break; case Image::FORMAT_RGBA8: { r_gl_format=GL_RGBA; r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?GL_SRGB8_ALPHA8:GL_RGBA8; r_gl_type=GL_UNSIGNED_BYTE; srgb=true; } break; case Image::FORMAT_RGB565: { #ifdef IPHONE_ENABLED r_gl_internal_format=GL_RGB565; #else //#warning TODO: Convert tod 555 if 565 is not supported (GLES3.3-) r_gl_internal_format=GL_RGB5; #endif //r_gl_internal_format=GL_RGB565; r_gl_format=GL_RGB; r_gl_type=GL_UNSIGNED_SHORT_5_6_5; } break; case Image::FORMAT_RGBA4444: { r_gl_internal_format=GL_RGBA4; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_SHORT_4_4_4_4; } break; case Image::FORMAT_RGBA5551: { r_gl_internal_format=GL_RGB5_A1; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_SHORT_5_5_5_1; } break; case Image::FORMAT_RF: { r_gl_internal_format=GL_R32F; r_gl_format=GL_RED; r_gl_type=GL_FLOAT; } break; case Image::FORMAT_RGF: { r_gl_internal_format=GL_RG32F; r_gl_format=GL_RG; r_gl_type=GL_FLOAT; } break; case Image::FORMAT_RGBF: { r_gl_internal_format=GL_RGB32F; r_gl_format=GL_RGB; r_gl_type=GL_FLOAT; } break; case Image::FORMAT_RGBAF: { r_gl_internal_format=GL_RGBA32F; r_gl_format=GL_RGBA; r_gl_type=GL_FLOAT; } break; case Image::FORMAT_RH: { r_gl_internal_format=GL_R32F; r_gl_format=GL_RED; r_gl_type=GL_HALF_FLOAT; } break; case Image::FORMAT_RGH: { r_gl_internal_format=GL_RG32F; r_gl_format=GL_RG; r_gl_type=GL_HALF_FLOAT; } break; case Image::FORMAT_RGBH: { r_gl_internal_format=GL_RGB32F; r_gl_format=GL_RGB; r_gl_type=GL_HALF_FLOAT; } break; case Image::FORMAT_RGBAH: { r_gl_internal_format=GL_RGBA32F; r_gl_format=GL_RGBA; r_gl_type=GL_HALF_FLOAT; } break; case Image::FORMAT_DXT1: { if (config.s3tc_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT1_EXT; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_DXT3: { if (config.s3tc_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT3_EXT; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_DXT5: { if (config.s3tc_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV:_EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_ATI1: { if (config.latc_supported) { r_gl_internal_format=_EXT_COMPRESSED_LUMINANCE_LATC1_EXT; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_ATI2: { if (config.latc_supported) { r_gl_internal_format=_EXT_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; } else { need_decompress=true; } } break; case Image::FORMAT_BPTC_RGBA: { if (config.bptc_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM:_EXT_COMPRESSED_RGBA_BPTC_UNORM; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_BPTC_RGBF: { if (config.bptc_supported) { r_gl_internal_format=_EXT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT; r_gl_format=GL_RGB; r_gl_type=GL_FLOAT; r_compressed=true; } else { need_decompress=true; } } break; case Image::FORMAT_BPTC_RGBFU: { if (config.bptc_supported) { r_gl_internal_format=_EXT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT; r_gl_format=GL_RGB; r_gl_type=GL_FLOAT; r_compressed=true; } else { need_decompress=true; } } break; case Image::FORMAT_PVRTC2: { if (config.pvrtc_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_PVRTC_2BPPV1_EXT:_EXT_COMPRESSED_RGB_PVRTC_2BPPV1_IMG; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_PVRTC2A: { if (config.pvrtc_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_PVRTC_2BPPV1_EXT:_EXT_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_PVRTC4: { if (config.pvrtc_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_PVRTC_4BPPV1_EXT:_EXT_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_PVRTC4A: { if (config.pvrtc_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB_ALPHA_PVRTC_4BPPV1_EXT:_EXT_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_ETC: { if (config.etc_supported) { r_gl_internal_format=_EXT_ETC1_RGB8_OES; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; } else { need_decompress=true; } } break; case Image::FORMAT_ETC2_R11: { if (config.etc2_supported) { r_gl_internal_format=_EXT_COMPRESSED_R11_EAC; r_gl_format=GL_RED; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; } else { need_decompress=true; } } break; case Image::FORMAT_ETC2_R11S: { if (config.etc2_supported) { r_gl_internal_format=_EXT_COMPRESSED_SIGNED_R11_EAC; r_gl_format=GL_RED; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; } else { need_decompress=true; } } break; case Image::FORMAT_ETC2_RG11: { if (config.etc2_supported) { r_gl_internal_format=_EXT_COMPRESSED_RG11_EAC; r_gl_format=GL_RG; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; } else { need_decompress=true; } } break; case Image::FORMAT_ETC2_RG11S: { if (config.etc2_supported) { r_gl_internal_format=_EXT_COMPRESSED_SIGNED_RG11_EAC; r_gl_format=GL_RG; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; } else { need_decompress=true; } } break; case Image::FORMAT_ETC2_RGB8: { if (config.etc2_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB8_ETC2:_EXT_COMPRESSED_RGB8_ETC2; r_gl_format=GL_RGB; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_ETC2_RGBA8: { if (config.etc2_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:_EXT_COMPRESSED_RGBA8_ETC2_EAC; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; case Image::FORMAT_ETC2_RGB8A1: { if (config.etc2_supported) { r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?_EXT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:_EXT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; r_gl_format=GL_RGBA; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=true; srgb=true; } else { need_decompress=true; } } break; default: { ERR_FAIL_V(Image()); } } if (need_decompress) { if (!image.empty()) { image.decompress(); ERR_FAIL_COND_V(image.is_compressed(),image); image.convert(Image::FORMAT_RGBA8); } r_gl_format=GL_RGBA; r_gl_internal_format=(config.srgb_decode_supported || p_flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)?GL_SRGB8_ALPHA8:GL_RGBA8; r_gl_type=GL_UNSIGNED_BYTE; r_compressed=false; srgb=true; return image; } return image; } static const GLenum _cube_side_enum[6]={ GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, }; RID RasterizerStorageGLES3::texture_create() { Texture *texture = memnew(Texture); ERR_FAIL_COND_V(!texture,RID()); glGenTextures(1, &texture->tex_id); texture->active=false; texture->total_data_size=0; return texture_owner.make_rid( texture ); } void RasterizerStorageGLES3::texture_allocate(RID p_texture,int p_width, int p_height,Image::Format p_format,uint32_t p_flags) { int components; GLenum format; GLenum internal_format; GLenum type; bool compressed; bool srgb; if (p_flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING) { p_flags&=~VS::TEXTURE_FLAG_MIPMAPS; // no mipies for video } Texture *texture = texture_owner.get( p_texture ); ERR_FAIL_COND(!texture); texture->width=p_width; texture->height=p_height; texture->format=p_format; texture->flags=p_flags; texture->stored_cube_sides=0; texture->target = (p_flags & VS::TEXTURE_FLAG_CUBEMAP) ? GL_TEXTURE_CUBE_MAP : GL_TEXTURE_2D; _get_gl_image_and_format(Image(),texture->format,texture->flags,format,internal_format,type,compressed,srgb); texture->alloc_width = texture->width; texture->alloc_height = texture->height; texture->gl_format_cache=format; texture->gl_type_cache=type; texture->gl_internal_format_cache=internal_format; texture->compressed=compressed; texture->srgb=srgb; texture->data_size=0; texture->mipmaps=1; glActiveTexture(GL_TEXTURE0); glBindTexture(texture->target, texture->tex_id); if (p_flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING) { //prealloc if video glTexImage2D(texture->target, 0, internal_format, p_width, p_height, 0, format, type,NULL); } texture->active=true; } void RasterizerStorageGLES3::texture_set_data(RID p_texture,const Image& p_image,VS::CubeMapSide p_cube_side) { Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND(!texture); ERR_FAIL_COND(!texture->active); ERR_FAIL_COND(texture->render_target); ERR_FAIL_COND(texture->format != p_image.get_format() ); ERR_FAIL_COND( p_image.empty() ); GLenum type; GLenum format; GLenum internal_format; bool compressed; bool srgb; if (config.keep_original_textures && !(texture->flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING)) { texture->images[p_cube_side]=p_image; } Image img = _get_gl_image_and_format(p_image, p_image.get_format(),texture->flags,format,internal_format,type,compressed,srgb); if (config.shrink_textures_x2 && (p_image.has_mipmaps() || !p_image.is_compressed()) && !(texture->flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING)) { texture->alloc_height = MAX(1,texture->alloc_height/2); texture->alloc_width = MAX(1,texture->alloc_width/2); if (texture->alloc_width == img.get_width()/2 && texture->alloc_height == img.get_height()/2) { img.shrink_x2(); } else if (img.get_format() <= Image::FORMAT_RGB565) { img.resize(texture->alloc_width, texture->alloc_height, Image::INTERPOLATE_BILINEAR); } }; GLenum blit_target = (texture->target == GL_TEXTURE_CUBE_MAP)?_cube_side_enum[p_cube_side]:GL_TEXTURE_2D; texture->data_size=img.get_data().size(); PoolVector<uint8_t>::Read read = img.get_data().read(); glActiveTexture(GL_TEXTURE0); glBindTexture(texture->target, texture->tex_id); texture->ignore_mipmaps = compressed && !img.has_mipmaps(); if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,config.use_fast_texture_filter?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR_MIPMAP_LINEAR); else { if (texture->flags&VS::TEXTURE_FLAG_FILTER) { glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR); } else { glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_NEAREST); } } if (config.srgb_decode_supported && srgb) { if (texture->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) { glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT); texture->using_srgb=true; } else { glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_SKIP_DECODE_EXT); texture->using_srgb=false; } } if (texture->flags&VS::TEXTURE_FLAG_FILTER) { glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering } else { glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // raw Filtering } if ((texture->flags&VS::TEXTURE_FLAG_REPEAT || texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) { if (texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT){ glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT ); } else{ glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); } } else { //glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE ); glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); } //set swizle for older format compatibility switch(texture->format) { case Image::FORMAT_L8: { glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_R,GL_RED); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_G,GL_RED); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_B,GL_RED); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_A,GL_ONE); } break; case Image::FORMAT_LA8: { glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_R,GL_RED); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_G,GL_RED); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_B,GL_RED); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_A,GL_GREEN); } break; default: { glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_R,GL_RED); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_G,GL_GREEN); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_B,GL_BLUE); glTexParameteri(texture->target,GL_TEXTURE_SWIZZLE_A,GL_ALPHA); } break; } if (config.use_anisotropic_filter) { if (texture->flags&VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) { glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, config.anisotropic_level); } else { glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); } } int mipmaps= (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && img.has_mipmaps()) ? img.get_mipmap_count() +1: 1; int w=img.get_width(); int h=img.get_height(); int tsize=0; for(int i=0;i<mipmaps;i++) { int size,ofs; img.get_mipmap_offset_and_size(i,ofs,size); //print_line("mipmap: "+itos(i)+" size: "+itos(size)+" w: "+itos(mm_w)+", h: "+itos(mm_h)); if (texture->compressed) { glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glCompressedTexImage2D( blit_target, i, format,w,h,0,size,&read[ofs] ); } else { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); if (texture->flags&VS::TEXTURE_FLAG_USED_FOR_STREAMING) { glTexSubImage2D( blit_target, i, 0,0,w, h,format,type,&read[ofs] ); } else { glTexImage2D(blit_target, i, internal_format, w, h, 0, format, type,&read[ofs]); } } tsize+=size; w = MAX(1,w>>1); h = MAX(1,h>>1); } info.texture_mem-=texture->total_data_size; texture->total_data_size=tsize; info.texture_mem+=texture->total_data_size; //printf("texture: %i x %i - size: %i - total: %i\n",texture->width,texture->height,tsize,_rinfo.texture_mem); texture->stored_cube_sides|=(1<<p_cube_side); if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && mipmaps==1 && !texture->ignore_mipmaps && (!(texture->flags&VS::TEXTURE_FLAG_CUBEMAP) || texture->stored_cube_sides==(1<<6)-1)) { //generate mipmaps if they were requested and the image does not contain them glGenerateMipmap(texture->target); } texture->mipmaps=mipmaps; //texture_set_flags(p_texture,texture->flags); } Image RasterizerStorageGLES3::texture_get_data(RID p_texture,VS::CubeMapSide p_cube_side) const { Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND_V(!texture,Image()); ERR_FAIL_COND_V(!texture->active,Image()); ERR_FAIL_COND_V(texture->data_size==0,Image()); ERR_FAIL_COND_V(texture->render_target,Image()); if (!texture->images[p_cube_side].empty()) return texture->images[p_cube_side]; #ifdef GLES_OVER_GL PoolVector<uint8_t> data; int data_size = Image::get_image_data_size(texture->alloc_width,texture->alloc_height,texture->format,texture->mipmaps>1?-1:0); data.resize(data_size*2); //add some memory at the end, just in case for buggy drivers PoolVector<uint8_t>::Write wb = data.write(); glActiveTexture(GL_TEXTURE0); glBindTexture(texture->target,texture->tex_id); glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); print_line("GET FORMAT: "+Image::get_format_name(texture->format)+" mipmaps: "+itos(texture->mipmaps)); for(int i=0;i<texture->mipmaps;i++) { int ofs=0; if (i>0) { ofs=Image::get_image_data_size(texture->alloc_width,texture->alloc_height,texture->format,i-1); } if (texture->compressed) { glPixelStorei(GL_PACK_ALIGNMENT, 4); glGetCompressedTexImage(texture->target,i,&wb[ofs]); } else { glPixelStorei(GL_PACK_ALIGNMENT, 1); glGetTexImage(texture->target,i,texture->gl_format_cache,texture->gl_type_cache,&wb[ofs]); } } wb=PoolVector<uint8_t>::Write(); data.resize(data_size); Image img(texture->alloc_width,texture->alloc_height,texture->mipmaps>1?true:false,texture->format,data); return img; #else ERR_EXPLAIN("Sorry, It's not posible to obtain images back in OpenGL ES"); return Image(); #endif } void RasterizerStorageGLES3::texture_set_flags(RID p_texture,uint32_t p_flags) { Texture *texture = texture_owner.get( p_texture ); ERR_FAIL_COND(!texture); if (texture->render_target) { p_flags&=VS::TEXTURE_FLAG_FILTER;//can change only filter } bool had_mipmaps = texture->flags&VS::TEXTURE_FLAG_MIPMAPS; glActiveTexture(GL_TEXTURE0); glBindTexture(texture->target, texture->tex_id); uint32_t cube = texture->flags & VS::TEXTURE_FLAG_CUBEMAP; texture->flags=p_flags|cube; // can't remove a cube from being a cube if ((texture->flags&VS::TEXTURE_FLAG_REPEAT || texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT) && texture->target != GL_TEXTURE_CUBE_MAP) { if (texture->flags&VS::TEXTURE_FLAG_MIRRORED_REPEAT){ glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT ); } else { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); } } else { //glTexParameterf( texture->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE ); glTexParameterf( texture->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameterf( texture->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); } if (config.use_anisotropic_filter) { if (texture->flags&VS::TEXTURE_FLAG_ANISOTROPIC_FILTER) { glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, config.anisotropic_level); } else { glTexParameterf(texture->target, _GL_TEXTURE_MAX_ANISOTROPY_EXT, 1); } } if (texture->flags&VS::TEXTURE_FLAG_MIPMAPS && !texture->ignore_mipmaps) { if (!had_mipmaps && texture->mipmaps==1) { glGenerateMipmap(texture->target); } glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,config.use_fast_texture_filter?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR_MIPMAP_LINEAR); } else{ if (texture->flags&VS::TEXTURE_FLAG_FILTER) { glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_LINEAR); } else { glTexParameteri(texture->target,GL_TEXTURE_MIN_FILTER,GL_NEAREST); } } if (config.srgb_decode_supported && texture->srgb) { if (texture->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR) { glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT); texture->using_srgb=true; } else { glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_SKIP_DECODE_EXT); texture->using_srgb=false; } } if (texture->flags&VS::TEXTURE_FLAG_FILTER) { glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_LINEAR); // Linear Filtering } else { glTexParameteri(texture->target,GL_TEXTURE_MAG_FILTER,GL_NEAREST); // raw Filtering } } uint32_t RasterizerStorageGLES3::texture_get_flags(RID p_texture) const { Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND_V(!texture,0); return texture->flags; } Image::Format RasterizerStorageGLES3::texture_get_format(RID p_texture) const { Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND_V(!texture,Image::FORMAT_L8); return texture->format; } uint32_t RasterizerStorageGLES3::texture_get_width(RID p_texture) const { Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND_V(!texture,0); return texture->width; } uint32_t RasterizerStorageGLES3::texture_get_height(RID p_texture) const { Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND_V(!texture,0); return texture->height; } void RasterizerStorageGLES3::texture_set_size_override(RID p_texture,int p_width, int p_height) { Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND(!texture); ERR_FAIL_COND(texture->render_target); ERR_FAIL_COND(p_width<=0 || p_width>16384); ERR_FAIL_COND(p_height<=0 || p_height>16384); //real texture size is in alloc width and height texture->width=p_width; texture->height=p_height; } void RasterizerStorageGLES3::texture_set_path(RID p_texture,const String& p_path) { Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND(!texture); texture->path=p_path; } String RasterizerStorageGLES3::texture_get_path(RID p_texture) const{ Texture * texture = texture_owner.get(p_texture); ERR_FAIL_COND_V(!texture,String()); return texture->path; } void RasterizerStorageGLES3::texture_debug_usage(List<VS::TextureInfo> *r_info){ List<RID> textures; texture_owner.get_owned_list(&textures); for (List<RID>::Element *E=textures.front();E;E=E->next()) { Texture *t = texture_owner.get(E->get()); if (!t) continue; VS::TextureInfo tinfo; tinfo.path=t->path; tinfo.format=t->format; tinfo.size.x=t->alloc_width; tinfo.size.y=t->alloc_height; tinfo.bytes=t->total_data_size; r_info->push_back(tinfo); } } void RasterizerStorageGLES3::texture_set_shrink_all_x2_on_set_data(bool p_enable) { config.shrink_textures_x2=p_enable; } void RasterizerStorageGLES3::textures_keep_original(bool p_enable) { config.keep_original_textures=p_enable; } RID RasterizerStorageGLES3::texture_create_radiance_cubemap(RID p_source,int p_resolution) const { Texture * texture = texture_owner.get(p_source); ERR_FAIL_COND_V(!texture,RID()); ERR_FAIL_COND_V(!(texture->flags&VS::TEXTURE_FLAG_CUBEMAP),RID()); bool use_float=true; if (p_resolution<0) { p_resolution=texture->width; } glBindVertexArray(0); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); glActiveTexture(GL_TEXTURE0); glBindTexture(texture->target, texture->tex_id); if (config.srgb_decode_supported && texture->srgb && !texture->using_srgb) { glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT); texture->using_srgb=true; #ifdef TOOLS_ENABLED if (!(texture->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) { texture->flags|=VS::TEXTURE_FLAG_CONVERT_TO_LINEAR; //notify that texture must be set to linear beforehand, so it works in other platforms when exported } #endif } glActiveTexture(GL_TEXTURE1); GLuint new_cubemap; glGenTextures(1, &new_cubemap); glBindTexture(GL_TEXTURE_CUBE_MAP, new_cubemap); GLuint tmp_fb; glGenFramebuffers(1, &tmp_fb); glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb); int size = p_resolution; int lod=0; shaders.cubemap_filter.bind(); int mipmaps=6; int mm_level=mipmaps; GLenum internal_format = use_float?GL_RGBA16F:GL_RGB10_A2; GLenum format = GL_RGBA; GLenum type = use_float?GL_HALF_FLOAT:GL_UNSIGNED_INT_2_10_10_10_REV; while(mm_level) { for(int i=0;i<6;i++) { glTexImage2D(_cube_side_enum[i], lod, internal_format, size, size, 0, format, type, NULL); } lod++; mm_level--; if (size>1) size>>=1; } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, lod-1); lod=0; mm_level=mipmaps; size = p_resolution; shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID,false); while(mm_level) { for(int i=0;i<6;i++) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, _cube_side_enum[i], new_cubemap, lod); glViewport(0,0,size,size); glBindVertexArray(resources.quadie_array); shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::FACE_ID,i); shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS,lod/float(mipmaps-1)); glDrawArrays(GL_TRIANGLE_FAN,0,4); glBindVertexArray(0); #ifdef DEBUG_ENABLED GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE); #endif } if (size>1) size>>=1; lod++; mm_level--; } //restore ranges glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_LEVEL, lod-1); glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo); glDeleteFramebuffers(1, &tmp_fb); Texture * ctex = memnew( Texture ); ctex->flags=VS::TEXTURE_FLAG_CUBEMAP|VS::TEXTURE_FLAG_MIPMAPS|VS::TEXTURE_FLAG_FILTER; ctex->width=p_resolution; ctex->height=p_resolution; ctex->alloc_width=p_resolution; ctex->alloc_height=p_resolution; ctex->format=use_float?Image::FORMAT_RGBAH:Image::FORMAT_RGBA8; ctex->target=GL_TEXTURE_CUBE_MAP; ctex->gl_format_cache=format; ctex->gl_internal_format_cache=internal_format; ctex->gl_type_cache=type; ctex->data_size=0; ctex->compressed=false; ctex->srgb=false; ctex->total_data_size=0; ctex->ignore_mipmaps=false; ctex->mipmaps=mipmaps; ctex->active=true; ctex->tex_id=new_cubemap; ctex->stored_cube_sides=(1<<6)-1; ctex->render_target=NULL; return texture_owner.make_rid(ctex); } RID RasterizerStorageGLES3::skybox_create() { SkyBox *skybox = memnew( SkyBox ); skybox->radiance=0; return skybox_owner.make_rid(skybox); } void RasterizerStorageGLES3::skybox_set_texture(RID p_skybox, RID p_cube_map, int p_radiance_size){ SkyBox *skybox = skybox_owner.getornull(p_skybox); ERR_FAIL_COND(!skybox); if (skybox->cubemap.is_valid()) { skybox->cubemap=RID(); glDeleteTextures(1,&skybox->radiance); skybox->radiance=0; } skybox->cubemap=p_cube_map; if (!skybox->cubemap.is_valid()) return; //cleared Texture *texture = texture_owner.getornull(skybox->cubemap); if (!texture || !(texture->flags&VS::TEXTURE_FLAG_CUBEMAP)) { skybox->cubemap=RID(); ERR_FAIL_COND(!texture || !(texture->flags&VS::TEXTURE_FLAG_CUBEMAP)); } glBindVertexArray(0); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glDisable(GL_BLEND); glActiveTexture(GL_TEXTURE0); glBindTexture(texture->target, texture->tex_id); if (config.srgb_decode_supported && texture->srgb && !texture->using_srgb) { glTexParameteri(texture->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT); texture->using_srgb=true; #ifdef TOOLS_ENABLED if (!(texture->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) { texture->flags|=VS::TEXTURE_FLAG_CONVERT_TO_LINEAR; //notify that texture must be set to linear beforehand, so it works in other platforms when exported } #endif } glActiveTexture(GL_TEXTURE1); glGenTextures(1, &skybox->radiance); glBindTexture(GL_TEXTURE_2D, skybox->radiance); GLuint tmp_fb; glGenFramebuffers(1, &tmp_fb); glBindFramebuffer(GL_FRAMEBUFFER, tmp_fb); int size = p_radiance_size; int lod=0; int mipmaps=6; int mm_level=mipmaps; bool use_float=true; GLenum internal_format = use_float?GL_RGBA16F:GL_RGB10_A2; GLenum format = GL_RGBA; GLenum type = use_float?GL_HALF_FLOAT:GL_UNSIGNED_INT_2_10_10_10_REV; while(mm_level) { glTexImage2D(GL_TEXTURE_2D, lod, internal_format, size, size*2, 0, format, type, NULL); lod++; mm_level--; if (size>1) size>>=1; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, lod-1); lod=0; mm_level=mipmaps; size = p_radiance_size; shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID,true); shaders.cubemap_filter.bind(); while(mm_level) { glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, skybox->radiance, lod); #ifdef DEBUG_ENABLED GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE); #endif for(int i=0;i<2;i++) { glViewport(0,i*size,size,size); glBindVertexArray(resources.quadie_array); shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP,i>0); shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS,lod/float(mipmaps-1)); glDrawArrays(GL_TRIANGLE_FAN,0,4); glBindVertexArray(0); } if (size>1) size>>=1; lod++; mm_level--; } shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID,false); //restore ranges glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, lod-1); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo); glDeleteFramebuffers(1, &tmp_fb); } /* SHADER API */ RID RasterizerStorageGLES3::shader_create(VS::ShaderMode p_mode){ Shader *shader = memnew( Shader ); shader->mode=p_mode; RID rid = shader_owner.make_rid(shader); shader_set_mode(rid,p_mode); _shader_make_dirty(shader); shader->self=rid; return rid; } void RasterizerStorageGLES3::_shader_make_dirty(Shader* p_shader) { if (p_shader->dirty_list.in_list()) return; _shader_dirty_list.add(&p_shader->dirty_list); } void RasterizerStorageGLES3::shader_set_mode(RID p_shader,VS::ShaderMode p_mode){ ERR_FAIL_INDEX(p_mode,VS::SHADER_MAX); Shader *shader=shader_owner.get(p_shader); ERR_FAIL_COND(!shader); if (shader->custom_code_id && p_mode==shader->mode) return; if (shader->custom_code_id) { shader->shader->free_custom_shader(shader->custom_code_id); shader->custom_code_id=0; } shader->mode=p_mode; ShaderGLES3* shaders[VS::SHADER_MAX]={ &scene->state.scene_shader, &canvas->state.canvas_shader, &this->shaders.particles, }; shader->shader=shaders[p_mode]; shader->custom_code_id = shader->shader->create_custom_shader(); _shader_make_dirty(shader); } VS::ShaderMode RasterizerStorageGLES3::shader_get_mode(RID p_shader) const { const Shader *shader=shader_owner.get(p_shader); ERR_FAIL_COND_V(!shader,VS::SHADER_MAX); return shader->mode; } void RasterizerStorageGLES3::shader_set_code(RID p_shader, const String& p_code){ Shader *shader=shader_owner.get(p_shader); ERR_FAIL_COND(!shader); shader->code=p_code; _shader_make_dirty(shader); } String RasterizerStorageGLES3::shader_get_code(RID p_shader) const{ const Shader *shader=shader_owner.get(p_shader); ERR_FAIL_COND_V(!shader,String()); return shader->code; } void RasterizerStorageGLES3::_update_shader(Shader* p_shader) const { _shader_dirty_list.remove( &p_shader->dirty_list ); p_shader->valid=false; p_shader->uniforms.clear(); ShaderCompilerGLES3::GeneratedCode gen_code; ShaderCompilerGLES3::IdentifierActions *actions=NULL; switch(p_shader->mode) { case VS::SHADER_CANVAS_ITEM: { p_shader->canvas_item.light_mode=Shader::CanvasItem::LIGHT_MODE_NORMAL; p_shader->canvas_item.blend_mode=Shader::CanvasItem::BLEND_MODE_MIX; shaders.actions_canvas.render_mode_values["blend_add"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_ADD); shaders.actions_canvas.render_mode_values["blend_mix"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_MIX); shaders.actions_canvas.render_mode_values["blend_sub"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_SUB); shaders.actions_canvas.render_mode_values["blend_mul"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_MUL); shaders.actions_canvas.render_mode_values["blend_premul_alpha"]=Pair<int*,int>(&p_shader->canvas_item.blend_mode,Shader::CanvasItem::BLEND_MODE_PMALPHA); shaders.actions_canvas.render_mode_values["unshaded"]=Pair<int*,int>(&p_shader->canvas_item.light_mode,Shader::CanvasItem::LIGHT_MODE_UNSHADED); shaders.actions_canvas.render_mode_values["light_only"]=Pair<int*,int>(&p_shader->canvas_item.light_mode,Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY); actions=&shaders.actions_canvas; actions->uniforms=&p_shader->uniforms; } break; case VS::SHADER_SPATIAL: { p_shader->spatial.blend_mode=Shader::Spatial::BLEND_MODE_MIX; p_shader->spatial.depth_draw_mode=Shader::Spatial::DEPTH_DRAW_OPAQUE; p_shader->spatial.cull_mode=Shader::Spatial::CULL_MODE_BACK; p_shader->spatial.uses_alpha=false; p_shader->spatial.uses_discard=false; p_shader->spatial.unshaded=false; p_shader->spatial.ontop=false; p_shader->spatial.uses_sss=false; p_shader->spatial.uses_vertex=false; shaders.actions_scene.render_mode_values["blend_add"]=Pair<int*,int>(&p_shader->spatial.blend_mode,Shader::Spatial::BLEND_MODE_ADD); shaders.actions_scene.render_mode_values["blend_mix"]=Pair<int*,int>(&p_shader->spatial.blend_mode,Shader::Spatial::BLEND_MODE_MIX); shaders.actions_scene.render_mode_values["blend_sub"]=Pair<int*,int>(&p_shader->spatial.blend_mode,Shader::Spatial::BLEND_MODE_SUB); shaders.actions_scene.render_mode_values["blend_mul"]=Pair<int*,int>(&p_shader->spatial.blend_mode,Shader::Spatial::BLEND_MODE_MUL); shaders.actions_scene.render_mode_values["depth_draw_opaque"]=Pair<int*,int>(&p_shader->spatial.depth_draw_mode,Shader::Spatial::DEPTH_DRAW_OPAQUE); shaders.actions_scene.render_mode_values["depth_draw_always"]=Pair<int*,int>(&p_shader->spatial.depth_draw_mode,Shader::Spatial::DEPTH_DRAW_ALWAYS); shaders.actions_scene.render_mode_values["depth_draw_never"]=Pair<int*,int>(&p_shader->spatial.depth_draw_mode,Shader::Spatial::DEPTH_DRAW_NEVER); shaders.actions_scene.render_mode_values["depth_draw_alpha_prepass"]=Pair<int*,int>(&p_shader->spatial.depth_draw_mode,Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS); shaders.actions_scene.render_mode_values["cull_front"]=Pair<int*,int>(&p_shader->spatial.cull_mode,Shader::Spatial::CULL_MODE_FRONT); shaders.actions_scene.render_mode_values["cull_back"]=Pair<int*,int>(&p_shader->spatial.cull_mode,Shader::Spatial::CULL_MODE_BACK); shaders.actions_scene.render_mode_values["cull_disabled"]=Pair<int*,int>(&p_shader->spatial.cull_mode,Shader::Spatial::CULL_MODE_DISABLED); shaders.actions_scene.render_mode_flags["unshaded"]=&p_shader->spatial.unshaded; shaders.actions_scene.render_mode_flags["ontop"]=&p_shader->spatial.ontop; shaders.actions_scene.usage_flag_pointers["ALPHA"]=&p_shader->spatial.uses_alpha; shaders.actions_scene.usage_flag_pointers["VERTEX"]=&p_shader->spatial.uses_vertex; shaders.actions_scene.usage_flag_pointers["SSS_STRENGTH"]=&p_shader->spatial.uses_sss; shaders.actions_scene.usage_flag_pointers["DISCARD"]=&p_shader->spatial.uses_discard; actions=&shaders.actions_scene; actions->uniforms=&p_shader->uniforms; } case VS::SHADER_PARTICLES: { actions=&shaders.actions_particles; actions->uniforms=&p_shader->uniforms; } } Error err = shaders.compiler.compile(p_shader->mode,p_shader->code,actions,p_shader->path,gen_code); ERR_FAIL_COND(err!=OK); p_shader->shader->set_custom_shader_code(p_shader->custom_code_id,gen_code.vertex,gen_code.vertex_global,gen_code.fragment,gen_code.light,gen_code.fragment_global,gen_code.uniforms,gen_code.texture_uniforms,gen_code.defines); p_shader->ubo_size=gen_code.uniform_total_size; p_shader->ubo_offsets=gen_code.uniform_offsets; p_shader->texture_count=gen_code.texture_uniforms.size(); p_shader->texture_hints=gen_code.texture_hints; p_shader->uses_vertex_time=gen_code.uses_vertex_time; p_shader->uses_fragment_time=gen_code.uses_fragment_time; //all materials using this shader will have to be invalidated, unfortunately for (SelfList<Material>* E = p_shader->materials.first();E;E=E->next() ) { _material_make_dirty(E->self()); } p_shader->valid=true; p_shader->version++; } void RasterizerStorageGLES3::update_dirty_shaders() { while( _shader_dirty_list.first() ) { _update_shader(_shader_dirty_list.first()->self() ); } } void RasterizerStorageGLES3::shader_get_param_list(RID p_shader, List<PropertyInfo> *p_param_list) const{ Shader *shader=shader_owner.get(p_shader); ERR_FAIL_COND(!shader); if (shader->dirty_list.in_list()) _update_shader(shader); // ok should be not anymore dirty Map<int,StringName> order; for(Map<StringName,ShaderLanguage::ShaderNode::Uniform>::Element *E=shader->uniforms.front();E;E=E->next()) { order[E->get().order]=E->key(); } for(Map<int,StringName>::Element *E=order.front();E;E=E->next()) { PropertyInfo pi; ShaderLanguage::ShaderNode::Uniform &u=shader->uniforms[E->get()]; pi.name=E->get(); switch(u.type) { case ShaderLanguage::TYPE_VOID: pi.type=Variant::NIL; break; case ShaderLanguage::TYPE_BOOL: pi.type=Variant::BOOL; break; case ShaderLanguage::TYPE_BVEC2: pi.type=Variant::INT; pi.hint=PROPERTY_HINT_FLAGS; pi.hint_string="x,y"; break; case ShaderLanguage::TYPE_BVEC3: pi.type=Variant::INT; pi.hint=PROPERTY_HINT_FLAGS; pi.hint_string="x,y,z"; break; case ShaderLanguage::TYPE_BVEC4: pi.type=Variant::INT; pi.hint=PROPERTY_HINT_FLAGS; pi.hint_string="x,y,z,w"; break; case ShaderLanguage::TYPE_UINT: case ShaderLanguage::TYPE_INT: { pi.type=Variant::INT; if (u.hint==ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) { pi.hint=PROPERTY_HINT_RANGE; pi.hint_string=rtos(u.hint_range[0])+","+rtos(u.hint_range[1]); } } break; case ShaderLanguage::TYPE_IVEC2: case ShaderLanguage::TYPE_IVEC3: case ShaderLanguage::TYPE_IVEC4: case ShaderLanguage::TYPE_UVEC2: case ShaderLanguage::TYPE_UVEC3: case ShaderLanguage::TYPE_UVEC4: { pi.type=Variant::POOL_INT_ARRAY; } break; case ShaderLanguage::TYPE_FLOAT: { pi.type=Variant::REAL; if (u.hint==ShaderLanguage::ShaderNode::Uniform::HINT_RANGE) { pi.hint=PROPERTY_HINT_RANGE; pi.hint_string=rtos(u.hint_range[0])+","+rtos(u.hint_range[1])+","+rtos(u.hint_range[2]); } } break; case ShaderLanguage::TYPE_VEC2: pi.type=Variant::VECTOR2; break; case ShaderLanguage::TYPE_VEC3: pi.type=Variant::VECTOR3; break; case ShaderLanguage::TYPE_VEC4: { if (u.hint==ShaderLanguage::ShaderNode::Uniform::HINT_COLOR) { pi.type=Variant::COLOR; } else { pi.type=Variant::PLANE; } } break; case ShaderLanguage::TYPE_MAT2: pi.type=Variant::TRANSFORM2D; break; case ShaderLanguage::TYPE_MAT3: pi.type=Variant::BASIS; break; case ShaderLanguage::TYPE_MAT4: pi.type=Variant::TRANSFORM; break; case ShaderLanguage::TYPE_SAMPLER2D: case ShaderLanguage::TYPE_ISAMPLER2D: case ShaderLanguage::TYPE_USAMPLER2D: { pi.type=Variant::OBJECT; pi.hint=PROPERTY_HINT_RESOURCE_TYPE; pi.hint_string="Texture"; } break; case ShaderLanguage::TYPE_SAMPLERCUBE: { pi.type=Variant::OBJECT; pi.hint=PROPERTY_HINT_RESOURCE_TYPE; pi.hint_string="CubeMap"; } break; }; p_param_list->push_back(pi); } } void RasterizerStorageGLES3::shader_set_default_texture_param(RID p_shader, const StringName& p_name, RID p_texture){ Shader *shader=shader_owner.get(p_shader); ERR_FAIL_COND(!shader); ERR_FAIL_COND(p_texture.is_valid() && !texture_owner.owns(p_texture)); if (p_texture.is_valid()) shader->default_textures[p_name]=p_texture; else shader->default_textures.erase(p_name); _shader_make_dirty(shader); } RID RasterizerStorageGLES3::shader_get_default_texture_param(RID p_shader, const StringName& p_name) const{ const Shader *shader=shader_owner.get(p_shader); ERR_FAIL_COND_V(!shader,RID()); const Map<StringName,RID>::Element *E=shader->default_textures.find(p_name); if (!E) return RID(); return E->get(); } /* COMMON MATERIAL API */ void RasterizerStorageGLES3::_material_make_dirty(Material* p_material) const { if (p_material->dirty_list.in_list()) return; _material_dirty_list.add(&p_material->dirty_list); } RID RasterizerStorageGLES3::material_create(){ Material *material = memnew( Material ); return material_owner.make_rid(material); } void RasterizerStorageGLES3::material_set_shader(RID p_material, RID p_shader){ Material *material = material_owner.get( p_material ); ERR_FAIL_COND(!material); Shader *shader=shader_owner.getornull(p_shader); if (material->shader) { //if shader, remove from previous shader material list material->shader->materials.remove( &material->list ); } material->shader=shader; if (shader) { shader->materials.add(&material->list); } _material_make_dirty(material); } RID RasterizerStorageGLES3::material_get_shader(RID p_material) const{ const Material *material = material_owner.get( p_material ); ERR_FAIL_COND_V(!material,RID()); if (material->shader) return material->shader->self; return RID(); } void RasterizerStorageGLES3::material_set_param(RID p_material, const StringName& p_param, const Variant& p_value){ Material *material = material_owner.get( p_material ); ERR_FAIL_COND(!material); if (p_value.get_type()==Variant::NIL) material->params.erase(p_param); else material->params[p_param]=p_value; _material_make_dirty(material); } Variant RasterizerStorageGLES3::material_get_param(RID p_material, const StringName& p_param) const{ const Material *material = material_owner.get( p_material ); ERR_FAIL_COND_V(!material,RID()); if (material->params.has(p_param)) return material->params[p_param]; return Variant(); } void RasterizerStorageGLES3::material_set_line_width(RID p_material, float p_width) { Material *material = material_owner.get( p_material ); ERR_FAIL_COND(!material); material->line_width=p_width; } bool RasterizerStorageGLES3::material_is_animated(RID p_material) { Material *material = material_owner.get( p_material ); ERR_FAIL_COND_V(!material,false); if (material->dirty_list.in_list()) { _update_material(material); } return material->is_animated_cache; } bool RasterizerStorageGLES3::material_casts_shadows(RID p_material) { Material *material = material_owner.get( p_material ); ERR_FAIL_COND_V(!material,false); if (material->dirty_list.in_list()) { _update_material(material); } return material->can_cast_shadow_cache; } void RasterizerStorageGLES3::material_add_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) { Material *material = material_owner.get( p_material ); ERR_FAIL_COND(!material); Map<RasterizerScene::InstanceBase*,int>::Element *E=material->instance_owners.find(p_instance); if (E) { E->get()++; } else { material->instance_owners[p_instance]=1; } } void RasterizerStorageGLES3::material_remove_instance_owner(RID p_material, RasterizerScene::InstanceBase *p_instance) { Material *material = material_owner.get( p_material ); ERR_FAIL_COND(!material); Map<RasterizerScene::InstanceBase*,int>::Element *E=material->instance_owners.find(p_instance); ERR_FAIL_COND(!E); E->get()--; if (E->get()==0) { material->instance_owners.erase(E); } } _FORCE_INLINE_ static void _fill_std140_variant_ubo_value(ShaderLanguage::DataType type, const Variant& value, uint8_t *data,bool p_linear_color) { switch(type) { case ShaderLanguage::TYPE_BOOL: { bool v = value; GLuint *gui = (GLuint*)data; *gui = v ? GL_TRUE : GL_FALSE; } break; case ShaderLanguage::TYPE_BVEC2: { int v = value; GLuint *gui = (GLuint*)data; gui[0]=v&1 ? GL_TRUE : GL_FALSE; gui[1]=v&2 ? GL_TRUE : GL_FALSE; } break; case ShaderLanguage::TYPE_BVEC3: { int v = value; GLuint *gui = (GLuint*)data; gui[0]=v&1 ? GL_TRUE : GL_FALSE; gui[1]=v&2 ? GL_TRUE : GL_FALSE; gui[2]=v&4 ? GL_TRUE : GL_FALSE; } break; case ShaderLanguage::TYPE_BVEC4: { int v = value; GLuint *gui = (GLuint*)data; gui[0]=v&1 ? GL_TRUE : GL_FALSE; gui[1]=v&2 ? GL_TRUE : GL_FALSE; gui[2]=v&4 ? GL_TRUE : GL_FALSE; gui[3]=v&8 ? GL_TRUE : GL_FALSE; } break; case ShaderLanguage::TYPE_INT: { int v = value; GLint *gui = (GLint*)data; gui[0]=v; } break; case ShaderLanguage::TYPE_IVEC2: { PoolVector<int> iv = value; int s = iv.size(); GLint *gui = (GLint*)data; PoolVector<int>::Read r = iv.read(); for(int i=0;i<2;i++) { if (i<s) gui[i]=r[i]; else gui[i]=0; } } break; case ShaderLanguage::TYPE_IVEC3: { PoolVector<int> iv = value; int s = iv.size(); GLint *gui = (GLint*)data; PoolVector<int>::Read r = iv.read(); for(int i=0;i<3;i++) { if (i<s) gui[i]=r[i]; else gui[i]=0; } } break; case ShaderLanguage::TYPE_IVEC4: { PoolVector<int> iv = value; int s = iv.size(); GLint *gui = (GLint*)data; PoolVector<int>::Read r = iv.read(); for(int i=0;i<4;i++) { if (i<s) gui[i]=r[i]; else gui[i]=0; } } break; case ShaderLanguage::TYPE_UINT: { int v = value; GLuint *gui = (GLuint*)data; gui[0]=v; } break; case ShaderLanguage::TYPE_UVEC2: { PoolVector<int> iv = value; int s = iv.size(); GLuint *gui = (GLuint*)data; PoolVector<int>::Read r = iv.read(); for(int i=0;i<2;i++) { if (i<s) gui[i]=r[i]; else gui[i]=0; } } break; case ShaderLanguage::TYPE_UVEC3: { PoolVector<int> iv = value; int s = iv.size(); GLuint *gui = (GLuint*)data; PoolVector<int>::Read r = iv.read(); for(int i=0;i<3;i++) { if (i<s) gui[i]=r[i]; else gui[i]=0; } } break; case ShaderLanguage::TYPE_UVEC4: { PoolVector<int> iv = value; int s = iv.size(); GLuint *gui = (GLuint*)data; PoolVector<int>::Read r = iv.read(); for(int i=0;i<4;i++) { if (i<s) gui[i]=r[i]; else gui[i]=0; } } break; case ShaderLanguage::TYPE_FLOAT: { float v = value; GLfloat *gui = (GLfloat*)data; gui[0]=v; } break; case ShaderLanguage::TYPE_VEC2: { Vector2 v = value; GLfloat *gui = (GLfloat*)data; gui[0]=v.x; gui[1]=v.y; } break; case ShaderLanguage::TYPE_VEC3: { Vector3 v = value; GLfloat *gui = (GLfloat*)data; gui[0]=v.x; gui[1]=v.y; gui[2]=v.z; } break; case ShaderLanguage::TYPE_VEC4: { GLfloat *gui = (GLfloat*)data; if (value.get_type()==Variant::COLOR) { Color v=value; if (p_linear_color) { v=v.to_linear(); } gui[0]=v.r; gui[1]=v.g; gui[2]=v.b; gui[3]=v.a; } else if (value.get_type()==Variant::RECT2) { Rect2 v=value; gui[0]=v.pos.x; gui[1]=v.pos.y; gui[2]=v.size.x; gui[3]=v.size.y; } else if (value.get_type()==Variant::QUAT) { Quat v=value; gui[0]=v.x; gui[1]=v.y; gui[2]=v.z; gui[3]=v.w; } else { Plane v=value; gui[0]=v.normal.x; gui[1]=v.normal.y; gui[2]=v.normal.x; gui[3]=v.d; } } break; case ShaderLanguage::TYPE_MAT2: { Transform2D v = value; GLfloat *gui = (GLfloat*)data; gui[ 0]=v.elements[0][0]; gui[ 1]=v.elements[0][1]; gui[ 2]=v.elements[1][0]; gui[ 3]=v.elements[1][1]; } break; case ShaderLanguage::TYPE_MAT3: { Basis v = value; GLfloat *gui = (GLfloat*)data; gui[ 0]=v.elements[0][0]; gui[ 1]=v.elements[1][0]; gui[ 2]=v.elements[2][0]; gui[ 3]=0; gui[ 4]=v.elements[0][1]; gui[ 5]=v.elements[1][1]; gui[ 6]=v.elements[2][1]; gui[ 7]=0; gui[ 8]=v.elements[0][2]; gui[ 9]=v.elements[1][2]; gui[10]=v.elements[2][2]; gui[11]=0; } break; case ShaderLanguage::TYPE_MAT4: { Transform v = value; GLfloat *gui = (GLfloat*)data; gui[ 0]=v.basis.elements[0][0]; gui[ 1]=v.basis.elements[1][0]; gui[ 2]=v.basis.elements[2][0]; gui[ 3]=0; gui[ 4]=v.basis.elements[0][1]; gui[ 5]=v.basis.elements[1][1]; gui[ 6]=v.basis.elements[2][1]; gui[ 7]=0; gui[ 8]=v.basis.elements[0][2]; gui[ 9]=v.basis.elements[1][2]; gui[10]=v.basis.elements[2][2]; gui[11]=0; gui[12]=v.origin.x; gui[13]=v.origin.y; gui[14]=v.origin.z; gui[15]=1; } break; default: {} } } _FORCE_INLINE_ static void _fill_std140_ubo_value(ShaderLanguage::DataType type, const Vector<ShaderLanguage::ConstantNode::Value>& value, uint8_t *data) { switch(type) { case ShaderLanguage::TYPE_BOOL: { GLuint *gui = (GLuint*)data; *gui = value[0].boolean ? GL_TRUE : GL_FALSE; } break; case ShaderLanguage::TYPE_BVEC2: { GLuint *gui = (GLuint*)data; gui[0]=value[0].boolean ? GL_TRUE : GL_FALSE; gui[1]=value[1].boolean ? GL_TRUE : GL_FALSE; } break; case ShaderLanguage::TYPE_BVEC3: { GLuint *gui = (GLuint*)data; gui[0]=value[0].boolean ? GL_TRUE : GL_FALSE; gui[1]=value[1].boolean ? GL_TRUE : GL_FALSE; gui[2]=value[2].boolean ? GL_TRUE : GL_FALSE; } break; case ShaderLanguage::TYPE_BVEC4: { GLuint *gui = (GLuint*)data; gui[0]=value[0].boolean ? GL_TRUE : GL_FALSE; gui[1]=value[1].boolean ? GL_TRUE : GL_FALSE; gui[2]=value[2].boolean ? GL_TRUE : GL_FALSE; gui[3]=value[3].boolean ? GL_TRUE : GL_FALSE; } break; case ShaderLanguage::TYPE_INT: { GLint *gui = (GLint*)data; gui[0]=value[0].sint; } break; case ShaderLanguage::TYPE_IVEC2: { GLint *gui = (GLint*)data; for(int i=0;i<2;i++) { gui[i]=value[i].sint; } } break; case ShaderLanguage::TYPE_IVEC3: { GLint *gui = (GLint*)data; for(int i=0;i<3;i++) { gui[i]=value[i].sint; } } break; case ShaderLanguage::TYPE_IVEC4: { GLint *gui = (GLint*)data; for(int i=0;i<4;i++) { gui[i]=value[i].sint; } } break; case ShaderLanguage::TYPE_UINT: { GLuint *gui = (GLuint*)data; gui[0]=value[0].uint; } break; case ShaderLanguage::TYPE_UVEC2: { GLint *gui = (GLint*)data; for(int i=0;i<2;i++) { gui[i]=value[i].uint; } } break; case ShaderLanguage::TYPE_UVEC3: { GLint *gui = (GLint*)data; for(int i=0;i<3;i++) { gui[i]=value[i].uint; } } break; case ShaderLanguage::TYPE_UVEC4: { GLint *gui = (GLint*)data; for(int i=0;i<4;i++) { gui[i]=value[i].uint; } } break; case ShaderLanguage::TYPE_FLOAT: { GLfloat *gui = (GLfloat*)data; gui[0]=value[0].real; } break; case ShaderLanguage::TYPE_VEC2: { GLfloat *gui = (GLfloat*)data; for(int i=0;i<2;i++) { gui[i]=value[i].real; } } break; case ShaderLanguage::TYPE_VEC3: { GLfloat *gui = (GLfloat*)data; for(int i=0;i<3;i++) { gui[i]=value[i].real; } } break; case ShaderLanguage::TYPE_VEC4: { GLfloat *gui = (GLfloat*)data; for(int i=0;i<4;i++) { gui[i]=value[i].real; } } break; case ShaderLanguage::TYPE_MAT2: { GLfloat *gui = (GLfloat*)data; for(int i=0;i<2;i++) { gui[i]=value[i].real; } } break; case ShaderLanguage::TYPE_MAT3: { GLfloat *gui = (GLfloat*)data; gui[ 0]=value[0].real; gui[ 1]=value[1].real; gui[ 2]=value[2].real; gui[ 3]=0; gui[ 4]=value[3].real; gui[ 5]=value[4].real; gui[ 6]=value[5].real; gui[ 7]=0; gui[ 8]=value[6].real; gui[ 9]=value[7].real; gui[10]=value[8].real; gui[11]=0; } break; case ShaderLanguage::TYPE_MAT4: { GLfloat *gui = (GLfloat*)data; for(int i=0;i<16;i++) { gui[i]=value[i].real; } } break; default: {} } } _FORCE_INLINE_ static void _fill_std140_ubo_empty(ShaderLanguage::DataType type, uint8_t *data) { switch(type) { case ShaderLanguage::TYPE_BOOL: case ShaderLanguage::TYPE_INT: case ShaderLanguage::TYPE_UINT: case ShaderLanguage::TYPE_FLOAT: { zeromem(data,4); } break; case ShaderLanguage::TYPE_BVEC2: case ShaderLanguage::TYPE_IVEC2: case ShaderLanguage::TYPE_UVEC2: case ShaderLanguage::TYPE_VEC2: { zeromem(data,8); } break; case ShaderLanguage::TYPE_BVEC3: case ShaderLanguage::TYPE_IVEC3: case ShaderLanguage::TYPE_UVEC3: case ShaderLanguage::TYPE_VEC3: case ShaderLanguage::TYPE_BVEC4: case ShaderLanguage::TYPE_IVEC4: case ShaderLanguage::TYPE_UVEC4: case ShaderLanguage::TYPE_VEC4: case ShaderLanguage::TYPE_MAT2:{ zeromem(data,16); } break; case ShaderLanguage::TYPE_MAT3:{ zeromem(data,48); } break; case ShaderLanguage::TYPE_MAT4:{ zeromem(data,64); } break; default: {} } } void RasterizerStorageGLES3::_update_material(Material* material) { if (material->dirty_list.in_list()) _material_dirty_list.remove( &material->dirty_list ); if (material->shader && material->shader->dirty_list.in_list()) { _update_shader(material->shader); } //update caches { bool can_cast_shadow = false; bool is_animated = false; if (material->shader && material->shader->mode==VS::SHADER_SPATIAL) { if (!material->shader->spatial.uses_alpha && material->shader->spatial.blend_mode==Shader::Spatial::BLEND_MODE_MIX) { can_cast_shadow=true; } if (material->shader->spatial.uses_discard && material->shader->uses_fragment_time) { is_animated=true; } if (material->shader->spatial.uses_vertex && material->shader->uses_vertex_time) { is_animated=true; } } if (can_cast_shadow!=material->can_cast_shadow_cache || is_animated!=material->is_animated_cache) { material->can_cast_shadow_cache=can_cast_shadow; material->is_animated_cache=is_animated; for(Map<Geometry*,int>::Element *E=material->geometry_owners.front();E;E=E->next()) { E->key()->material_changed_notify(); } for(Map<RasterizerScene::InstanceBase*,int>::Element *E=material->instance_owners.front();E;E=E->next()) { E->key()->base_material_changed(); } } } //clear ubo if it needs to be cleared if (material->ubo_size) { if (!material->shader || material->shader->ubo_size!=material->ubo_size) { //by by ubo glDeleteBuffers(1,&material->ubo_id); material->ubo_id=0; material->ubo_size=0; } } //create ubo if it needs to be created if (material->ubo_size==0 && material->shader && material->shader->ubo_size) { glGenBuffers(1, &material->ubo_id); glBindBuffer(GL_UNIFORM_BUFFER, material->ubo_id); glBufferData(GL_UNIFORM_BUFFER, material->shader->ubo_size, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); material->ubo_size=material->shader->ubo_size; } //fill up the UBO if it needs to be filled if (material->shader && material->ubo_size) { uint8_t* local_ubo = (uint8_t*)alloca(material->ubo_size); for(Map<StringName,ShaderLanguage::ShaderNode::Uniform>::Element *E=material->shader->uniforms.front();E;E=E->next()) { if (E->get().order<0) continue; // texture, does not go here //regular uniform uint8_t *data = &local_ubo[ material->shader->ubo_offsets[E->get().order] ]; Map<StringName,Variant>::Element *V = material->params.find(E->key()); if (V) { //user provided _fill_std140_variant_ubo_value(E->get().type,V->get(),data,material->shader->mode==VS::SHADER_SPATIAL); } else if (E->get().default_value.size()){ //default value _fill_std140_ubo_value(E->get().type,E->get().default_value,data); //value=E->get().default_value; } else { //zero because it was not provided _fill_std140_ubo_empty(E->get().type,data); } } glBindBuffer(GL_UNIFORM_BUFFER,material->ubo_id); glBufferSubData(GL_UNIFORM_BUFFER, 0, material->ubo_size, local_ubo); glBindBuffer(GL_UNIFORM_BUFFER, 0); } //set up the texture array, for easy access when it needs to be drawn if (material->shader && material->shader->texture_count) { material->textures.resize(material->shader->texture_count); for(Map<StringName,ShaderLanguage::ShaderNode::Uniform>::Element *E=material->shader->uniforms.front();E;E=E->next()) { if (E->get().texture_order<0) continue; // not a texture, does not go here RID texture; Map<StringName,Variant>::Element *V = material->params.find(E->key()); if (V) { texture=V->get(); } if (!texture.is_valid()) { Map<StringName,RID>::Element *W = material->shader->default_textures.find(E->key()); if (W) { texture=W->get(); } } material->textures[ E->get().texture_order ]=texture; } } else { material->textures.clear(); } } void RasterizerStorageGLES3::_material_add_geometry(RID p_material,Geometry *p_geometry) { Material * material = material_owner.getornull(p_material); ERR_FAIL_COND(!material); Map<Geometry*,int>::Element *I = material->geometry_owners.find(p_geometry); if (I) { I->get()++; } else { material->geometry_owners[p_geometry]=1; } } void RasterizerStorageGLES3::_material_remove_geometry(RID p_material,Geometry *p_geometry) { Material * material = material_owner.getornull(p_material); ERR_FAIL_COND(!material); Map<Geometry*,int>::Element *I = material->geometry_owners.find(p_geometry); ERR_FAIL_COND(!I); I->get()--; if (I->get()==0) { material->geometry_owners.erase(I); } } void RasterizerStorageGLES3::update_dirty_materials() { while( _material_dirty_list.first() ) { Material *material = _material_dirty_list.first()->self(); _update_material(material); } } /* MESH API */ RID RasterizerStorageGLES3::mesh_create(){ Mesh * mesh = memnew( Mesh ); return mesh_owner.make_rid(mesh); } void RasterizerStorageGLES3::mesh_add_surface(RID p_mesh,uint32_t p_format,VS::PrimitiveType p_primitive,const PoolVector<uint8_t>& p_array,int p_vertex_count,const PoolVector<uint8_t>& p_index_array,int p_index_count,const Rect3& p_aabb,const Vector<PoolVector<uint8_t> >& p_blend_shapes,const Vector<Rect3>& p_bone_aabbs){ PoolVector<uint8_t> array = p_array; Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND(!mesh); ERR_FAIL_COND(!(p_format&VS::ARRAY_FORMAT_VERTEX)); //must have index and bones, both. { uint32_t bones_weight = VS::ARRAY_FORMAT_BONES|VS::ARRAY_FORMAT_WEIGHTS; ERR_EXPLAIN("Array must have both bones and weights in format or none."); ERR_FAIL_COND( (p_format&bones_weight) && (p_format&bones_weight)!=bones_weight ); } //bool has_morph = p_blend_shapes.size(); Surface::Attrib attribs[VS::ARRAY_MAX]; int stride=0; for(int i=0;i<VS::ARRAY_MAX;i++) { attribs[i].index=i; if (! (p_format&(1<<i) ) ) { attribs[i].enabled=false; attribs[i].integer=false; continue; } attribs[i].enabled=true; attribs[i].offset=stride; attribs[i].integer=false; switch(i) { case VS::ARRAY_VERTEX: { if (p_format&VS::ARRAY_FLAG_USE_2D_VERTICES) { attribs[i].size=2; } else { attribs[i].size=(p_format&VS::ARRAY_COMPRESS_VERTEX)?4:3; } if (p_format&VS::ARRAY_COMPRESS_VERTEX) { attribs[i].type=GL_HALF_FLOAT; stride+=attribs[i].size*2; } else { attribs[i].type=GL_FLOAT; stride+=attribs[i].size*4; } attribs[i].normalized=GL_FALSE; } break; case VS::ARRAY_NORMAL: { attribs[i].size=3; if (p_format&VS::ARRAY_COMPRESS_NORMAL) { attribs[i].type=GL_BYTE; stride+=4; //pad extra byte attribs[i].normalized=GL_TRUE; } else { attribs[i].type=GL_FLOAT; stride+=12; attribs[i].normalized=GL_FALSE; } } break; case VS::ARRAY_TANGENT: { attribs[i].size=4; if (p_format&VS::ARRAY_COMPRESS_TANGENT) { attribs[i].type=GL_BYTE; stride+=4; attribs[i].normalized=GL_TRUE; } else { attribs[i].type=GL_FLOAT; stride+=16; attribs[i].normalized=GL_FALSE; } } break; case VS::ARRAY_COLOR: { attribs[i].size=4; if (p_format&VS::ARRAY_COMPRESS_COLOR) { attribs[i].type=GL_UNSIGNED_BYTE; stride+=4; attribs[i].normalized=GL_TRUE; } else { attribs[i].type=GL_FLOAT; stride+=16; attribs[i].normalized=GL_FALSE; } } break; case VS::ARRAY_TEX_UV: { attribs[i].size=2; if (p_format&VS::ARRAY_COMPRESS_TEX_UV) { attribs[i].type=GL_HALF_FLOAT; stride+=4; } else { attribs[i].type=GL_FLOAT; stride+=8; } attribs[i].normalized=GL_FALSE; } break; case VS::ARRAY_TEX_UV2: { attribs[i].size=2; if (p_format&VS::ARRAY_COMPRESS_TEX_UV2) { attribs[i].type=GL_HALF_FLOAT; stride+=4; } else { attribs[i].type=GL_FLOAT; stride+=8; } attribs[i].normalized=GL_FALSE; } break; case VS::ARRAY_BONES: { attribs[i].size=4; if (p_format&VS::ARRAY_FLAG_USE_16_BIT_BONES) { attribs[i].type=GL_UNSIGNED_SHORT; stride+=8; } else { attribs[i].type=GL_UNSIGNED_BYTE; stride+=4; } attribs[i].normalized=GL_FALSE; attribs[i].integer=true; } break; case VS::ARRAY_WEIGHTS: { attribs[i].size=4; if (p_format&VS::ARRAY_COMPRESS_WEIGHTS) { attribs[i].type=GL_UNSIGNED_SHORT; stride+=8; attribs[i].normalized=GL_TRUE; } else { attribs[i].type=GL_FLOAT; stride+=16; attribs[i].normalized=GL_FALSE; } } break; case VS::ARRAY_INDEX: { attribs[i].size=1; if (p_vertex_count>=(1<<16)) { attribs[i].type=GL_UNSIGNED_INT; attribs[i].stride=4; } else { attribs[i].type=GL_UNSIGNED_SHORT; attribs[i].stride=2; } attribs[i].normalized=GL_FALSE; } break; } } for(int i=0;i<VS::ARRAY_MAX-1;i++) { attribs[i].stride=stride; } //validate sizes int array_size = stride * p_vertex_count; int index_array_size=0; print_line("desired size: "+itos(array_size)+" vcount "+itos(p_vertex_count)+" should be: "+itos(array.size()+p_vertex_count*2)+" but is "+itos(array.size())); if (array.size()!=array_size && array.size()+p_vertex_count*2 == array_size) { //old format, convert array = PoolVector<uint8_t>(); array.resize( p_array.size()+p_vertex_count*2 ); PoolVector<uint8_t>::Write w = array.write(); PoolVector<uint8_t>::Read r = p_array.read(); uint16_t *w16 = (uint16_t*)w.ptr(); const uint16_t *r16 = (uint16_t*)r.ptr(); uint16_t one = Math::make_half_float(1); for(int i=0;i<p_vertex_count;i++) { *w16++ = *r16++; *w16++ = *r16++; *w16++ = *r16++; *w16++ = one; for(int j=0;j<(stride/2)-4;j++) { *w16++ = *r16++; } } } ERR_FAIL_COND(array.size()!=array_size); if (p_format&VS::ARRAY_FORMAT_INDEX) { index_array_size=attribs[VS::ARRAY_INDEX].stride*p_index_count; } ERR_FAIL_COND(p_index_array.size()!=index_array_size); ERR_FAIL_COND(p_blend_shapes.size()!=mesh->blend_shape_count); for(int i=0;i<p_blend_shapes.size();i++) { ERR_FAIL_COND(p_blend_shapes[i].size()!=array_size); } //ok all valid, create stuff Surface * surface = memnew( Surface ); surface->active=true; surface->array_len=p_vertex_count; surface->index_array_len=p_index_count; surface->array_byte_size=array.size(); surface->index_array_byte_size=p_index_array.size(); surface->primitive=p_primitive; surface->mesh=mesh; surface->format=p_format; surface->skeleton_bone_aabb=p_bone_aabbs; surface->skeleton_bone_used.resize(surface->skeleton_bone_aabb.size()); surface->aabb=p_aabb; surface->max_bone=p_bone_aabbs.size(); for(int i=0;i<surface->skeleton_bone_used.size();i++) { if (surface->skeleton_bone_aabb[i].size.x<0 || surface->skeleton_bone_aabb[i].size.y<0 || surface->skeleton_bone_aabb[i].size.z<0) { surface->skeleton_bone_used[i]=false; } else { surface->skeleton_bone_used[i]=true; } } for(int i=0;i<VS::ARRAY_MAX;i++) { surface->attribs[i]=attribs[i]; } { PoolVector<uint8_t>::Read vr = array.read(); glGenBuffers(1,&surface->vertex_id); glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id); glBufferData(GL_ARRAY_BUFFER,array_size,vr.ptr(),GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind if (p_format&VS::ARRAY_FORMAT_INDEX) { PoolVector<uint8_t>::Read ir = p_index_array.read(); glGenBuffers(1,&surface->index_id); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id); glBufferData(GL_ELEMENT_ARRAY_BUFFER,index_array_size,ir.ptr(),GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); //unbind } //generate arrays for faster state switching for(int ai=0;ai<2;ai++) { if (ai==0) { //for normal draw glGenVertexArrays(1,&surface->array_id); glBindVertexArray(surface->array_id); glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id); } else if (ai==1) { //for instancing draw (can be changed and no one cares) glGenVertexArrays(1,&surface->instancing_array_id); glBindVertexArray(surface->instancing_array_id); glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id); } for(int i=0;i<VS::ARRAY_MAX-1;i++) { if (!attribs[i].enabled) continue; if (attribs[i].integer) { glVertexAttribIPointer(attribs[i].index,attribs[i].size,attribs[i].type,attribs[i].stride,((uint8_t*)0)+attribs[i].offset); } else { glVertexAttribPointer(attribs[i].index,attribs[i].size,attribs[i].type,attribs[i].normalized,attribs[i].stride,((uint8_t*)0)+attribs[i].offset); } glEnableVertexAttribArray(attribs[i].index); } if (surface->index_id) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id); } glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); } } { //blend shapes for(int i=0;i<p_blend_shapes.size();i++) { Surface::BlendShape mt; PoolVector<uint8_t>::Read vr = p_blend_shapes[i].read(); glGenBuffers(1,&mt.vertex_id); glBindBuffer(GL_ARRAY_BUFFER,mt.vertex_id); glBufferData(GL_ARRAY_BUFFER,array_size,vr.ptr(),GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind glGenVertexArrays(1,&mt.array_id); glBindVertexArray(mt.array_id); glBindBuffer(GL_ARRAY_BUFFER,mt.vertex_id); for(int j=0;j<VS::ARRAY_MAX-1;j++) { if (!attribs[j].enabled) continue; if (attribs[j].integer) { glVertexAttribIPointer(attribs[j].index,attribs[j].size,attribs[j].type,attribs[j].stride,((uint8_t*)0)+attribs[j].offset); } else { glVertexAttribPointer(attribs[j].index,attribs[j].size,attribs[j].type,attribs[j].normalized,attribs[j].stride,((uint8_t*)0)+attribs[j].offset); } glEnableVertexAttribArray(attribs[j].index); } glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind surface->blend_shapes.push_back(mt); } } mesh->surfaces.push_back(surface); mesh->instance_change_notify(); } void RasterizerStorageGLES3::mesh_set_blend_shape_count(RID p_mesh,int p_amount){ Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND(!mesh); ERR_FAIL_COND(mesh->surfaces.size()!=0); ERR_FAIL_COND(p_amount<0); mesh->blend_shape_count=p_amount; } int RasterizerStorageGLES3::mesh_get_blend_shape_count(RID p_mesh) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,0); return mesh->blend_shape_count; } void RasterizerStorageGLES3::mesh_set_blend_shape_mode(RID p_mesh,VS::BlendShapeMode p_mode){ Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND(!mesh); mesh->blend_shape_mode=p_mode; } VS::BlendShapeMode RasterizerStorageGLES3::mesh_get_blend_shape_mode(RID p_mesh) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,VS::BLEND_SHAPE_MODE_NORMALIZED); return mesh->blend_shape_mode; } void RasterizerStorageGLES3::mesh_surface_set_material(RID p_mesh, int p_surface, RID p_material){ Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND(!mesh); ERR_FAIL_INDEX(p_surface,mesh->surfaces.size()); if (mesh->surfaces[p_surface]->material==p_material) return; if (mesh->surfaces[p_surface]->material.is_valid()) { _material_remove_geometry(mesh->surfaces[p_surface]->material,mesh->surfaces[p_surface]); } mesh->surfaces[p_surface]->material=p_material; if (mesh->surfaces[p_surface]->material.is_valid()) { _material_add_geometry(mesh->surfaces[p_surface]->material,mesh->surfaces[p_surface]); } mesh->instance_material_change_notify(); } RID RasterizerStorageGLES3::mesh_surface_get_material(RID p_mesh, int p_surface) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,RID()); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),RID()); return mesh->surfaces[p_surface]->material; } int RasterizerStorageGLES3::mesh_surface_get_array_len(RID p_mesh, int p_surface) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,0); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),0); return mesh->surfaces[p_surface]->array_len; } int RasterizerStorageGLES3::mesh_surface_get_array_index_len(RID p_mesh, int p_surface) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,0); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),0); return mesh->surfaces[p_surface]->index_array_len; } PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_array(RID p_mesh, int p_surface) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,PoolVector<uint8_t>()); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),PoolVector<uint8_t>()); Surface *surface = mesh->surfaces[p_surface]; glBindBuffer(GL_ARRAY_BUFFER,surface->vertex_id); void * data = glMapBufferRange(GL_ARRAY_BUFFER,0,surface->array_byte_size,GL_MAP_READ_BIT); ERR_FAIL_COND_V(!data,PoolVector<uint8_t>()); PoolVector<uint8_t> ret; ret.resize(surface->array_byte_size); { PoolVector<uint8_t>::Write w = ret.write(); copymem(w.ptr(),data,surface->array_byte_size); } glUnmapBuffer(GL_ARRAY_BUFFER); return ret; } PoolVector<uint8_t> RasterizerStorageGLES3::mesh_surface_get_index_array(RID p_mesh, int p_surface) const { const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,PoolVector<uint8_t>()); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),PoolVector<uint8_t>()); Surface *surface = mesh->surfaces[p_surface]; ERR_FAIL_COND_V(surface->index_array_len==0,PoolVector<uint8_t>()); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,surface->index_id); void * data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER,0,surface->index_array_byte_size,GL_MAP_READ_BIT); ERR_FAIL_COND_V(!data,PoolVector<uint8_t>()); PoolVector<uint8_t> ret; ret.resize(surface->index_array_byte_size); { PoolVector<uint8_t>::Write w = ret.write(); copymem(w.ptr(),data,surface->index_array_byte_size); } glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); return ret; } uint32_t RasterizerStorageGLES3::mesh_surface_get_format(RID p_mesh, int p_surface) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,0); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),0); return mesh->surfaces[p_surface]->format; } VS::PrimitiveType RasterizerStorageGLES3::mesh_surface_get_primitive_type(RID p_mesh, int p_surface) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,VS::PRIMITIVE_MAX); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),VS::PRIMITIVE_MAX); return mesh->surfaces[p_surface]->primitive; } Rect3 RasterizerStorageGLES3::mesh_surface_get_aabb(RID p_mesh, int p_surface) const { const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,Rect3()); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),Rect3()); return mesh->surfaces[p_surface]->aabb; } Vector<PoolVector<uint8_t> > RasterizerStorageGLES3::mesh_surface_get_blend_shapes(RID p_mesh, int p_surface) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,Vector<PoolVector<uint8_t> >()); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),Vector<PoolVector<uint8_t> >()); Vector<PoolVector<uint8_t> > bsarr; for(int i=0;i<mesh->surfaces[p_surface]->blend_shapes.size();i++) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,mesh->surfaces[p_surface]->blend_shapes[i].vertex_id); void * data = glMapBufferRange(GL_ELEMENT_ARRAY_BUFFER,0,mesh->surfaces[p_surface]->array_byte_size,GL_MAP_READ_BIT); ERR_FAIL_COND_V(!data,Vector<PoolVector<uint8_t> >()); PoolVector<uint8_t> ret; ret.resize(mesh->surfaces[p_surface]->array_byte_size); { PoolVector<uint8_t>::Write w = ret.write(); copymem(w.ptr(),data,mesh->surfaces[p_surface]->array_byte_size); } bsarr.push_back(ret); glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); } return bsarr; } Vector<Rect3> RasterizerStorageGLES3::mesh_surface_get_skeleton_aabb(RID p_mesh, int p_surface) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,Vector<Rect3 >()); ERR_FAIL_INDEX_V(p_surface,mesh->surfaces.size(),Vector<Rect3 >()); return mesh->surfaces[p_surface]->skeleton_bone_aabb; } void RasterizerStorageGLES3::mesh_remove_surface(RID p_mesh, int p_surface){ Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND(!mesh); ERR_FAIL_INDEX(p_surface,mesh->surfaces.size()); Surface *surface = mesh->surfaces[p_surface]; if (surface->material.is_valid()) { _material_remove_geometry(surface->material,mesh->surfaces[p_surface]); } glDeleteBuffers(1,&surface->vertex_id); if (surface->index_id) { glDeleteBuffers(1,&surface->index_id); } glDeleteVertexArrays(1,&surface->array_id); for(int i=0;i<surface->blend_shapes.size();i++) { glDeleteBuffers(1,&surface->blend_shapes[i].vertex_id); glDeleteVertexArrays(1,&surface->blend_shapes[i].array_id); } mesh->instance_material_change_notify(); memdelete(surface); mesh->surfaces.remove(p_surface); mesh->instance_change_notify(); } int RasterizerStorageGLES3::mesh_get_surface_count(RID p_mesh) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,0); return mesh->surfaces.size(); } void RasterizerStorageGLES3::mesh_set_custom_aabb(RID p_mesh,const Rect3& p_aabb){ Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND(!mesh); mesh->custom_aabb=p_aabb; } Rect3 RasterizerStorageGLES3::mesh_get_custom_aabb(RID p_mesh) const{ const Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND_V(!mesh,Rect3()); return mesh->custom_aabb; } Rect3 RasterizerStorageGLES3::mesh_get_aabb(RID p_mesh,RID p_skeleton) const{ Mesh *mesh = mesh_owner.get( p_mesh ); ERR_FAIL_COND_V(!mesh,Rect3()); if (mesh->custom_aabb!=Rect3()) return mesh->custom_aabb; Skeleton *sk=NULL; if (p_skeleton.is_valid()) sk=skeleton_owner.get(p_skeleton); Rect3 aabb; if (sk && sk->size!=0) { for (int i=0;i<mesh->surfaces.size();i++) { Rect3 laabb; if (mesh->surfaces[i]->format&VS::ARRAY_FORMAT_BONES && mesh->surfaces[i]->skeleton_bone_aabb.size()) { int bs = mesh->surfaces[i]->skeleton_bone_aabb.size(); const Rect3 *skbones = mesh->surfaces[i]->skeleton_bone_aabb.ptr(); const bool *skused = mesh->surfaces[i]->skeleton_bone_used.ptr(); int sbs = sk->size; ERR_CONTINUE(bs>sbs); float *skb = sk->bones.ptr(); bool first=true; if (sk->use_2d) { for(int j=0;j<bs;j++) { if (!skused[j]) continue; float *dataptr = &skb[8*j]; Transform mtx; mtx.basis.elements[0][0]=dataptr[ 0]; mtx.basis.elements[0][1]=dataptr[ 1]; mtx.origin[0]=dataptr[ 3]; mtx.basis.elements[1][0]=dataptr[ 4]; mtx.basis.elements[1][1]=dataptr[ 5]; mtx.origin[1]=dataptr[ 7]; Rect3 baabb = mtx.xform( skbones[j] ); if (first) { laabb=baabb; first=false; } else { laabb.merge_with(baabb); } } } else { for(int j=0;j<bs;j++) { if (!skused[j]) continue; float *dataptr = &skb[12*j]; Transform mtx; mtx.basis.elements[0][0]=dataptr[ 0]; mtx.basis.elements[0][1]=dataptr[ 1]; mtx.basis.elements[0][2]=dataptr[ 2]; mtx.origin.x=dataptr[ 3]; mtx.basis.elements[1][0]=dataptr[ 4]; mtx.basis.elements[1][1]=dataptr[ 5]; mtx.basis.elements[1][2]=dataptr[ 6]; mtx.origin.y=dataptr[ 7]; mtx.basis.elements[2][0]=dataptr[ 8]; mtx.basis.elements[2][1]=dataptr[ 9]; mtx.basis.elements[2][2]=dataptr[10]; mtx.origin.z=dataptr[11]; Rect3 baabb = mtx.xform ( skbones[j] ); if (first) { laabb=baabb; first=false; } else { laabb.merge_with(baabb); } } } } else { laabb=mesh->surfaces[i]->aabb; } if (i==0) aabb=laabb; else aabb.merge_with(laabb); } } else { for (int i=0;i<mesh->surfaces.size();i++) { if (i==0) aabb=mesh->surfaces[i]->aabb; else aabb.merge_with(mesh->surfaces[i]->aabb); } } return aabb; } void RasterizerStorageGLES3::mesh_clear(RID p_mesh){ Mesh *mesh = mesh_owner.getornull(p_mesh); ERR_FAIL_COND(!mesh); while(mesh->surfaces.size()) { mesh_remove_surface(p_mesh,0); } } void RasterizerStorageGLES3::mesh_render_blend_shapes(Surface *s, float *p_weights) { glBindVertexArray(s->array_id); BlendShapeShaderGLES3::Conditionals cond[VS::ARRAY_MAX-1]={ BlendShapeShaderGLES3::ENABLE_NORMAL, //will be ignored BlendShapeShaderGLES3::ENABLE_NORMAL, BlendShapeShaderGLES3::ENABLE_TANGENT, BlendShapeShaderGLES3::ENABLE_COLOR, BlendShapeShaderGLES3::ENABLE_UV, BlendShapeShaderGLES3::ENABLE_UV2, BlendShapeShaderGLES3::ENABLE_SKELETON, BlendShapeShaderGLES3::ENABLE_SKELETON, }; int stride=0; if (s->format&VS::ARRAY_FLAG_USE_2D_VERTICES) { stride=2*4; } else { stride=3*4; } static const int sizes[VS::ARRAY_MAX-1]={ 3*4, 3*4, 4*4, 4*4, 2*4, 2*4, 4*4, 4*4 }; for(int i=1;i<VS::ARRAY_MAX-1;i++) { shaders.blend_shapes.set_conditional(cond[i],s->format&(1<<i)); //enable conditional for format if (s->format&(1<<i)) { stride+=sizes[i]; } } //copy all first float base_weight=1.0; int mtc = s->blend_shapes.size(); if (s->mesh->blend_shape_mode==VS::BLEND_SHAPE_MODE_NORMALIZED) { for(int i=0;i<mtc;i++) { base_weight-=p_weights[i]; } } shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::ENABLE_BLEND,false); //first pass does not blend shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::USE_2D_VERTEX,s->format&VS::ARRAY_FLAG_USE_2D_VERTICES); //use 2D vertices if needed shaders.blend_shapes.bind(); shaders.blend_shapes.set_uniform(BlendShapeShaderGLES3::BLEND_AMOUNT,base_weight); glEnable(GL_RASTERIZER_DISCARD); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, resources.transform_feedback_buffers[0]); glBeginTransformFeedback(GL_POINTS); glDrawArrays(GL_POINTS,0,s->array_len); glEndTransformFeedback(); shaders.blend_shapes.set_conditional(BlendShapeShaderGLES3::ENABLE_BLEND,true); //first pass does not blend shaders.blend_shapes.bind(); for(int ti=0;ti<mtc;ti++) { float weight = p_weights[ti]; if (weight<0.001) //not bother with this one continue; glBindVertexArray(s->blend_shapes[ti].array_id); glBindBuffer(GL_ARRAY_BUFFER, resources.transform_feedback_buffers[0]); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, resources.transform_feedback_buffers[1]); shaders.blend_shapes.set_uniform(BlendShapeShaderGLES3::BLEND_AMOUNT,weight); int ofs=0; for(int i=0;i<VS::ARRAY_MAX-1;i++) { if (s->format&(1<<i)) { glEnableVertexAttribArray(i+8); switch(i) { case VS::ARRAY_VERTEX: { if (s->format&VS::ARRAY_FLAG_USE_2D_VERTICES) { glVertexAttribPointer(i+8,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=2*4; } else { glVertexAttribPointer(i+8,3,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=3*4; } } break; case VS::ARRAY_NORMAL: { glVertexAttribPointer(i+8,3,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=3*4; } break; case VS::ARRAY_TANGENT: { glVertexAttribPointer(i+8,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=4*4; } break; case VS::ARRAY_COLOR: { glVertexAttribPointer(i+8,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=4*4; } break; case VS::ARRAY_TEX_UV: { glVertexAttribPointer(i+8,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=2*4; } break; case VS::ARRAY_TEX_UV2: { glVertexAttribPointer(i+8,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=2*4; } break; case VS::ARRAY_BONES: { glVertexAttribIPointer(i+8,4,GL_UNSIGNED_INT,stride,((uint8_t*)0)+ofs); ofs+=4*4; } break; case VS::ARRAY_WEIGHTS: { glVertexAttribPointer(i+8,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=4*4; } break; } } else { glDisableVertexAttribArray(i+8); } } glBeginTransformFeedback(GL_POINTS); glDrawArrays(GL_POINTS,0,s->array_len); glEndTransformFeedback(); SWAP(resources.transform_feedback_buffers[0],resources.transform_feedback_buffers[1]); } glDisable(GL_RASTERIZER_DISCARD); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, 0); glBindVertexArray(resources.transform_feedback_array); glBindBuffer(GL_ARRAY_BUFFER, resources.transform_feedback_buffers[0]); int ofs=0; for(int i=0;i<VS::ARRAY_MAX-1;i++) { if (s->format&(1<<i)) { glEnableVertexAttribArray(i); switch(i) { case VS::ARRAY_VERTEX: { if (s->format&VS::ARRAY_FLAG_USE_2D_VERTICES) { glVertexAttribPointer(i,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=2*4; } else { glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=3*4; } } break; case VS::ARRAY_NORMAL: { glVertexAttribPointer(i,3,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=3*4; } break; case VS::ARRAY_TANGENT: { glVertexAttribPointer(i,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=4*4; } break; case VS::ARRAY_COLOR: { glVertexAttribPointer(i,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=4*4; } break; case VS::ARRAY_TEX_UV: { glVertexAttribPointer(i,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=2*4; } break; case VS::ARRAY_TEX_UV2: { glVertexAttribPointer(i,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=2*4; } break; case VS::ARRAY_BONES: { glVertexAttribIPointer(i,4,GL_UNSIGNED_INT,stride,((uint8_t*)0)+ofs); ofs+=4*4; } break; case VS::ARRAY_WEIGHTS: { glVertexAttribPointer(i,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)0)+ofs); ofs+=4*4; } break; } } else { glDisableVertexAttribArray(i); } } if (s->index_array_len) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,s->index_id); } } /* MULTIMESH API */ RID RasterizerStorageGLES3::multimesh_create(){ MultiMesh *multimesh = memnew( MultiMesh ); return multimesh_owner.make_rid(multimesh); } void RasterizerStorageGLES3::multimesh_allocate(RID p_multimesh, int p_instances, VS::MultimeshTransformFormat p_transform_format, VS::MultimeshColorFormat p_color_format){ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND(!multimesh); if (multimesh->size==p_instances && multimesh->transform_format==p_transform_format && multimesh->color_format==p_color_format) return; if (multimesh->buffer) { glDeleteBuffers(1,&multimesh->buffer); multimesh->data.resize(0); } multimesh->size=p_instances; multimesh->transform_format=p_transform_format; multimesh->color_format=p_color_format; if (multimesh->size) { if (multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D) { multimesh->xform_floats=8; } else { multimesh->xform_floats=12; } if (multimesh->color_format==VS::MULTIMESH_COLOR_NONE) { multimesh->color_floats=0; } else if (multimesh->color_format==VS::MULTIMESH_COLOR_8BIT) { multimesh->color_floats=1; } else if (multimesh->color_format==VS::MULTIMESH_COLOR_FLOAT) { multimesh->color_floats=4; } int format_floats = multimesh->color_floats+multimesh->xform_floats; multimesh->data.resize(format_floats*p_instances); for(int i=0;i<p_instances;i+=format_floats) { int color_from=0; if (multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D) { multimesh->data[i+0]=1.0; multimesh->data[i+1]=0.0; multimesh->data[i+2]=0.0; multimesh->data[i+3]=0.0; multimesh->data[i+4]=0.0; multimesh->data[i+5]=1.0; multimesh->data[i+6]=0.0; multimesh->data[i+7]=0.0; color_from=8; } else { multimesh->data[i+0]=1.0; multimesh->data[i+1]=0.0; multimesh->data[i+2]=0.0; multimesh->data[i+3]=0.0; multimesh->data[i+4]=0.0; multimesh->data[i+5]=1.0; multimesh->data[i+6]=0.0; multimesh->data[i+7]=0.0; multimesh->data[i+8]=0.0; multimesh->data[i+9]=0.0; multimesh->data[i+10]=1.0; multimesh->data[i+11]=0.0; color_from=12; } if (multimesh->color_format==VS::MULTIMESH_COLOR_NONE) { //none } else if (multimesh->color_format==VS::MULTIMESH_COLOR_8BIT) { union { uint32_t colu; float colf; } cu; cu.colu=0xFFFFFFFF; multimesh->data[i+color_from+0]=cu.colf; } else if (multimesh->color_format==VS::MULTIMESH_COLOR_FLOAT) { multimesh->data[i+color_from+0]=1.0; multimesh->data[i+color_from+1]=1.0; multimesh->data[i+color_from+2]=1.0; multimesh->data[i+color_from+3]=1.0; } } glGenBuffers(1,&multimesh->buffer); glBindBuffer(GL_ARRAY_BUFFER,multimesh->buffer); glBufferData(GL_ARRAY_BUFFER,multimesh->data.size()*sizeof(float),NULL,GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,0); } multimesh->dirty_data=true; multimesh->dirty_aabb=true; if (!multimesh->update_list.in_list()) { multimesh_update_list.add(&multimesh->update_list); } } int RasterizerStorageGLES3::multimesh_get_instance_count(RID p_multimesh) const{ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND_V(!multimesh,0); return multimesh->size; } void RasterizerStorageGLES3::multimesh_set_mesh(RID p_multimesh,RID p_mesh){ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND(!multimesh); multimesh->mesh=p_mesh; multimesh->dirty_aabb=true; if (!multimesh->update_list.in_list()) { multimesh_update_list.add(&multimesh->update_list); } } void RasterizerStorageGLES3::multimesh_instance_set_transform(RID p_multimesh,int p_index,const Transform& p_transform){ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND(!multimesh); ERR_FAIL_INDEX(p_index,multimesh->size); ERR_FAIL_COND(multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D); int stride = multimesh->color_floats+multimesh->xform_floats; float *dataptr=&multimesh->data[stride*p_index]; dataptr[ 0]=p_transform.basis.elements[0][0]; dataptr[ 1]=p_transform.basis.elements[0][1]; dataptr[ 2]=p_transform.basis.elements[0][2]; dataptr[ 3]=p_transform.origin.x; dataptr[ 4]=p_transform.basis.elements[1][0]; dataptr[ 5]=p_transform.basis.elements[1][1]; dataptr[ 6]=p_transform.basis.elements[1][2]; dataptr[ 7]=p_transform.origin.y; dataptr[ 8]=p_transform.basis.elements[2][0]; dataptr[ 9]=p_transform.basis.elements[2][1]; dataptr[10]=p_transform.basis.elements[2][2]; dataptr[11]=p_transform.origin.z; multimesh->dirty_data=true; multimesh->dirty_aabb=true; if (!multimesh->update_list.in_list()) { multimesh_update_list.add(&multimesh->update_list); } } void RasterizerStorageGLES3::multimesh_instance_set_transform_2d(RID p_multimesh,int p_index,const Transform2D& p_transform){ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND(!multimesh); ERR_FAIL_INDEX(p_index,multimesh->size); ERR_FAIL_COND(multimesh->transform_format==VS::MULTIMESH_TRANSFORM_3D); int stride = multimesh->color_floats+multimesh->xform_floats; float *dataptr=&multimesh->data[stride*p_index]; dataptr[ 0]=p_transform.elements[0][0]; dataptr[ 1]=p_transform.elements[1][0]; dataptr[ 2]=0; dataptr[ 3]=p_transform.elements[2][0]; dataptr[ 4]=p_transform.elements[0][1]; dataptr[ 5]=p_transform.elements[1][1]; dataptr[ 6]=0; dataptr[ 7]=p_transform.elements[2][1]; multimesh->dirty_data=true; multimesh->dirty_aabb=true; if (!multimesh->update_list.in_list()) { multimesh_update_list.add(&multimesh->update_list); } } void RasterizerStorageGLES3::multimesh_instance_set_color(RID p_multimesh,int p_index,const Color& p_color){ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND(!multimesh); ERR_FAIL_INDEX(p_index,multimesh->size); ERR_FAIL_COND(multimesh->color_format==VS::MULTIMESH_COLOR_NONE); int stride = multimesh->color_floats+multimesh->xform_floats; float *dataptr=&multimesh->data[stride*p_index+multimesh->xform_floats]; if (multimesh->color_format==VS::MULTIMESH_COLOR_8BIT) { uint8_t *data8=(uint8_t*)dataptr; data8[0]=CLAMP(p_color.r*255.0,0,255); data8[1]=CLAMP(p_color.g*255.0,0,255); data8[2]=CLAMP(p_color.b*255.0,0,255); data8[3]=CLAMP(p_color.a*255.0,0,255); } else if (multimesh->color_format==VS::MULTIMESH_COLOR_FLOAT) { dataptr[ 0]=p_color.r; dataptr[ 1]=p_color.g; dataptr[ 2]=p_color.b; dataptr[ 3]=p_color.a; } multimesh->dirty_data=true; multimesh->dirty_aabb=true; if (!multimesh->update_list.in_list()) { multimesh_update_list.add(&multimesh->update_list); } } RID RasterizerStorageGLES3::multimesh_get_mesh(RID p_multimesh) const{ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND_V(!multimesh,RID()); return multimesh->mesh; } Transform RasterizerStorageGLES3::multimesh_instance_get_transform(RID p_multimesh,int p_index) const{ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND_V(!multimesh,Transform()); ERR_FAIL_INDEX_V(p_index,multimesh->size,Transform()); ERR_FAIL_COND_V(multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D,Transform()); int stride = multimesh->color_floats+multimesh->xform_floats; float *dataptr=&multimesh->data[stride*p_index]; Transform xform; xform.basis.elements[0][0]=dataptr[ 0]; xform.basis.elements[0][1]=dataptr[ 1]; xform.basis.elements[0][2]=dataptr[ 2]; xform.origin.x=dataptr[ 3]; xform.basis.elements[1][0]=dataptr[ 4]; xform.basis.elements[1][1]=dataptr[ 5]; xform.basis.elements[1][2]=dataptr[ 6]; xform.origin.y=dataptr[ 7]; xform.basis.elements[2][0]=dataptr[ 8]; xform.basis.elements[2][1]=dataptr[ 9]; xform.basis.elements[2][2]=dataptr[10]; xform.origin.z=dataptr[11]; return xform; } Transform2D RasterizerStorageGLES3::multimesh_instance_get_transform_2d(RID p_multimesh,int p_index) const{ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND_V(!multimesh,Transform2D()); ERR_FAIL_INDEX_V(p_index,multimesh->size,Transform2D()); ERR_FAIL_COND_V(multimesh->transform_format==VS::MULTIMESH_TRANSFORM_3D,Transform2D()); int stride = multimesh->color_floats+multimesh->xform_floats; float *dataptr=&multimesh->data[stride*p_index]; Transform2D xform; xform.elements[0][0]=dataptr[ 0]; xform.elements[1][0]=dataptr[ 1]; xform.elements[2][0]=dataptr[ 3]; xform.elements[0][1]=dataptr[ 4]; xform.elements[1][1]=dataptr[ 5]; xform.elements[2][1]=dataptr[ 7]; return xform; } Color RasterizerStorageGLES3::multimesh_instance_get_color(RID p_multimesh,int p_index) const{ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND_V(!multimesh,Color()); ERR_FAIL_INDEX_V(p_index,multimesh->size,Color()); ERR_FAIL_COND_V(multimesh->color_format==VS::MULTIMESH_COLOR_NONE,Color()); int stride = multimesh->color_floats+multimesh->xform_floats; float *dataptr=&multimesh->data[stride*p_index+multimesh->color_floats]; if (multimesh->color_format==VS::MULTIMESH_COLOR_8BIT) { union { uint32_t colu; float colf; } cu; return Color::hex(BSWAP32(cu.colu)); } else if (multimesh->color_format==VS::MULTIMESH_COLOR_FLOAT) { Color c; c.r=dataptr[ 0]; c.g=dataptr[ 1]; c.b=dataptr[ 2]; c.a=dataptr[ 3]; return c; } return Color(); } void RasterizerStorageGLES3::multimesh_set_visible_instances(RID p_multimesh,int p_visible){ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND(!multimesh); multimesh->visible_instances=p_visible; } int RasterizerStorageGLES3::multimesh_get_visible_instances(RID p_multimesh) const{ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND_V(!multimesh,-1); return multimesh->visible_instances; } Rect3 RasterizerStorageGLES3::multimesh_get_aabb(RID p_multimesh) const{ MultiMesh *multimesh = multimesh_owner.getornull(p_multimesh); ERR_FAIL_COND_V(!multimesh,Rect3()); const_cast<RasterizerStorageGLES3*>(this)->update_dirty_multimeshes(); //update pending AABBs return multimesh->aabb; } void RasterizerStorageGLES3::update_dirty_multimeshes() { while(multimesh_update_list.first()) { MultiMesh *multimesh = multimesh_update_list.first()->self(); if (multimesh->size && multimesh->dirty_data) { glBindBuffer(GL_ARRAY_BUFFER,multimesh->buffer); glBufferSubData(GL_ARRAY_BUFFER,0,multimesh->data.size()*sizeof(float),multimesh->data.ptr()); glBindBuffer(GL_ARRAY_BUFFER,0); } if (multimesh->size && multimesh->dirty_aabb) { Rect3 mesh_aabb; if (multimesh->mesh.is_valid()) { mesh_aabb=mesh_get_aabb(multimesh->mesh,RID()); } else { mesh_aabb.size+=Vector3(0.001,0.001,0.001); } int stride=multimesh->color_floats+multimesh->xform_floats; int count = multimesh->data.size(); float *data=multimesh->data.ptr(); Rect3 aabb; if (multimesh->transform_format==VS::MULTIMESH_TRANSFORM_2D) { for(int i=0;i<count;i+=stride) { float *dataptr=&data[i]; Transform xform; xform.basis[0][0]=dataptr[ 0]; xform.basis[0][1]=dataptr[ 1]; xform.origin[0]=dataptr[ 3]; xform.basis[1][0]=dataptr[ 4]; xform.basis[1][1]=dataptr[ 5]; xform.origin[1]=dataptr[ 7]; Rect3 laabb = xform.xform(mesh_aabb); if (i==0) aabb=laabb; else aabb.merge_with(laabb); } } else { for(int i=0;i<count;i+=stride) { float *dataptr=&data[i]; Transform xform; xform.basis.elements[0][0]=dataptr[ 0]; xform.basis.elements[0][1]=dataptr[ 1]; xform.basis.elements[0][2]=dataptr[ 2]; xform.origin.x=dataptr[ 3]; xform.basis.elements[1][0]=dataptr[ 4]; xform.basis.elements[1][1]=dataptr[ 5]; xform.basis.elements[1][2]=dataptr[ 6]; xform.origin.y=dataptr[ 7]; xform.basis.elements[2][0]=dataptr[ 8]; xform.basis.elements[2][1]=dataptr[ 9]; xform.basis.elements[2][2]=dataptr[10]; xform.origin.z=dataptr[11]; Rect3 laabb = xform.xform(mesh_aabb); if (i==0) aabb=laabb; else aabb.merge_with(laabb); } } multimesh->aabb=aabb; } multimesh->dirty_aabb=false; multimesh->dirty_data=false; multimesh->instance_change_notify(); multimesh_update_list.remove(multimesh_update_list.first()); } } /* IMMEDIATE API */ RID RasterizerStorageGLES3::immediate_create() { Immediate *im = memnew( Immediate ); return immediate_owner.make_rid(im); } void RasterizerStorageGLES3::immediate_begin(RID p_immediate, VS::PrimitiveType p_rimitive, RID p_texture){ Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(im->building); Immediate::Chunk ic; ic.texture=p_texture; ic.primitive=p_rimitive; im->chunks.push_back(ic); im->mask=0; im->building=true; } void RasterizerStorageGLES3::immediate_vertex(RID p_immediate,const Vector3& p_vertex){ Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(!im->building); Immediate::Chunk *c = &im->chunks.back()->get(); if (c->vertices.empty() && im->chunks.size()==1) { im->aabb.pos=p_vertex; im->aabb.size=Vector3(); } else { im->aabb.expand_to(p_vertex); } if (im->mask&VS::ARRAY_FORMAT_NORMAL) c->normals.push_back(chunk_normal); if (im->mask&VS::ARRAY_FORMAT_TANGENT) c->tangents.push_back(chunk_tangent); if (im->mask&VS::ARRAY_FORMAT_COLOR) c->colors.push_back(chunk_color); if (im->mask&VS::ARRAY_FORMAT_TEX_UV) c->uvs.push_back(chunk_uv); if (im->mask&VS::ARRAY_FORMAT_TEX_UV2) c->uvs2.push_back(chunk_uv2); im->mask|=VS::ARRAY_FORMAT_VERTEX; c->vertices.push_back(p_vertex); } void RasterizerStorageGLES3::immediate_normal(RID p_immediate,const Vector3& p_normal){ Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(!im->building); im->mask|=VS::ARRAY_FORMAT_NORMAL; chunk_normal=p_normal; } void RasterizerStorageGLES3::immediate_tangent(RID p_immediate,const Plane& p_tangent){ Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(!im->building); im->mask|=VS::ARRAY_FORMAT_TANGENT; chunk_tangent=p_tangent; } void RasterizerStorageGLES3::immediate_color(RID p_immediate,const Color& p_color){ Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(!im->building); im->mask|=VS::ARRAY_FORMAT_COLOR; chunk_color=p_color; } void RasterizerStorageGLES3::immediate_uv(RID p_immediate,const Vector2& tex_uv){ Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(!im->building); im->mask|=VS::ARRAY_FORMAT_TEX_UV; chunk_uv=tex_uv; } void RasterizerStorageGLES3::immediate_uv2(RID p_immediate,const Vector2& tex_uv){ Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(!im->building); im->mask|=VS::ARRAY_FORMAT_TEX_UV2; chunk_uv2=tex_uv; } void RasterizerStorageGLES3::immediate_end(RID p_immediate){ Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(!im->building); im->building=false; im->instance_change_notify(); } void RasterizerStorageGLES3::immediate_clear(RID p_immediate) { Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); ERR_FAIL_COND(im->building); im->chunks.clear(); im->instance_change_notify(); } Rect3 RasterizerStorageGLES3::immediate_get_aabb(RID p_immediate) const { Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND_V(!im,Rect3()); return im->aabb; } void RasterizerStorageGLES3::immediate_set_material(RID p_immediate,RID p_material) { Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND(!im); im->material=p_material; im->instance_material_change_notify(); } RID RasterizerStorageGLES3::immediate_get_material(RID p_immediate) const { const Immediate *im = immediate_owner.get(p_immediate); ERR_FAIL_COND_V(!im,RID()); return im->material; } /* SKELETON API */ RID RasterizerStorageGLES3::skeleton_create(){ Skeleton *skeleton = memnew( Skeleton ); return skeleton_owner.make_rid(skeleton); } void RasterizerStorageGLES3::skeleton_allocate(RID p_skeleton,int p_bones,bool p_2d_skeleton){ Skeleton *skeleton = skeleton_owner.getornull(p_skeleton); ERR_FAIL_COND(!skeleton); ERR_FAIL_COND(p_bones<0); if (skeleton->size==p_bones && skeleton->use_2d==p_2d_skeleton) return; if (skeleton->ubo) { glDeleteBuffers(1,&skeleton->ubo); skeleton->ubo=0; } skeleton->size=p_bones; if (p_2d_skeleton) { skeleton->bones.resize(p_bones*8); for(int i=0;i<skeleton->bones.size();i+=8) { skeleton->bones[i+0]=1; skeleton->bones[i+1]=0; skeleton->bones[i+2]=0; skeleton->bones[i+3]=0; skeleton->bones[i+4]=0; skeleton->bones[i+5]=1; skeleton->bones[i+6]=0; skeleton->bones[i+7]=0; } } else { skeleton->bones.resize(p_bones*12); for(int i=0;i<skeleton->bones.size();i+=12) { skeleton->bones[i+0]=1; skeleton->bones[i+1]=0; skeleton->bones[i+2]=0; skeleton->bones[i+3]=0; skeleton->bones[i+4]=0; skeleton->bones[i+5]=1; skeleton->bones[i+6]=0; skeleton->bones[i+7]=0; skeleton->bones[i+8]=0; skeleton->bones[i+9]=0; skeleton->bones[i+10]=1; skeleton->bones[i+11]=0; } } if (p_bones) { glGenBuffers(1, &skeleton->ubo); glBindBuffer(GL_UNIFORM_BUFFER, skeleton->ubo); glBufferData(GL_UNIFORM_BUFFER, skeleton->bones.size()*sizeof(float), NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); } if (!skeleton->update_list.in_list()) { skeleton_update_list.add(&skeleton->update_list); } } int RasterizerStorageGLES3::skeleton_get_bone_count(RID p_skeleton) const{ Skeleton *skeleton = skeleton_owner.getornull(p_skeleton); ERR_FAIL_COND_V(!skeleton,0); return skeleton->size; } void RasterizerStorageGLES3::skeleton_bone_set_transform(RID p_skeleton,int p_bone, const Transform& p_transform){ Skeleton *skeleton = skeleton_owner.getornull(p_skeleton); ERR_FAIL_COND(!skeleton); ERR_FAIL_INDEX(p_bone,skeleton->size); ERR_FAIL_COND(skeleton->use_2d); float * bones = skeleton->bones.ptr(); bones[p_bone*12+ 0]=p_transform.basis.elements[0][0]; bones[p_bone*12+ 1]=p_transform.basis.elements[0][1]; bones[p_bone*12+ 2]=p_transform.basis.elements[0][2]; bones[p_bone*12+ 3]=p_transform.origin.x; bones[p_bone*12+ 4]=p_transform.basis.elements[1][0]; bones[p_bone*12+ 5]=p_transform.basis.elements[1][1]; bones[p_bone*12+ 6]=p_transform.basis.elements[1][2]; bones[p_bone*12+ 7]=p_transform.origin.y; bones[p_bone*12+ 8]=p_transform.basis.elements[2][0]; bones[p_bone*12+ 9]=p_transform.basis.elements[2][1]; bones[p_bone*12+10]=p_transform.basis.elements[2][2]; bones[p_bone*12+11]=p_transform.origin.z; if (!skeleton->update_list.in_list()) { skeleton_update_list.add(&skeleton->update_list); } } Transform RasterizerStorageGLES3::skeleton_bone_get_transform(RID p_skeleton,int p_bone) const{ Skeleton *skeleton = skeleton_owner.getornull(p_skeleton); ERR_FAIL_COND_V(!skeleton,Transform()); ERR_FAIL_INDEX_V(p_bone,skeleton->size,Transform()); ERR_FAIL_COND_V(skeleton->use_2d,Transform()); float * bones = skeleton->bones.ptr(); Transform mtx; mtx.basis.elements[0][0]=bones[p_bone*12+ 0]; mtx.basis.elements[0][1]=bones[p_bone*12+ 1]; mtx.basis.elements[0][2]=bones[p_bone*12+ 2]; mtx.origin.x=bones[p_bone*12+ 3]; mtx.basis.elements[1][0]=bones[p_bone*12+ 4]; mtx.basis.elements[1][1]=bones[p_bone*12+ 5]; mtx.basis.elements[1][2]=bones[p_bone*12+ 6]; mtx.origin.y=bones[p_bone*12+ 7]; mtx.basis.elements[2][0]=bones[p_bone*12+ 8]; mtx.basis.elements[2][1]=bones[p_bone*12+ 9]; mtx.basis.elements[2][2]=bones[p_bone*12+10]; mtx.origin.z=bones[p_bone*12+11]; return mtx; } void RasterizerStorageGLES3::skeleton_bone_set_transform_2d(RID p_skeleton,int p_bone, const Transform2D& p_transform){ Skeleton *skeleton = skeleton_owner.getornull(p_skeleton); ERR_FAIL_COND(!skeleton); ERR_FAIL_INDEX(p_bone,skeleton->size); ERR_FAIL_COND(!skeleton->use_2d); float * bones = skeleton->bones.ptr(); bones[p_bone*12+ 0]=p_transform.elements[0][0]; bones[p_bone*12+ 1]=p_transform.elements[1][0]; bones[p_bone*12+ 2]=0; bones[p_bone*12+ 3]=p_transform.elements[2][0]; bones[p_bone*12+ 4]=p_transform.elements[0][1]; bones[p_bone*12+ 5]=p_transform.elements[1][1]; bones[p_bone*12+ 6]=0; bones[p_bone*12+ 7]=p_transform.elements[2][1]; if (!skeleton->update_list.in_list()) { skeleton_update_list.add(&skeleton->update_list); } } Transform2D RasterizerStorageGLES3::skeleton_bone_get_transform_2d(RID p_skeleton,int p_bone) const{ Skeleton *skeleton = skeleton_owner.getornull(p_skeleton); ERR_FAIL_COND_V(!skeleton,Transform2D()); ERR_FAIL_INDEX_V(p_bone,skeleton->size,Transform2D()); ERR_FAIL_COND_V(!skeleton->use_2d,Transform2D()); Transform2D mtx; float * bones = skeleton->bones.ptr(); mtx.elements[0][0]=bones[p_bone*12+ 0]; mtx.elements[1][0]=bones[p_bone*12+ 1]; mtx.elements[2][0]=bones[p_bone*12+ 3]; mtx.elements[0][1]=bones[p_bone*12+ 4]; mtx.elements[1][1]=bones[p_bone*12+ 5]; mtx.elements[2][1]=bones[p_bone*12+ 7]; return mtx; } void RasterizerStorageGLES3::update_dirty_skeletons() { while(skeleton_update_list.first()) { Skeleton *skeleton = skeleton_update_list.first()->self(); if (skeleton->size) { glBindBuffer(GL_UNIFORM_BUFFER, skeleton->ubo); glBufferSubData(GL_UNIFORM_BUFFER,0,skeleton->bones.size()*sizeof(float),skeleton->bones.ptr()); glBindBuffer(GL_UNIFORM_BUFFER, 0); } for (Set<RasterizerScene::InstanceBase*>::Element *E=skeleton->instances.front();E;E=E->next()) { E->get()->base_changed(); } skeleton_update_list.remove(skeleton_update_list.first()); } } /* Light API */ RID RasterizerStorageGLES3::light_create(VS::LightType p_type){ Light *light = memnew( Light ); light->type=p_type; light->param[VS::LIGHT_PARAM_ENERGY]=1.0; light->param[VS::LIGHT_PARAM_SPECULAR]=0.5; light->param[VS::LIGHT_PARAM_RANGE]=1.0; light->param[VS::LIGHT_PARAM_SPOT_ANGLE]=45; light->param[VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE]=0; light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET]=0.1; light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_2_OFFSET]=0.3; light->param[VS::LIGHT_PARAM_SHADOW_SPLIT_3_OFFSET]=0.6; light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS]=0.1; light->param[VS::LIGHT_PARAM_SHADOW_BIAS_SPLIT_SCALE]=0.1; light->color=Color(1,1,1,1); light->shadow=false; light->negative=false; light->cull_mask=0xFFFFFFFF; light->directional_shadow_mode=VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL; light->omni_shadow_mode=VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID; light->omni_shadow_detail=VS::LIGHT_OMNI_SHADOW_DETAIL_VERTICAL; light->directional_blend_splits=false; light->version=0; return light_owner.make_rid(light); } void RasterizerStorageGLES3::light_set_color(RID p_light,const Color& p_color){ Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->color=p_color; } void RasterizerStorageGLES3::light_set_param(RID p_light,VS::LightParam p_param,float p_value){ Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); ERR_FAIL_INDEX(p_param,VS::LIGHT_PARAM_MAX); switch(p_param) { case VS::LIGHT_PARAM_RANGE: case VS::LIGHT_PARAM_SPOT_ANGLE: case VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE: case VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET: case VS::LIGHT_PARAM_SHADOW_SPLIT_2_OFFSET: case VS::LIGHT_PARAM_SHADOW_SPLIT_3_OFFSET: case VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS: case VS::LIGHT_PARAM_SHADOW_BIAS: case VS::LIGHT_PARAM_SHADOW_BIAS_SPLIT_SCALE: { light->version++; light->instance_change_notify(); } break; } light->param[p_param]=p_value; } void RasterizerStorageGLES3::light_set_shadow(RID p_light,bool p_enabled){ Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->shadow=p_enabled; light->version++; light->instance_change_notify(); } void RasterizerStorageGLES3::light_set_shadow_color(RID p_light,const Color& p_color) { Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->shadow_color=p_color; } void RasterizerStorageGLES3::light_set_projector(RID p_light,RID p_texture){ Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->projector=p_texture; } void RasterizerStorageGLES3::light_set_negative(RID p_light,bool p_enable){ Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->negative=p_enable; } void RasterizerStorageGLES3::light_set_cull_mask(RID p_light,uint32_t p_mask){ Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->cull_mask=p_mask; light->version++; light->instance_change_notify(); } void RasterizerStorageGLES3::light_omni_set_shadow_mode(RID p_light,VS::LightOmniShadowMode p_mode) { Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->omni_shadow_mode=p_mode; light->version++; light->instance_change_notify(); } VS::LightOmniShadowMode RasterizerStorageGLES3::light_omni_get_shadow_mode(RID p_light) { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,VS::LIGHT_OMNI_SHADOW_CUBE); return light->omni_shadow_mode; } void RasterizerStorageGLES3::light_omni_set_shadow_detail(RID p_light,VS::LightOmniShadowDetail p_detail) { Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->omni_shadow_detail=p_detail; light->version++; light->instance_change_notify(); } void RasterizerStorageGLES3::light_directional_set_shadow_mode(RID p_light,VS::LightDirectionalShadowMode p_mode){ Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->directional_shadow_mode=p_mode; light->version++; light->instance_change_notify(); } void RasterizerStorageGLES3::light_directional_set_blend_splits(RID p_light,bool p_enable) { Light * light = light_owner.getornull(p_light); ERR_FAIL_COND(!light); light->directional_blend_splits=p_enable; light->version++; light->instance_change_notify(); } bool RasterizerStorageGLES3::light_directional_get_blend_splits(RID p_light) const { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,false); return light->directional_blend_splits; } VS::LightDirectionalShadowMode RasterizerStorageGLES3::light_directional_get_shadow_mode(RID p_light) { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL); return light->directional_shadow_mode; } VS::LightType RasterizerStorageGLES3::light_get_type(RID p_light) const { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL); return light->type; } float RasterizerStorageGLES3::light_get_param(RID p_light,VS::LightParam p_param) { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL); return light->param[p_param]; } Color RasterizerStorageGLES3::light_get_color(RID p_light) { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,Color()); return light->color; } bool RasterizerStorageGLES3::light_has_shadow(RID p_light) const { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,VS::LIGHT_DIRECTIONAL); return light->shadow; } uint64_t RasterizerStorageGLES3::light_get_version(RID p_light) const { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,0); return light->version; } Rect3 RasterizerStorageGLES3::light_get_aabb(RID p_light) const { const Light * light = light_owner.getornull(p_light); ERR_FAIL_COND_V(!light,Rect3()); switch( light->type ) { case VS::LIGHT_SPOT: { float len=light->param[VS::LIGHT_PARAM_RANGE]; float size=Math::tan(Math::deg2rad(light->param[VS::LIGHT_PARAM_SPOT_ANGLE]))*len; return Rect3( Vector3( -size,-size,-len ), Vector3( size*2, size*2, len ) ); } break; case VS::LIGHT_OMNI: { float r = light->param[VS::LIGHT_PARAM_RANGE]; return Rect3( -Vector3(r,r,r), Vector3(r,r,r)*2 ); } break; case VS::LIGHT_DIRECTIONAL: { return Rect3(); } break; default: {} } ERR_FAIL_V( Rect3() ); return Rect3(); } /* PROBE API */ RID RasterizerStorageGLES3::reflection_probe_create(){ ReflectionProbe *reflection_probe = memnew( ReflectionProbe ); reflection_probe->intensity=1.0; reflection_probe->interior_ambient=Color(); reflection_probe->interior_ambient_energy=1.0; reflection_probe->max_distance=0; reflection_probe->extents=Vector3(1,1,1); reflection_probe->origin_offset=Vector3(0,0,0); reflection_probe->interior=false; reflection_probe->box_projection=false; reflection_probe->enable_shadows=false; reflection_probe->cull_mask=(1<<20)-1; reflection_probe->update_mode=VS::REFLECTION_PROBE_UPDATE_ONCE; return reflection_probe_owner.make_rid(reflection_probe); } void RasterizerStorageGLES3::reflection_probe_set_update_mode(RID p_probe, VS::ReflectionProbeUpdateMode p_mode) { ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->update_mode=p_mode; reflection_probe->instance_change_notify(); } void RasterizerStorageGLES3::reflection_probe_set_intensity(RID p_probe, float p_intensity) { ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->intensity=p_intensity; } void RasterizerStorageGLES3::reflection_probe_set_interior_ambient(RID p_probe, const Color& p_ambient) { ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->interior_ambient=p_ambient; } void RasterizerStorageGLES3::reflection_probe_set_interior_ambient_energy(RID p_probe, float p_energy) { ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->interior_ambient_energy=p_energy; } void RasterizerStorageGLES3::reflection_probe_set_interior_ambient_probe_contribution(RID p_probe, float p_contrib) { ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->interior_ambient_probe_contrib=p_contrib; } void RasterizerStorageGLES3::reflection_probe_set_max_distance(RID p_probe, float p_distance){ ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->max_distance=p_distance; reflection_probe->instance_change_notify(); } void RasterizerStorageGLES3::reflection_probe_set_extents(RID p_probe, const Vector3& p_extents){ ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->extents=p_extents; reflection_probe->instance_change_notify(); } void RasterizerStorageGLES3::reflection_probe_set_origin_offset(RID p_probe, const Vector3& p_offset){ ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->origin_offset=p_offset; reflection_probe->instance_change_notify(); } void RasterizerStorageGLES3::reflection_probe_set_as_interior(RID p_probe, bool p_enable){ ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->interior=p_enable; } void RasterizerStorageGLES3::reflection_probe_set_enable_box_projection(RID p_probe, bool p_enable){ ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->box_projection=p_enable; } void RasterizerStorageGLES3::reflection_probe_set_enable_shadows(RID p_probe, bool p_enable){ ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->enable_shadows=p_enable; reflection_probe->instance_change_notify(); } void RasterizerStorageGLES3::reflection_probe_set_cull_mask(RID p_probe, uint32_t p_layers){ ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND(!reflection_probe); reflection_probe->cull_mask=p_layers; reflection_probe->instance_change_notify(); } Rect3 RasterizerStorageGLES3::reflection_probe_get_aabb(RID p_probe) const { const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!reflection_probe,Rect3()); Rect3 aabb; aabb.pos=-reflection_probe->extents; aabb.size=reflection_probe->extents*2.0; return aabb; } VS::ReflectionProbeUpdateMode RasterizerStorageGLES3::reflection_probe_get_update_mode(RID p_probe) const{ const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!reflection_probe,VS::REFLECTION_PROBE_UPDATE_ALWAYS); return reflection_probe->update_mode; } uint32_t RasterizerStorageGLES3::reflection_probe_get_cull_mask(RID p_probe) const { const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!reflection_probe,0); return reflection_probe->cull_mask; } Vector3 RasterizerStorageGLES3::reflection_probe_get_extents(RID p_probe) const { const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!reflection_probe,Vector3()); return reflection_probe->extents; } Vector3 RasterizerStorageGLES3::reflection_probe_get_origin_offset(RID p_probe) const{ const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!reflection_probe,Vector3()); return reflection_probe->origin_offset; } bool RasterizerStorageGLES3::reflection_probe_renders_shadows(RID p_probe) const { const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!reflection_probe,false); return reflection_probe->enable_shadows; } float RasterizerStorageGLES3::reflection_probe_get_origin_max_distance(RID p_probe) const{ const ReflectionProbe *reflection_probe = reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!reflection_probe,0); return reflection_probe->max_distance; } /* ROOM API */ RID RasterizerStorageGLES3::room_create(){ return RID(); } void RasterizerStorageGLES3::room_add_bounds(RID p_room, const PoolVector<Vector2>& p_convex_polygon,float p_height,const Transform& p_transform){ } void RasterizerStorageGLES3::room_clear_bounds(RID p_room){ } /* PORTAL API */ // portals are only (x/y) points, forming a convex shape, which its clockwise // order points outside. (z is 0); RID RasterizerStorageGLES3::portal_create(){ return RID(); } void RasterizerStorageGLES3::portal_set_shape(RID p_portal, const Vector<Point2>& p_shape){ } void RasterizerStorageGLES3::portal_set_enabled(RID p_portal, bool p_enabled){ } void RasterizerStorageGLES3::portal_set_disable_distance(RID p_portal, float p_distance){ } void RasterizerStorageGLES3::portal_set_disabled_color(RID p_portal, const Color& p_color){ } RID RasterizerStorageGLES3::gi_probe_create() { GIProbe *gip = memnew( GIProbe ); gip->bounds=Rect3(Vector3(),Vector3(1,1,1)); gip->dynamic_range=1.0; gip->energy=1.0; gip->interior=false; gip->compress=false; gip->version=1; gip->cell_size=1.0; return gi_probe_owner.make_rid(gip); } void RasterizerStorageGLES3::gi_probe_set_bounds(RID p_probe,const Rect3& p_bounds){ GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND(!gip); gip->bounds=p_bounds; gip->version++; gip->instance_change_notify(); } Rect3 RasterizerStorageGLES3::gi_probe_get_bounds(RID p_probe) const{ const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,Rect3()); return gip->bounds; } void RasterizerStorageGLES3::gi_probe_set_cell_size(RID p_probe,float p_size) { GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND(!gip); gip->cell_size=p_size; gip->version++; gip->instance_change_notify(); } float RasterizerStorageGLES3::gi_probe_get_cell_size(RID p_probe) const { const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,0); return gip->cell_size; } void RasterizerStorageGLES3::gi_probe_set_to_cell_xform(RID p_probe,const Transform& p_xform) { GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND(!gip); gip->to_cell=p_xform; } Transform RasterizerStorageGLES3::gi_probe_get_to_cell_xform(RID p_probe) const { const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,Transform()); return gip->to_cell; } void RasterizerStorageGLES3::gi_probe_set_dynamic_data(RID p_probe,const PoolVector<int>& p_data){ GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND(!gip); gip->dynamic_data=p_data; gip->version++; gip->instance_change_notify(); } PoolVector<int> RasterizerStorageGLES3::gi_probe_get_dynamic_data(RID p_probe) const{ const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,PoolVector<int>()); return gip->dynamic_data; } void RasterizerStorageGLES3::gi_probe_set_dynamic_range(RID p_probe,int p_range){ GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND(!gip); gip->dynamic_range=p_range; } int RasterizerStorageGLES3::gi_probe_get_dynamic_range(RID p_probe) const{ const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,0); return gip->dynamic_range; } void RasterizerStorageGLES3::gi_probe_set_energy(RID p_probe,float p_range){ GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND(!gip); gip->energy=p_range; } void RasterizerStorageGLES3::gi_probe_set_interior(RID p_probe,bool p_enable) { GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND(!gip); gip->interior=p_enable; } bool RasterizerStorageGLES3::gi_probe_is_interior(RID p_probe) const{ const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,false); return gip->interior; } void RasterizerStorageGLES3::gi_probe_set_compress(RID p_probe,bool p_enable) { GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND(!gip); gip->compress=p_enable; } bool RasterizerStorageGLES3::gi_probe_is_compressed(RID p_probe) const{ const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,false); return gip->compress; } float RasterizerStorageGLES3::gi_probe_get_energy(RID p_probe) const{ const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,0); return gip->energy; } uint32_t RasterizerStorageGLES3::gi_probe_get_version(RID p_probe) { const GIProbe *gip = gi_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!gip,0); return gip->version; } RasterizerStorage::GIProbeCompression RasterizerStorageGLES3::gi_probe_get_dynamic_data_get_preferred_compression() const { if (config.s3tc_supported) { return GI_PROBE_S3TC; } else { return GI_PROBE_UNCOMPRESSED; } } RID RasterizerStorageGLES3::gi_probe_dynamic_data_create(int p_width, int p_height, int p_depth, GIProbeCompression p_compression) { GIProbeData *gipd = memnew( GIProbeData ); gipd->width=p_width; gipd->height=p_height; gipd->depth=p_depth; gipd->compression=p_compression; glActiveTexture(GL_TEXTURE0); glGenTextures(1,&gipd->tex_id); glBindTexture(GL_TEXTURE_3D,gipd->tex_id); int level=0; int min_size=1; if (gipd->compression==GI_PROBE_S3TC) { min_size=4; } print_line("dyndata create"); while(true) { if (gipd->compression==GI_PROBE_S3TC) { int size = p_width * p_height * p_depth; glCompressedTexImage3D(GL_TEXTURE_3D,level,_EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT,p_width,p_height,p_depth,0, size,NULL); } else { glTexImage3D(GL_TEXTURE_3D,level,GL_RGBA8,p_width,p_height,p_depth,0,GL_RGBA,GL_UNSIGNED_BYTE,NULL); } if (p_width<=min_size || p_height<=min_size || p_depth<=min_size) break; p_width>>=1; p_height>>=1; p_depth>>=1; level++; } glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, level); gipd->levels=level+1; return gi_probe_data_owner.make_rid(gipd); } void RasterizerStorageGLES3::gi_probe_dynamic_data_update(RID p_gi_probe_data, int p_depth_slice, int p_slice_count, int p_mipmap, const void *p_data) { GIProbeData *gipd = gi_probe_data_owner.getornull(p_gi_probe_data); ERR_FAIL_COND(!gipd); /* Vector<uint8_t> data; data.resize((gipd->width>>p_mipmap)*(gipd->height>>p_mipmap)*(gipd->depth>>p_mipmap)*4); for(int i=0;i<(gipd->width>>p_mipmap);i++) { for(int j=0;j<(gipd->height>>p_mipmap);j++) { for(int k=0;k<(gipd->depth>>p_mipmap);k++) { int ofs = (k*(gipd->height>>p_mipmap)*(gipd->width>>p_mipmap)) + j *(gipd->width>>p_mipmap) + i; ofs*=4; data[ofs+0]=i*0xFF/(gipd->width>>p_mipmap); data[ofs+1]=j*0xFF/(gipd->height>>p_mipmap); data[ofs+2]=k*0xFF/(gipd->depth>>p_mipmap); data[ofs+3]=0xFF; } } } */ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_3D,gipd->tex_id); if (gipd->compression==GI_PROBE_S3TC) { int size = (gipd->width>>p_mipmap) * (gipd->height>>p_mipmap) * p_slice_count; glCompressedTexSubImage3D(GL_TEXTURE_3D,p_mipmap,0,0,p_depth_slice,gipd->width>>p_mipmap,gipd->height>>p_mipmap,p_slice_count,_EXT_COMPRESSED_RGBA_S3TC_DXT5_EXT,size, p_data); } else { glTexSubImage3D(GL_TEXTURE_3D,p_mipmap,0,0,p_depth_slice,gipd->width>>p_mipmap,gipd->height>>p_mipmap,p_slice_count,GL_RGBA,GL_UNSIGNED_BYTE,p_data); } //glTexImage3D(GL_TEXTURE_3D,p_mipmap,GL_RGBA8,gipd->width>>p_mipmap,gipd->height>>p_mipmap,gipd->depth>>p_mipmap,0,GL_RGBA,GL_UNSIGNED_BYTE,p_data); //glTexImage3D(GL_TEXTURE_3D,p_mipmap,GL_RGBA8,gipd->width>>p_mipmap,gipd->height>>p_mipmap,gipd->depth>>p_mipmap,0,GL_RGBA,GL_UNSIGNED_BYTE,data.ptr()); } /////// RID RasterizerStorageGLES3::particles_create() { Particles *particles = memnew( Particles ); return particles_owner.make_rid(particles); } void RasterizerStorageGLES3::particles_set_emitting(RID p_particles,bool p_emitting) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->emitting=p_emitting; } void RasterizerStorageGLES3::particles_set_amount(RID p_particles,int p_amount) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); int floats = p_amount*24; float * data = memnew_arr(float,floats); for(int i=0;i<floats;i++) { data[i]=0; } glBindBuffer(GL_ARRAY_BUFFER,particles->particle_buffers[0]); glBufferData(GL_ARRAY_BUFFER,floats*sizeof(float),data,GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,particles->particle_buffers[1]); glBufferData(GL_ARRAY_BUFFER,floats*sizeof(float),data,GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,0); particles->prev_ticks=0; particles->phase=0; particles->prev_phase=0; memdelete_arr(data); } void RasterizerStorageGLES3::particles_set_lifetime(RID p_particles,float p_lifetime){ Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->lifetime=p_lifetime; } void RasterizerStorageGLES3::particles_set_pre_process_time(RID p_particles,float p_time) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->pre_process_time=p_time; } void RasterizerStorageGLES3::particles_set_explosiveness_ratio(RID p_particles,float p_ratio) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->explosiveness=p_ratio; } void RasterizerStorageGLES3::particles_set_randomness_ratio(RID p_particles,float p_ratio) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->randomness=p_ratio; } void RasterizerStorageGLES3::particles_set_custom_aabb(RID p_particles,const Rect3& p_aabb) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->custom_aabb=p_aabb; } void RasterizerStorageGLES3::particles_set_gravity(RID p_particles,const Vector3& p_gravity) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->gravity=p_gravity; } void RasterizerStorageGLES3::particles_set_use_local_coordinates(RID p_particles,bool p_enable) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->use_local_coords=p_enable; } void RasterizerStorageGLES3::particles_set_process_material(RID p_particles,RID p_material) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->process_material=p_material; } void RasterizerStorageGLES3::particles_set_emission_shape(RID p_particles, VS::ParticlesEmissionShape p_shape) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->emission_shape=p_shape; } void RasterizerStorageGLES3::particles_set_emission_sphere_radius(RID p_particles,float p_radius) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->emission_sphere_radius=p_radius; } void RasterizerStorageGLES3::particles_set_emission_box_extents(RID p_particles,const Vector3& p_extents) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->emission_box_extents=p_extents; } void RasterizerStorageGLES3::particles_set_emission_points(RID p_particles,const PoolVector<Vector3>& p_points) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->emission_points=p_points; } void RasterizerStorageGLES3::particles_set_draw_order(RID p_particles,VS::ParticlesDrawOrder p_order) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->draw_order=p_order; } void RasterizerStorageGLES3::particles_set_draw_passes(RID p_particles,int p_count) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); particles->draw_passes.resize(p_count); } void RasterizerStorageGLES3::particles_set_draw_pass_material(RID p_particles,int p_pass, RID p_material) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); ERR_FAIL_INDEX(p_pass,particles->draw_passes.size()); particles->draw_passes[p_pass].material=p_material; } void RasterizerStorageGLES3::particles_set_draw_pass_mesh(RID p_particles,int p_pass, RID p_mesh) { Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND(!particles); ERR_FAIL_INDEX(p_pass,particles->draw_passes.size()); particles->draw_passes[p_pass].mesh=p_mesh; } Rect3 RasterizerStorageGLES3::particles_get_current_aabb(RID p_particles) { const Particles *particles = particles_owner.getornull(p_particles); ERR_FAIL_COND_V(!particles,Rect3()); return particles->computed_aabb; } void RasterizerStorageGLES3::update_particles() { glEnable(GL_RASTERIZER_DISCARD); glBindVertexArray(0); while (particle_update_list.first()) { //use transform feedback to process particles Particles *particles = particle_update_list.first()->self(); Material *material = material_owner.getornull(particles->process_material); if (!material || !material->shader || material->shader->mode!=VS::SHADER_PARTICLES) { shaders.particles.set_custom_shader(0); } else { shaders.particles.set_custom_shader( material->shader->custom_code_id ); if (material->ubo_id) { glBindBufferBase(GL_UNIFORM_BUFFER,0,material->ubo_id); } int tc = material->textures.size(); RID* textures = material->textures.ptr(); ShaderLanguage::ShaderNode::Uniform::Hint* texture_hints = material->shader->texture_hints.ptr(); for(int i=0;i<tc;i++) { glActiveTexture(GL_TEXTURE0+i); GLenum target; GLuint tex; RasterizerStorageGLES3::Texture *t = texture_owner.getornull( textures[i] ); if (!t) { //check hints target=GL_TEXTURE_2D; switch(texture_hints[i]) { case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: { tex=resources.black_tex; } break; case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: { tex=resources.aniso_tex; } break; case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: { tex=resources.normal_tex; } break; default: { tex=resources.white_tex; } break; } } else { target=t->target; tex = t->tex_id; } glBindTexture(target,tex); } } shaders.particles.bind(); shaders.particles.set_uniform(ParticlesShaderGLES3::ORIGIN,particles->origin); float new_phase = Math::fmod((float)particles->phase+(frame.delta/particles->lifetime),(float)1.0); shaders.particles.set_uniform(ParticlesShaderGLES3::SYSTEM_PHASE,new_phase); shaders.particles.set_uniform(ParticlesShaderGLES3::PREV_SYSTEM_PHASE,particles->phase); particles->phase = new_phase; shaders.particles.set_uniform(ParticlesShaderGLES3::TOTAL_PARTICLES,particles->amount); shaders.particles.set_uniform(ParticlesShaderGLES3::TIME,0.0); shaders.particles.set_uniform(ParticlesShaderGLES3::EXPLOSIVENESS,particles->explosiveness); shaders.particles.set_uniform(ParticlesShaderGLES3::DELTA,frame.delta); shaders.particles.set_uniform(ParticlesShaderGLES3::GRAVITY,particles->gravity); shaders.particles.set_uniform(ParticlesShaderGLES3::ATTRACTOR_COUNT,0); glBindBuffer(GL_ARRAY_BUFFER,particles->particle_buffers[0]); glBindBufferBase(GL_TRANSFORM_FEEDBACK_BUFFER, 0, particles->particle_buffers[1]); for(int i=0;i<6;i++) { glEnableVertexAttribArray(i); glVertexAttribPointer(i,4,GL_FLOAT,GL_FALSE,sizeof(float)*4*6,((uint8_t*)0)+(i*16)); } glBeginTransformFeedback(GL_POINTS); glDrawArrays(GL_POINTS,0,particles->amount); glEndTransformFeedback(); particle_update_list.remove(particle_update_list.first()); SWAP(particles->particle_buffers[0],particles->particle_buffers[1]); } glDisable(GL_RASTERIZER_DISCARD); for(int i=0;i<6;i++) { glDisableVertexAttribArray(i); } } //////// void RasterizerStorageGLES3::instance_add_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance) { Skeleton *skeleton = skeleton_owner.getornull(p_skeleton); ERR_FAIL_COND(!skeleton); skeleton->instances.insert(p_instance); } void RasterizerStorageGLES3::instance_remove_skeleton(RID p_skeleton,RasterizerScene::InstanceBase *p_instance) { Skeleton *skeleton = skeleton_owner.getornull(p_skeleton); ERR_FAIL_COND(!skeleton); skeleton->instances.erase(p_instance); } void RasterizerStorageGLES3::instance_add_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance) { Instantiable *inst=NULL; switch(p_instance->base_type) { case VS::INSTANCE_MESH: { inst = mesh_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_MULTIMESH: { inst = multimesh_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_IMMEDIATE: { inst = immediate_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_REFLECTION_PROBE: { inst = reflection_probe_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_LIGHT: { inst = light_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_GI_PROBE: { inst = gi_probe_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; default: { if (!inst) { ERR_FAIL(); } } } inst->instance_list.add( &p_instance->dependency_item ); } void RasterizerStorageGLES3::instance_remove_dependency(RID p_base,RasterizerScene::InstanceBase *p_instance){ Instantiable *inst=NULL; switch(p_instance->base_type) { case VS::INSTANCE_MESH: { inst = mesh_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_MULTIMESH: { inst = multimesh_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_IMMEDIATE: { inst = immediate_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_REFLECTION_PROBE: { inst = reflection_probe_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_LIGHT: { inst = light_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; case VS::INSTANCE_GI_PROBE: { inst = gi_probe_owner.getornull(p_base); ERR_FAIL_COND(!inst); } break; default: { if (!inst) { ERR_FAIL(); } } } ERR_FAIL_COND(!inst); inst->instance_list.remove( &p_instance->dependency_item ); } /* RENDER TARGET */ void RasterizerStorageGLES3::_render_target_clear(RenderTarget *rt) { if (rt->fbo) { glDeleteFramebuffers(1,&rt->fbo); glDeleteTextures(1,&rt->color); rt->fbo=0; } if (rt->buffers.fbo) { glDeleteFramebuffers(1,&rt->buffers.fbo); glDeleteRenderbuffers(1,&rt->buffers.depth); glDeleteRenderbuffers(1,&rt->buffers.diffuse); glDeleteRenderbuffers(1,&rt->buffers.specular); glDeleteRenderbuffers(1,&rt->buffers.normal_rough); glDeleteRenderbuffers(1,&rt->buffers.motion_sss); glDeleteFramebuffers(1,&rt->buffers.effect_fbo); glDeleteTextures(1,&rt->buffers.effect); rt->buffers.fbo=0; } if (rt->depth) { glDeleteTextures(1,&rt->depth); rt->depth=0; } if (rt->effects.ssao.blur_fbo[0]) { glDeleteFramebuffers(1,&rt->effects.ssao.blur_fbo[0]); glDeleteTextures(1,&rt->effects.ssao.blur_red[0]); glDeleteFramebuffers(1,&rt->effects.ssao.blur_fbo[1]); glDeleteTextures(1,&rt->effects.ssao.blur_red[1]); for(int i=0;i<rt->effects.ssao.depth_mipmap_fbos.size();i++) { glDeleteFramebuffers(1,&rt->effects.ssao.depth_mipmap_fbos[i]); } rt->effects.ssao.depth_mipmap_fbos.clear(); glDeleteTextures(1,&rt->effects.ssao.linear_depth); } if (rt->exposure.fbo) { glDeleteFramebuffers(1,&rt->exposure.fbo); glDeleteTextures(1,&rt->exposure.color); } Texture *tex = texture_owner.get(rt->texture); tex->alloc_height=0; tex->alloc_width=0; tex->width=0; tex->height=0; for(int i=0;i<2;i++) { for(int j=0;j<rt->effects.mip_maps[i].sizes.size();j++) { glDeleteFramebuffers(1,&rt->effects.mip_maps[i].sizes[j].fbo); } glDeleteTextures(1,&rt->effects.mip_maps[i].color); rt->effects.mip_maps[i].sizes.clear(); rt->effects.mip_maps[i].levels=0; } /* if (rt->effects.screen_space_depth) { glDeleteTextures(1,&rt->effects.screen_space_depth); rt->effects.screen_space_depth=0; } */ } void RasterizerStorageGLES3::_render_target_allocate(RenderTarget *rt){ if (rt->width<=0 || rt->height<=0) return; GLuint color_internal_format; GLuint color_format; GLuint color_type; Image::Format image_format; if (!rt->flags[RENDER_TARGET_HDR] || rt->flags[RENDER_TARGET_NO_3D]) { color_internal_format=GL_RGBA8; color_format=GL_RGBA; color_type=GL_UNSIGNED_BYTE; image_format=Image::FORMAT_RGBA8; } else { color_internal_format=GL_RGBA16F; color_format=GL_RGBA; color_type=GL_HALF_FLOAT; image_format=Image::FORMAT_RGBAH; } { /* FRONT FBO */ glActiveTexture(GL_TEXTURE0); glGenFramebuffers(1, &rt->fbo); glBindFramebuffer(GL_FRAMEBUFFER, rt->fbo); glGenTextures(1, &rt->depth); glBindTexture(GL_TEXTURE_2D, rt->depth); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, rt->width, rt->height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0); glGenTextures(1, &rt->color); glBindTexture(GL_TEXTURE_2D, rt->color); glTexImage2D(GL_TEXTURE_2D, 0, color_internal_format, rt->width, rt->height, 0, color_format, color_type, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->color, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo); ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE ); Texture *tex = texture_owner.get(rt->texture); tex->format=image_format; tex->gl_format_cache=color_format; tex->gl_type_cache=color_type; tex->gl_internal_format_cache=color_internal_format; tex->tex_id=rt->color; tex->width=rt->width; tex->alloc_width=rt->width; tex->height=rt->height; tex->alloc_height=rt->height; texture_set_flags(rt->texture,tex->flags); } /* BACK FBO */ if (config.render_arch==RENDER_ARCH_DESKTOP && !rt->flags[RENDER_TARGET_NO_3D]) { static const int msaa_value[]={0,2,4,8,16}; int msaa=msaa_value[rt->msaa]; //regular fbo glGenFramebuffers(1, &rt->buffers.fbo); glBindFramebuffer(GL_FRAMEBUFFER, rt->buffers.fbo); glGenRenderbuffers(1, &rt->buffers.depth); glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.depth); if (msaa==0) glRenderbufferStorage(GL_RENDERBUFFER,GL_DEPTH24_STENCIL8,rt->width,rt->height); else glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_DEPTH24_STENCIL8,rt->width,rt->height); glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,GL_RENDERBUFFER,rt->buffers.depth); glGenRenderbuffers(1, &rt->buffers.diffuse); glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.diffuse); if (msaa==0) glRenderbufferStorage(GL_RENDERBUFFER,color_internal_format,rt->width,rt->height); else glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_RGBA16F,rt->width,rt->height); glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_RENDERBUFFER,rt->buffers.diffuse); glGenRenderbuffers(1, &rt->buffers.specular); glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.specular); if (msaa==0) glRenderbufferStorage(GL_RENDERBUFFER,GL_RGBA16F,rt->width,rt->height); else glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,color_internal_format,rt->width,rt->height); glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT1,GL_RENDERBUFFER,rt->buffers.specular); glGenRenderbuffers(1, &rt->buffers.normal_rough); glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.normal_rough); if (msaa==0) glRenderbufferStorage(GL_RENDERBUFFER,GL_RGBA8,rt->width,rt->height); else glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_RGBA8,rt->width,rt->height); glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT2,GL_RENDERBUFFER,rt->buffers.normal_rough); glGenRenderbuffers(1, &rt->buffers.motion_sss); glBindRenderbuffer(GL_RENDERBUFFER, rt->buffers.motion_sss); if (msaa==0) glRenderbufferStorage(GL_RENDERBUFFER,GL_RGBA8,rt->width,rt->height); else glRenderbufferStorageMultisample(GL_RENDERBUFFER,msaa,GL_RGBA8,rt->width,rt->height); glFramebufferRenderbuffer(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT3,GL_RENDERBUFFER,rt->buffers.motion_sss); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo); if (status != GL_FRAMEBUFFER_COMPLETE) { printf("err status: %x\n",status); _render_target_clear(rt); ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE ); } glBindRenderbuffer(GL_RENDERBUFFER,0); // effect resolver glGenFramebuffers(1, &rt->buffers.effect_fbo); glBindFramebuffer(GL_FRAMEBUFFER, rt->buffers.effect_fbo); glGenTextures(1, &rt->buffers.effect); glBindTexture(GL_TEXTURE_2D, rt->buffers.effect); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, rt->width, rt->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->buffers.effect, 0); if (status != GL_FRAMEBUFFER_COMPLETE) { printf("err status: %x\n",status); _render_target_clear(rt); ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE ); } glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo); if (status != GL_FRAMEBUFFER_COMPLETE) { _render_target_clear(rt); ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE ); } for(int i=0;i<2;i++) { ERR_FAIL_COND( rt->effects.mip_maps[i].sizes.size() ); int w=rt->width; int h=rt->height; if (i>0) { w>>=1; h>>=1; } glGenTextures(1, &rt->effects.mip_maps[i].color); glBindTexture(GL_TEXTURE_2D, rt->effects.mip_maps[i].color); int level=0; while(true) { RenderTarget::Effects::MipMaps::Size mm; glTexImage2D(GL_TEXTURE_2D, level, color_internal_format, w, h, 0, color_format, color_type, NULL); mm.width=w; mm.height=h; rt->effects.mip_maps[i].sizes.push_back(mm); w>>=1; h>>=1; if (w<2 || h<2) break; level++; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, level); for(int j=0;j<rt->effects.mip_maps[i].sizes.size();j++) { RenderTarget::Effects::MipMaps::Size &mm=rt->effects.mip_maps[i].sizes[j]; glGenFramebuffers(1, &mm.fbo); glBindFramebuffer(GL_FRAMEBUFFER, mm.fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,rt->effects.mip_maps[i].color ,j); status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { _render_target_clear(rt); ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE ); } float zero[4]={1,0,1,0}; glClearBufferfv(GL_COLOR,0,zero); } glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo); rt->effects.mip_maps[i].levels=level; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } ///////////////// ssao //AO strength textures for(int i=0;i<2;i++) { glGenFramebuffers(1, &rt->effects.ssao.blur_fbo[i]); glBindFramebuffer(GL_FRAMEBUFFER, rt->effects.ssao.blur_fbo[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, rt->depth, 0); glGenTextures(1, &rt->effects.ssao.blur_red[i]); glBindTexture(GL_TEXTURE_2D, rt->effects.ssao.blur_red[i]); glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, rt->width, rt->height, 0, GL_RED, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->effects.ssao.blur_red[i], 0); status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { _render_target_clear(rt); ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE ); } } //5 mip levels for depth texture, but base is read separately glGenTextures(1, &rt->effects.ssao.linear_depth); glBindTexture(GL_TEXTURE_2D, rt->effects.ssao.linear_depth); int ssao_w=rt->width/2; int ssao_h=rt->height/2; for(int i=0;i<4;i++) { //5, but 4 mips, base is read directly to save bw glTexImage2D(GL_TEXTURE_2D, i, GL_R16UI, ssao_w, ssao_h, 0, GL_RED_INTEGER, GL_UNSIGNED_SHORT, NULL); ssao_w>>=1; ssao_h>>=1; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 3); for(int i=0;i<4;i++) { //5, but 4 mips, base is read directly to save bw GLuint fbo; glGenFramebuffers(1, &fbo); glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->effects.ssao.linear_depth, i); rt->effects.ssao.depth_mipmap_fbos.push_back(fbo); } //////Exposure glGenFramebuffers(1, &rt->exposure.fbo); glBindFramebuffer(GL_FRAMEBUFFER, rt->exposure.fbo); glGenTextures(1, &rt->exposure.color); glBindTexture(GL_TEXTURE_2D, rt->exposure.color); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, 1, 1, 0, GL_RED, GL_FLOAT, NULL); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, rt->exposure.color, 0); status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status != GL_FRAMEBUFFER_COMPLETE) { _render_target_clear(rt); ERR_FAIL_COND( status != GL_FRAMEBUFFER_COMPLETE ); } } } RID RasterizerStorageGLES3::render_target_create(){ RenderTarget *rt = memnew( RenderTarget ); Texture * t = memnew( Texture ); t->flags=0; t->width=0; t->height=0; t->alloc_height=0; t->alloc_width=0; t->format=Image::FORMAT_R8; t->target=GL_TEXTURE_2D; t->gl_format_cache=0; t->gl_internal_format_cache=0; t->gl_type_cache=0; t->data_size=0; t->compressed=false; t->srgb=false; t->total_data_size=0; t->ignore_mipmaps=false; t->mipmaps=0; t->active=true; t->tex_id=0; rt->texture=texture_owner.make_rid(t); return render_target_owner.make_rid(rt); } void RasterizerStorageGLES3::render_target_set_size(RID p_render_target,int p_width, int p_height){ RenderTarget *rt = render_target_owner.getornull(p_render_target); ERR_FAIL_COND(!rt); if (rt->width==p_width && rt->height==p_height) return; _render_target_clear(rt); rt->width=p_width; rt->height=p_height; _render_target_allocate(rt); } RID RasterizerStorageGLES3::render_target_get_texture(RID p_render_target) const{ RenderTarget *rt = render_target_owner.getornull(p_render_target); ERR_FAIL_COND_V(!rt,RID()); return rt->texture; } void RasterizerStorageGLES3::render_target_set_flag(RID p_render_target,RenderTargetFlags p_flag,bool p_value) { RenderTarget *rt = render_target_owner.getornull(p_render_target); ERR_FAIL_COND(!rt); rt->flags[p_flag]=p_value; switch(p_flag) { case RENDER_TARGET_NO_3D: case RENDER_TARGET_TRANSPARENT: { //must reset for these formats _render_target_clear(rt); _render_target_allocate(rt); } break; default: {} } } bool RasterizerStorageGLES3::render_target_renedered_in_frame(RID p_render_target){ return false; } void RasterizerStorageGLES3::render_target_set_msaa(RID p_render_target,VS::ViewportMSAA p_msaa) { RenderTarget *rt = render_target_owner.getornull(p_render_target); ERR_FAIL_COND(!rt); if (rt->msaa==p_msaa) return; _render_target_clear(rt); rt->msaa=p_msaa; _render_target_allocate(rt); } /* CANVAS SHADOW */ RID RasterizerStorageGLES3::canvas_light_shadow_buffer_create(int p_width) { CanvasLightShadow *cls = memnew( CanvasLightShadow ); if (p_width>config.max_texture_size) p_width=config.max_texture_size; cls->size=p_width; cls->height=16; glActiveTexture(GL_TEXTURE0); glGenFramebuffers(1, &cls->fbo); glBindFramebuffer(GL_FRAMEBUFFER, cls->fbo); glGenRenderbuffers(1, &cls->depth); glBindRenderbuffer(GL_RENDERBUFFER, cls->depth ); glRenderbufferStorage(GL_RENDERBUFFER,GL_DEPTH_COMPONENT24, cls->size, cls->height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, cls->depth); glBindRenderbuffer(GL_RENDERBUFFER, 0 ); glGenTextures(1,&cls->distance); glBindTexture(GL_TEXTURE_2D, cls->distance); if (config.use_rgba_2d_shadows) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cls->size, cls->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); } else { glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, cls->size, cls->height, 0, GL_RED, GL_FLOAT, NULL); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, cls->distance, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); //printf("errnum: %x\n",status); glBindFramebuffer(GL_FRAMEBUFFER, RasterizerStorageGLES3::system_fbo); ERR_FAIL_COND_V( status != GL_FRAMEBUFFER_COMPLETE, RID() ); return canvas_light_shadow_owner.make_rid(cls); } /* LIGHT SHADOW MAPPING */ RID RasterizerStorageGLES3::canvas_light_occluder_create() { CanvasOccluder *co = memnew( CanvasOccluder ); co->index_id=0; co->vertex_id=0; co->len=0; return canvas_occluder_owner.make_rid(co); } void RasterizerStorageGLES3::canvas_light_occluder_set_polylines(RID p_occluder, const PoolVector<Vector2>& p_lines) { CanvasOccluder *co = canvas_occluder_owner.get(p_occluder); ERR_FAIL_COND(!co); co->lines=p_lines; if (p_lines.size()!=co->len) { if (co->index_id) glDeleteBuffers(1,&co->index_id); if (co->vertex_id) glDeleteBuffers(1,&co->vertex_id); co->index_id=0; co->vertex_id=0; co->len=0; } if (p_lines.size()) { PoolVector<float> geometry; PoolVector<uint16_t> indices; int lc = p_lines.size(); geometry.resize(lc*6); indices.resize(lc*3); PoolVector<float>::Write vw=geometry.write(); PoolVector<uint16_t>::Write iw=indices.write(); PoolVector<Vector2>::Read lr=p_lines.read(); const int POLY_HEIGHT = 16384; for(int i=0;i<lc/2;i++) { vw[i*12+0]=lr[i*2+0].x; vw[i*12+1]=lr[i*2+0].y; vw[i*12+2]=POLY_HEIGHT; vw[i*12+3]=lr[i*2+1].x; vw[i*12+4]=lr[i*2+1].y; vw[i*12+5]=POLY_HEIGHT; vw[i*12+6]=lr[i*2+1].x; vw[i*12+7]=lr[i*2+1].y; vw[i*12+8]=-POLY_HEIGHT; vw[i*12+9]=lr[i*2+0].x; vw[i*12+10]=lr[i*2+0].y; vw[i*12+11]=-POLY_HEIGHT; iw[i*6+0]=i*4+0; iw[i*6+1]=i*4+1; iw[i*6+2]=i*4+2; iw[i*6+3]=i*4+2; iw[i*6+4]=i*4+3; iw[i*6+5]=i*4+0; } //if same buffer len is being set, just use BufferSubData to avoid a pipeline flush if (!co->vertex_id) { glGenBuffers(1,&co->vertex_id); glBindBuffer(GL_ARRAY_BUFFER,co->vertex_id); glBufferData(GL_ARRAY_BUFFER,lc*6*sizeof(real_t),vw.ptr(),GL_STATIC_DRAW); } else { glBindBuffer(GL_ARRAY_BUFFER,co->vertex_id); glBufferSubData(GL_ARRAY_BUFFER,0,lc*6*sizeof(real_t),vw.ptr()); } glBindBuffer(GL_ARRAY_BUFFER,0); //unbind if (!co->index_id) { glGenBuffers(1,&co->index_id); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,co->index_id); glBufferData(GL_ELEMENT_ARRAY_BUFFER,lc*3*sizeof(uint16_t),iw.ptr(),GL_STATIC_DRAW); } else { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,co->index_id); glBufferSubData(GL_ELEMENT_ARRAY_BUFFER,0,lc*3*sizeof(uint16_t),iw.ptr()); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); //unbind co->len=lc; } } VS::InstanceType RasterizerStorageGLES3::get_base_type(RID p_rid) const { if (mesh_owner.owns(p_rid)) { return VS::INSTANCE_MESH; } if (multimesh_owner.owns(p_rid)) { return VS::INSTANCE_MULTIMESH; } if (immediate_owner.owns(p_rid)) { return VS::INSTANCE_IMMEDIATE; } if (light_owner.owns(p_rid)) { return VS::INSTANCE_LIGHT; } if (reflection_probe_owner.owns(p_rid)) { return VS::INSTANCE_REFLECTION_PROBE; } if (gi_probe_owner.owns(p_rid)) { return VS::INSTANCE_GI_PROBE; } return VS::INSTANCE_NONE; } bool RasterizerStorageGLES3::free(RID p_rid){ if (render_target_owner.owns(p_rid)) { RenderTarget *rt = render_target_owner.getornull(p_rid); _render_target_clear(rt); Texture *t=texture_owner.get(rt->texture); texture_owner.free(rt->texture); memdelete(t); render_target_owner.free(p_rid); memdelete(rt); } else if (texture_owner.owns(p_rid)) { // delete the texture Texture *texture = texture_owner.get(p_rid); ERR_FAIL_COND_V(texture->render_target,true); //cant free the render target texture, dude info.texture_mem-=texture->total_data_size; texture_owner.free(p_rid); memdelete(texture); } else if (skybox_owner.owns(p_rid)) { // delete the skybox SkyBox *skybox = skybox_owner.get(p_rid); skybox_set_texture(p_rid,RID(),256); skybox_owner.free(p_rid); memdelete(skybox); } else if (shader_owner.owns(p_rid)) { // delete the texture Shader *shader = shader_owner.get(p_rid); if (shader->shader) shader->shader->free_custom_shader(shader->custom_code_id); if (shader->dirty_list.in_list()) _shader_dirty_list.remove(&shader->dirty_list); while (shader->materials.first()) { Material *mat = shader->materials.first()->self(); mat->shader=NULL; _material_make_dirty(mat); shader->materials.remove( shader->materials.first() ); } //material_shader.free_custom_shader(shader->custom_code_id); shader_owner.free(p_rid); memdelete(shader); } else if (material_owner.owns(p_rid)) { // delete the texture Material *material = material_owner.get(p_rid); if (material->shader) { material->shader->materials.remove( & material->list ); } if (material->ubo_id) { glDeleteBuffers(1,&material->ubo_id); } //remove from owners for (Map<Geometry*,int>::Element *E=material->geometry_owners.front();E;E=E->next()) { Geometry *g = E->key(); g->material=RID(); } for (Map<RasterizerScene::InstanceBase*,int>::Element *E=material->instance_owners.front();E;E=E->next()) { RasterizerScene::InstanceBase*ins=E->key(); if (ins->material_override==p_rid) { ins->material_override=RID(); } for(int i=0;i<ins->materials.size();i++) { if (ins->materials[i]==p_rid) { ins->materials[i]=RID(); } } } material_owner.free(p_rid); memdelete(material); } else if (skeleton_owner.owns(p_rid)) { // delete the texture Skeleton *skeleton = skeleton_owner.get(p_rid); if (skeleton->update_list.in_list()) { skeleton_update_list.remove(&skeleton->update_list); } for (Set<RasterizerScene::InstanceBase*>::Element *E=skeleton->instances.front();E;E=E->next()) { E->get()->skeleton=RID(); } skeleton_allocate(p_rid,0,false); skeleton_owner.free(p_rid); memdelete(skeleton); } else if (mesh_owner.owns(p_rid)) { // delete the texture Mesh *mesh = mesh_owner.get(p_rid); mesh->instance_remove_deps(); mesh_clear(p_rid); mesh_owner.free(p_rid); memdelete(mesh); } else if (multimesh_owner.owns(p_rid)) { // delete the texture MultiMesh *multimesh = multimesh_owner.get(p_rid); multimesh->instance_remove_deps(); multimesh_allocate(p_rid,0,VS::MULTIMESH_TRANSFORM_2D,VS::MULTIMESH_COLOR_NONE); //frees multimesh update_dirty_multimeshes(); multimesh_owner.free(p_rid); memdelete(multimesh); } else if (immediate_owner.owns(p_rid)) { Immediate *immediate = immediate_owner.get(p_rid); immediate->instance_remove_deps(); immediate_owner.free(p_rid); memdelete(immediate); } else if (light_owner.owns(p_rid)) { // delete the texture Light *light = light_owner.get(p_rid); light->instance_remove_deps(); light_owner.free(p_rid); memdelete(light); } else if (reflection_probe_owner.owns(p_rid)) { // delete the texture ReflectionProbe *reflection_probe = reflection_probe_owner.get(p_rid); reflection_probe->instance_remove_deps(); reflection_probe_owner.free(p_rid); memdelete(reflection_probe); } else if (gi_probe_owner.owns(p_rid)) { // delete the texture GIProbe *gi_probe = gi_probe_owner.get(p_rid); gi_probe_owner.free(p_rid); memdelete(gi_probe); } else if (gi_probe_data_owner.owns(p_rid)) { // delete the texture GIProbeData *gi_probe_data = gi_probe_data_owner.get(p_rid); print_line("dyndata delete"); glDeleteTextures(1,&gi_probe_data->tex_id); gi_probe_owner.free(p_rid); memdelete(gi_probe_data); } else if (canvas_occluder_owner.owns(p_rid)) { CanvasOccluder *co = canvas_occluder_owner.get(p_rid); if (co->index_id) glDeleteBuffers(1,&co->index_id); if (co->vertex_id) glDeleteBuffers(1,&co->vertex_id); canvas_occluder_owner.free(p_rid); memdelete(co); } else if (canvas_light_shadow_owner.owns(p_rid)) { CanvasLightShadow *cls = canvas_light_shadow_owner.get(p_rid); glDeleteFramebuffers(1,&cls->fbo); glDeleteRenderbuffers(1,&cls->depth); glDeleteTextures(1,&cls->distance); canvas_light_shadow_owner.free(p_rid); memdelete(cls); } else { return false; } return true; } //////////////////////////////////////////// void RasterizerStorageGLES3::initialize() { config.render_arch=RENDER_ARCH_DESKTOP; //config.fbo_deferred=int(Globals::get_singleton()->get("rendering/gles3/lighting_technique")); RasterizerStorageGLES3::system_fbo=0; //// extensions config /// { int max_extensions=0; print_line("getting extensions"); glGetIntegerv(GL_NUM_EXTENSIONS,&max_extensions); print_line("total "+itos(max_extensions)); for(int i=0;i<max_extensions;i++) { const GLubyte *s = glGetStringi( GL_EXTENSIONS,i ); if (!s) break; config.extensions.insert((const char*)s); } } config.shrink_textures_x2=false; config.use_fast_texture_filter=int(GlobalConfig::get_singleton()->get("rendering/quality/use_nearest_mipmap_filter")); config.use_anisotropic_filter = config.extensions.has("GL_EXT_texture_filter_anisotropic"); config.s3tc_supported=config.extensions.has("GL_EXT_texture_compression_dxt1") || config.extensions.has("GL_EXT_texture_compression_s3tc") || config.extensions.has("WEBGL_compressed_texture_s3tc"); config.etc_supported=config.extensions.has("GL_OES_compressed_ETC1_RGB8_texture"); config.latc_supported=config.extensions.has("GL_EXT_texture_compression_latc"); config.bptc_supported=config.extensions.has("GL_ARB_texture_compression_bptc"); #ifdef GLES_OVER_GL config.etc2_supported=false; #else config.etc2_supported=true; #endif config.pvrtc_supported=config.extensions.has("GL_IMG_texture_compression_pvrtc"); config.srgb_decode_supported=config.extensions.has("GL_EXT_texture_sRGB_decode"); config.anisotropic_level=1.0; config.use_anisotropic_filter=config.extensions.has("GL_EXT_texture_filter_anisotropic"); if (config.use_anisotropic_filter) { glGetFloatv(_GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT,&config.anisotropic_level); config.anisotropic_level=MIN(int(GlobalConfig::get_singleton()->get("rendering/quality/anisotropic_filter_level")),config.anisotropic_level); } frame.clear_request=false; shaders.copy.init(); { //default textures glGenTextures(1, &resources.white_tex); unsigned char whitetexdata[8*8*3]; for(int i=0;i<8*8*3;i++) { whitetexdata[i]=255; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,resources.white_tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,whitetexdata); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,0); glGenTextures(1, &resources.black_tex); unsigned char blacktexdata[8*8*3]; for(int i=0;i<8*8*3;i++) { blacktexdata[i]=0; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,resources.black_tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,blacktexdata); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,0); glGenTextures(1, &resources.normal_tex); unsigned char normaltexdata[8*8*3]; for(int i=0;i<8*8*3;i+=3) { normaltexdata[i+0]=128; normaltexdata[i+1]=128; normaltexdata[i+2]=255; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,resources.normal_tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,normaltexdata); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,0); glGenTextures(1, &resources.aniso_tex); unsigned char anisotexdata[8*8*3]; for(int i=0;i<8*8*3;i+=3) { anisotexdata[i+0]=255; anisotexdata[i+1]=128; anisotexdata[i+2]=0; } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,resources.aniso_tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0, GL_RGB, GL_UNSIGNED_BYTE,anisotexdata); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,0); } glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS,&config.max_texture_image_units); glGetIntegerv(GL_MAX_TEXTURE_SIZE,&config.max_texture_size); #ifdef GLES_OVER_GL config.use_rgba_2d_shadows=false; #else config.use_rgba_2d_shadows=true; #endif //generic quadie for copying { //quad buffers glGenBuffers(1,&resources.quadie); glBindBuffer(GL_ARRAY_BUFFER,resources.quadie); { const float qv[16]={ -1,-1, 0, 0, -1, 1, 0, 1, 1, 1, 1, 1, 1,-1, 1, 0, }; glBufferData(GL_ARRAY_BUFFER,sizeof(float)*16,qv,GL_STATIC_DRAW); } glBindBuffer(GL_ARRAY_BUFFER,0); //unbind glGenVertexArrays(1,&resources.quadie_array); glBindVertexArray(resources.quadie_array); glBindBuffer(GL_ARRAY_BUFFER,resources.quadie); glVertexAttribPointer(VS::ARRAY_VERTEX,2,GL_FLOAT,GL_FALSE,sizeof(float)*4,0); glEnableVertexAttribArray(0); glVertexAttribPointer(VS::ARRAY_TEX_UV,2,GL_FLOAT,GL_FALSE,sizeof(float)*4,((uint8_t*)NULL)+8); glEnableVertexAttribArray(4); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind } //generic quadie for copying without touching skybox { //transform feedback buffers uint32_t xf_feedback_size = GLOBAL_DEF("rendering/buffers/blend_shape_max_buffer_size_kb",4096); for(int i=0;i<2;i++) { glGenBuffers(1,&resources.transform_feedback_buffers[i]); glBindBuffer(GL_ARRAY_BUFFER,resources.transform_feedback_buffers[i]); glBufferData(GL_ARRAY_BUFFER,xf_feedback_size*1024,NULL,GL_STREAM_DRAW); } shaders.blend_shapes.init(); glGenVertexArrays(1,&resources.transform_feedback_array); } shaders.cubemap_filter.init(); shaders.particles.init(); glEnable(_EXT_TEXTURE_CUBE_MAP_SEAMLESS); frame.count=0; frame.prev_tick=0; frame.delta=0; config.keep_original_textures=false; } void RasterizerStorageGLES3::finalize() { glDeleteTextures(1, &resources.white_tex); glDeleteTextures(1, &resources.black_tex); glDeleteTextures(1, &resources.normal_tex); } RasterizerStorageGLES3::RasterizerStorageGLES3() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_delay.cpp
326
#include "audio_effect_delay.h" #include "servers/audio_server.h" #include "math_funcs.h" void AudioEffectDelayInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { int todo = p_frame_count; while(todo) { int to_mix = MIN(todo,256); //can't mix too much _process_chunk(p_src_frames,p_dst_frames,to_mix); p_src_frames+=to_mix; p_dst_frames+=to_mix; todo-=to_mix; } } void AudioEffectDelayInstance::_process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { float main_level_f=base->dry; float mix_rate = AudioServer::get_singleton()->get_mix_rate(); float tap_1_level_f=base->tap_1_active?Math::db2linear(base->tap_1_level):0.0; int tap_1_delay_frames=int((base->tap_1_delay_ms/1000.0)*mix_rate);; float tap_2_level_f=base->tap_2_active?Math::db2linear(base->tap_2_level):0.0; int tap_2_delay_frames=int((base->tap_2_delay_ms/1000.0)*mix_rate);; float feedback_level_f=base->feedback_active?Math::db2linear(base->feedback_level):0.0; unsigned int feedback_delay_frames=int((base->feedback_delay_ms/1000.0)*mix_rate);; AudioFrame tap1_vol=AudioFrame(tap_1_level_f,tap_1_level_f); tap1_vol.l*=CLAMP( 1.0 - base->tap_1_pan, 0, 1); tap1_vol.r*=CLAMP( 1.0 + base->tap_1_pan, 0, 1); AudioFrame tap2_vol=AudioFrame(tap_2_level_f,tap_2_level_f); tap2_vol.l*=CLAMP( 1.0 - base->tap_2_pan, 0, 1); tap2_vol.r*=CLAMP( 1.0 + base->tap_2_pan, 0, 1); // feedback lowpass here float lpf_c=expf(-2.0*Math_PI*base->feedback_lowpass/mix_rate); // 0 .. 10khz float lpf_ic=1.0-lpf_c; const AudioFrame *src=p_src_frames; AudioFrame *dst=p_dst_frames; AudioFrame *rb_buf=ring_buffer.ptr(); AudioFrame *fb_buf=feedback_buffer.ptr(); for (int i=0;i<p_frame_count;i++) { rb_buf[ring_buffer_pos&ring_buffer_mask]=src[i]; AudioFrame main_val=src[i]*main_level_f; AudioFrame tap_1_val=rb_buf[(ring_buffer_pos-tap_1_delay_frames)&ring_buffer_mask]*tap1_vol; AudioFrame tap_2_val=rb_buf[(ring_buffer_pos-tap_2_delay_frames)&ring_buffer_mask]*tap2_vol; AudioFrame out=main_val+tap_1_val+tap_2_val; out+=fb_buf[ feedback_buffer_pos ]; //apply lowpass and feedback gain AudioFrame fb_in=out*feedback_level_f*lpf_ic+h*lpf_c; fb_in.undenormalise(); //avoid denormals h=fb_in; fb_buf[ feedback_buffer_pos ]=fb_in; dst[i]=out; ring_buffer_pos++; if ( (++feedback_buffer_pos) >= feedback_delay_frames ) feedback_buffer_pos=0; } } Ref<AudioEffectInstance> AudioEffectDelay::instance() { Ref<AudioEffectDelayInstance> ins; ins.instance(); ins->base=Ref<AudioEffectDelay>(this); float ring_buffer_max_size=MAX_DELAY_MS+100; //add 100ms of extra room, just in case ring_buffer_max_size/=1000.0;//convert to seconds ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate(); int ringbuff_size=ring_buffer_max_size; int bits=0; while(ringbuff_size>0) { bits++; ringbuff_size/=2; } ringbuff_size=1<<bits; ins->ring_buffer_mask=ringbuff_size-1; ins->ring_buffer_pos=0; ins->ring_buffer.resize( ringbuff_size ); ins->feedback_buffer.resize( ringbuff_size ); ins->feedback_buffer_pos=0; ins->h=AudioFrame(0,0); return ins; } void AudioEffectDelay::set_dry(float p_dry) { dry=p_dry; } float AudioEffectDelay::get_dry(){ return dry; } void AudioEffectDelay::set_tap1_active(bool p_active){ tap_1_active=p_active; } bool AudioEffectDelay::is_tap1_active() const{ return tap_1_active; } void AudioEffectDelay::set_tap1_delay_ms(float p_delay_ms){ tap_1_delay_ms=p_delay_ms; } float AudioEffectDelay::get_tap1_delay_ms() const{ return tap_1_delay_ms; } void AudioEffectDelay::set_tap1_level_db(float p_level_db){ tap_1_level=p_level_db; } float AudioEffectDelay::get_tap1_level_db() const{ return tap_1_level; } void AudioEffectDelay::set_tap1_pan(float p_pan){ tap_1_pan=p_pan; } float AudioEffectDelay::get_tap1_pan() const{ return tap_1_pan; } void AudioEffectDelay::set_tap2_active(bool p_active){ tap_2_active=p_active; } bool AudioEffectDelay::is_tap2_active() const{ return tap_2_active; } void AudioEffectDelay::set_tap2_delay_ms(float p_delay_ms){ tap_2_delay_ms=p_delay_ms; } float AudioEffectDelay::get_tap2_delay_ms() const{ return tap_2_delay_ms; } void AudioEffectDelay::set_tap2_level_db(float p_level_db){ tap_2_level=p_level_db; } float AudioEffectDelay::get_tap2_level_db() const{ return tap_2_level; } void AudioEffectDelay::set_tap2_pan(float p_pan){ tap_2_pan=p_pan; } float AudioEffectDelay::get_tap2_pan() const{ return tap_2_pan; } void AudioEffectDelay::set_feedback_active(bool p_active){ feedback_active=p_active; } bool AudioEffectDelay::is_feedback_active() const{ return feedback_active; } void AudioEffectDelay::set_feedback_delay_ms(float p_delay_ms){ feedback_delay_ms=p_delay_ms; } float AudioEffectDelay::get_feedback_delay_ms() const{ return feedback_delay_ms; } void AudioEffectDelay::set_feedback_level_db(float p_level_db){ feedback_level=p_level_db; } float AudioEffectDelay::get_feedback_level_db() const{ return feedback_level; } void AudioEffectDelay::set_feedback_lowpass(float p_lowpass){ feedback_lowpass=p_lowpass; } float AudioEffectDelay::get_feedback_lowpass() const{ return feedback_lowpass; } void AudioEffectDelay::_bind_methods() { ClassDB::bind_method(_MD("set_dry","amount"),&AudioEffectDelay::set_dry); ClassDB::bind_method(_MD("get_dry"),&AudioEffectDelay::get_dry); ClassDB::bind_method(_MD("set_tap1_active","amount"),&AudioEffectDelay::set_tap1_active); ClassDB::bind_method(_MD("is_tap1_active"),&AudioEffectDelay::is_tap1_active); ClassDB::bind_method(_MD("set_tap1_delay_ms","amount"),&AudioEffectDelay::set_tap1_delay_ms); ClassDB::bind_method(_MD("get_tap1_delay_ms"),&AudioEffectDelay::get_tap1_delay_ms); ClassDB::bind_method(_MD("set_tap1_level_db","amount"),&AudioEffectDelay::set_tap1_level_db); ClassDB::bind_method(_MD("get_tap1_level_db"),&AudioEffectDelay::get_tap1_level_db); ClassDB::bind_method(_MD("set_tap1_pan","amount"),&AudioEffectDelay::set_tap1_pan); ClassDB::bind_method(_MD("get_tap1_pan"),&AudioEffectDelay::get_tap1_pan); ClassDB::bind_method(_MD("set_tap2_active","amount"),&AudioEffectDelay::set_tap2_active); ClassDB::bind_method(_MD("is_tap2_active"),&AudioEffectDelay::is_tap2_active); ClassDB::bind_method(_MD("set_tap2_delay_ms","amount"),&AudioEffectDelay::set_tap2_delay_ms); ClassDB::bind_method(_MD("get_tap2_delay_ms"),&AudioEffectDelay::get_tap2_delay_ms); ClassDB::bind_method(_MD("set_tap2_level_db","amount"),&AudioEffectDelay::set_tap2_level_db); ClassDB::bind_method(_MD("get_tap2_level_db"),&AudioEffectDelay::get_tap2_level_db); ClassDB::bind_method(_MD("set_tap2_pan","amount"),&AudioEffectDelay::set_tap2_pan); ClassDB::bind_method(_MD("get_tap2_pan"),&AudioEffectDelay::get_tap2_pan); ClassDB::bind_method(_MD("set_feedback_active","amount"),&AudioEffectDelay::set_feedback_active); ClassDB::bind_method(_MD("is_feedback_active"),&AudioEffectDelay::is_feedback_active); ClassDB::bind_method(_MD("set_feedback_delay_ms","amount"),&AudioEffectDelay::set_feedback_delay_ms); ClassDB::bind_method(_MD("get_feedback_delay_ms"),&AudioEffectDelay::get_feedback_delay_ms); ClassDB::bind_method(_MD("set_feedback_level_db","amount"),&AudioEffectDelay::set_feedback_level_db); ClassDB::bind_method(_MD("get_feedback_level_db"),&AudioEffectDelay::get_feedback_level_db); ClassDB::bind_method(_MD("set_feedback_lowpass","amount"),&AudioEffectDelay::set_feedback_lowpass); ClassDB::bind_method(_MD("get_feedback_lowpass"),&AudioEffectDelay::get_feedback_lowpass); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_dry"),_SCS("get_dry")); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"tap1/active"),_SCS("set_tap1_active"),_SCS("is_tap1_active")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),_SCS("set_tap1_delay_ms"),_SCS("get_tap1_delay_ms")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),_SCS("set_tap1_level_db"),_SCS("get_tap1_level_db")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap1/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),_SCS("set_tap1_pan"),_SCS("get_tap1_pan")); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"tap2/active"),_SCS("set_tap2_active"),_SCS("is_tap2_active")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),_SCS("set_tap2_delay_ms"),_SCS("get_tap2_delay_ms")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),_SCS("set_tap2_level_db"),_SCS("get_tap2_level_db")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"tap2/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),_SCS("set_tap2_pan"),_SCS("get_tap2_pan")); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"feedback/active"),_SCS("set_feedback_active"),_SCS("is_feedback_active")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/delay_ms",PROPERTY_HINT_RANGE,"0,1500,1"),_SCS("set_feedback_delay_ms"),_SCS("get_feedback_delay_ms")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/level_db",PROPERTY_HINT_RANGE,"-60,0,0.01"),_SCS("set_feedback_level_db"),_SCS("get_feedback_level_db")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback/lowpass",PROPERTY_HINT_RANGE,"1,16000,1"),_SCS("set_feedback_lowpass"),_SCS("get_feedback_lowpass")); } AudioEffectDelay::AudioEffectDelay() { tap_1_active=true; tap_1_delay_ms=250; tap_1_level=-6; tap_1_pan=0.2; tap_2_active=true; tap_2_delay_ms=500; tap_2_level=-12; tap_2_pan=-0.4; feedback_active=false; feedback_delay_ms=340; feedback_level=-6; feedback_lowpass=16000; dry=1.0; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
scene/audio/audio_player.cpp
301
#include "audio_player.h" void AudioPlayer::_mix_audio() { if (!stream_playback.is_valid()) { return; } if (!active) { return; } if (setseek>=0.0) { stream_playback->start(setseek); setseek=-1.0; //reset seek } int bus_index = AudioServer::get_singleton()->thread_find_bus_index(bus); //get data AudioFrame *buffer = mix_buffer.ptr(); int buffer_size = mix_buffer.size(); //mix stream_playback->mix(buffer,1.0,buffer_size); //multiply volume interpolating to avoid clicks if this changes float vol = Math::db2linear(mix_volume_db); float vol_inc = (Math::db2linear(volume_db) - vol)/float(buffer_size); for(int i=0;i<buffer_size;i++) { buffer[i]*=vol; vol+=vol_inc; } //set volume for next mix mix_volume_db = volume_db; AudioFrame * targets[3]={NULL,NULL,NULL}; if (AudioServer::get_singleton()->get_speaker_mode()==AudioServer::SPEAKER_MODE_STEREO) { targets[0] = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,0); } else { switch(mix_target) { case MIX_TARGET_STEREO: { targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,1); } break; case MIX_TARGET_SURROUND: { targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,1); targets[1]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,2); if (AudioServer::get_singleton()->get_speaker_mode()==AudioServer::SPEAKER_SURROUND_71) { targets[2]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,3); } } break; case MIX_TARGET_CENTER: { targets[0]=AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus_index,0); } break; } } for(int c=0;c<3;c++) { if (!targets[c]) break; for(int i=0;i<buffer_size;i++) { targets[c][i]+=buffer[i]; } } } void AudioPlayer::_notification(int p_what) { if (p_what==NOTIFICATION_ENTER_TREE) { AudioServer::get_singleton()->add_callback(_mix_audios,this); if (autoplay && !get_tree()->is_editor_hint()) { play(); } } if (p_what==NOTIFICATION_EXIT_TREE) { AudioServer::get_singleton()->remove_callback(_mix_audios,this); } } void AudioPlayer::set_stream(Ref<AudioStream> p_stream) { AudioServer::get_singleton()->lock(); mix_buffer.resize(AudioServer::get_singleton()->thread_get_mix_buffer_size()); if (stream_playback.is_valid()) { stream_playback.unref(); stream.unref(); active=false; setseek=-1; } stream=p_stream; stream_playback=p_stream->instance_playback(); if (stream_playback.is_null()) { stream.unref(); ERR_FAIL_COND(stream_playback.is_null()); } AudioServer::get_singleton()->unlock(); } Ref<AudioStream> AudioPlayer::get_stream() const { return stream; } void AudioPlayer::set_volume_db(float p_volume) { volume_db=p_volume; } float AudioPlayer::get_volume_db() const { return volume_db; } void AudioPlayer::play(float p_from_pos) { if (stream_playback.is_valid()) { mix_volume_db=volume_db; //reset volume ramp setseek=p_from_pos; active=true; } } void AudioPlayer::seek(float p_seconds) { if (stream_playback.is_valid()) { setseek=p_seconds; } } void AudioPlayer::stop() { if (stream_playback.is_valid()) { active=false; } } bool AudioPlayer::is_playing() const { if (stream_playback.is_valid()) { return active && stream_playback->is_playing(); } return false; } float AudioPlayer::get_pos() { if (stream_playback.is_valid()) { return stream_playback->get_pos(); } return 0; } void AudioPlayer::set_bus(const StringName& p_bus) { //if audio is active, must lock this AudioServer::get_singleton()->lock(); bus=p_bus; AudioServer::get_singleton()->unlock(); } StringName AudioPlayer::get_bus() const { for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) { if (AudioServer::get_singleton()->get_bus_name(i)==bus) { return bus; } } return "Master"; } void AudioPlayer::set_autoplay(bool p_enable) { autoplay=p_enable; } bool AudioPlayer::is_autoplay_enabled() { return autoplay; } void AudioPlayer::set_mix_target(MixTarget p_target) { mix_target=p_target; } AudioPlayer::MixTarget AudioPlayer::get_mix_target() const{ return mix_target; } void AudioPlayer::_set_playing(bool p_enable) { if (p_enable) play(); else stop(); } bool AudioPlayer::_is_active() const { return active; } void AudioPlayer::_validate_property(PropertyInfo& property) const { if (property.name=="bus") { String options; for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) { if (i>0) options+=","; String name = AudioServer::get_singleton()->get_bus_name(i); options+=name; } property.hint_string=options; } } void AudioPlayer::_bus_layout_changed() { _change_notify(); } void AudioPlayer::_bind_methods() { ClassDB::bind_method(_MD("set_stream","stream:AudioStream"),&AudioPlayer::set_stream); ClassDB::bind_method(_MD("get_stream"),&AudioPlayer::get_stream); ClassDB::bind_method(_MD("set_volume_db","volume_db"),&AudioPlayer::set_volume_db); ClassDB::bind_method(_MD("get_volume_db"),&AudioPlayer::get_volume_db); ClassDB::bind_method(_MD("play","from_pos"),&AudioPlayer::play,DEFVAL(0.0)); ClassDB::bind_method(_MD("seek","to_pos"),&AudioPlayer::seek); ClassDB::bind_method(_MD("stop"),&AudioPlayer::stop); ClassDB::bind_method(_MD("is_playing"),&AudioPlayer::is_playing); ClassDB::bind_method(_MD("get_pos"),&AudioPlayer::get_pos); ClassDB::bind_method(_MD("set_bus","bus"),&AudioPlayer::set_bus); ClassDB::bind_method(_MD("get_bus"),&AudioPlayer::get_bus); ClassDB::bind_method(_MD("set_autoplay","enable"),&AudioPlayer::set_autoplay); ClassDB::bind_method(_MD("is_autoplay_enabled"),&AudioPlayer::is_autoplay_enabled); ClassDB::bind_method(_MD("set_mix_target","mix_target"),&AudioPlayer::set_mix_target); ClassDB::bind_method(_MD("get_mix_target"),&AudioPlayer::get_mix_target); ClassDB::bind_method(_MD("_set_playing","enable"),&AudioPlayer::_set_playing); ClassDB::bind_method(_MD("_is_active"),&AudioPlayer::_is_active); ClassDB::bind_method(_MD("_bus_layout_changed"),&AudioPlayer::_bus_layout_changed); ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"stream",PROPERTY_HINT_RESOURCE_TYPE,"AudioStream"),_SCS("set_stream"),_SCS("get_stream") ); ADD_PROPERTY( PropertyInfo(Variant::REAL,"volume_db",PROPERTY_HINT_RANGE,"-80,24"),_SCS("set_volume_db"),_SCS("get_volume_db") ); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"playing",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_EDITOR),_SCS("_set_playing"),_SCS("_is_active" )); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"autoplay"),_SCS("set_autoplay"),_SCS("is_autoplay_enabled") ); ADD_PROPERTY( PropertyInfo(Variant::INT,"mix_target",PROPERTY_HINT_ENUM,"Stereo,Surround,Center"),_SCS("set_mix_target"),_SCS("get_mix_target")); ADD_PROPERTY( PropertyInfo(Variant::STRING,"bus",PROPERTY_HINT_ENUM,""),_SCS("set_bus"),_SCS("get_bus")); } AudioPlayer::AudioPlayer() { mix_volume_db=0; volume_db=0; autoplay=false; setseek=-1; active=false; mix_target=MIX_TARGET_STEREO; AudioServer::get_singleton()->connect("bus_layout_changed",this,"_bus_layout_changed"); } AudioPlayer::~AudioPlayer() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
thirdparty/zlib/gzlib.c
637
/* gzlib.c -- zlib functions common to reading and writing gzip files * Copyright (C) 2004-2017 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" #if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__) # define LSEEK _lseeki64 #else #if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0 # define LSEEK lseek64 #else # define LSEEK lseek #endif #endif /* Local functions */ local void gz_reset OF((gz_statep)); local gzFile gz_open OF((const void *, int, const char *)); #if defined UNDER_CE /* Map the Windows error number in ERROR to a locale-dependent error message string and return a pointer to it. Typically, the values for ERROR come from GetLastError. The string pointed to shall not be modified by the application, but may be overwritten by a subsequent call to gz_strwinerror The gz_strwinerror function does not change the current setting of GetLastError. */ char ZLIB_INTERNAL *gz_strwinerror (error) DWORD error; { static char buf[1024]; wchar_t *msgbuf; DWORD lasterr = GetLastError(); DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, error, 0, /* Default language */ (LPVOID)&msgbuf, 0, NULL); if (chars != 0) { /* If there is an \r\n appended, zap it. */ if (chars >= 2 && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') { chars -= 2; msgbuf[chars] = 0; } if (chars > sizeof (buf) - 1) { chars = sizeof (buf) - 1; msgbuf[chars] = 0; } wcstombs(buf, msgbuf, chars + 1); LocalFree(msgbuf); } else { sprintf(buf, "unknown win32 error (%ld)", error); } SetLastError(lasterr); return buf; } #endif /* UNDER_CE */ /* Reset gzip file state */ local void gz_reset(state) gz_statep state; { state->x.have = 0; /* no output data available */ if (state->mode == GZ_READ) { /* for reading ... */ state->eof = 0; /* not at end of file */ state->past = 0; /* have not read past end yet */ state->how = LOOK; /* look for gzip header */ } state->seek = 0; /* no seek request pending */ gz_error(state, Z_OK, NULL); /* clear error */ state->x.pos = 0; /* no uncompressed data yet */ state->strm.avail_in = 0; /* no input data yet */ } /* Open a gzip file either by name or file descriptor. */ local gzFile gz_open(path, fd, mode) const void *path; int fd; const char *mode; { gz_statep state; z_size_t len; int oflag; #ifdef O_CLOEXEC int cloexec = 0; #endif #ifdef O_EXCL int exclusive = 0; #endif /* check input */ if (path == NULL) return NULL; /* allocate gzFile structure to return */ state = (gz_statep)malloc(sizeof(gz_state)); if (state == NULL) return NULL; state->size = 0; /* no buffers allocated yet */ state->want = GZBUFSIZE; /* requested buffer size */ state->msg = NULL; /* no error message yet */ /* interpret mode */ state->mode = GZ_NONE; state->level = Z_DEFAULT_COMPRESSION; state->strategy = Z_DEFAULT_STRATEGY; state->direct = 0; while (*mode) { if (*mode >= '0' && *mode <= '9') state->level = *mode - '0'; else switch (*mode) { case 'r': state->mode = GZ_READ; break; #ifndef NO_GZCOMPRESS case 'w': state->mode = GZ_WRITE; break; case 'a': state->mode = GZ_APPEND; break; #endif case '+': /* can't read and write at the same time */ free(state); return NULL; case 'b': /* ignore -- will request binary anyway */ break; #ifdef O_CLOEXEC case 'e': cloexec = 1; break; #endif #ifdef O_EXCL case 'x': exclusive = 1; break; #endif case 'f': state->strategy = Z_FILTERED; break; case 'h': state->strategy = Z_HUFFMAN_ONLY; break; case 'R': state->strategy = Z_RLE; break; case 'F': state->strategy = Z_FIXED; break; case 'T': state->direct = 1; break; default: /* could consider as an error, but just ignore */ ; } mode++; } /* must provide an "r", "w", or "a" */ if (state->mode == GZ_NONE) { free(state); return NULL; } /* can't force transparent read */ if (state->mode == GZ_READ) { if (state->direct) { free(state); return NULL; } state->direct = 1; /* for empty file */ } /* save the path name for error messages */ #ifdef WIDECHAR if (fd == -2) { len = wcstombs(NULL, path, 0); if (len == (z_size_t)-1) len = 0; } else #endif len = strlen((const char *)path); state->path = (char *)malloc(len + 1); if (state->path == NULL) { free(state); return NULL; } #ifdef WIDECHAR if (fd == -2) if (len) wcstombs(state->path, path, len + 1); else *(state->path) = 0; else #endif #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(state->path, len + 1, "%s", (const char *)path); #else strcpy(state->path, path); #endif /* compute the flags for open() */ oflag = #ifdef O_LARGEFILE O_LARGEFILE | #endif #ifdef O_BINARY O_BINARY | #endif #ifdef O_CLOEXEC (cloexec ? O_CLOEXEC : 0) | #endif (state->mode == GZ_READ ? O_RDONLY : (O_WRONLY | O_CREAT | #ifdef O_EXCL (exclusive ? O_EXCL : 0) | #endif (state->mode == GZ_WRITE ? O_TRUNC : O_APPEND))); /* open the file with the appropriate flags (or just use fd) */ state->fd = fd > -1 ? fd : ( #ifdef WIDECHAR fd == -2 ? _wopen(path, oflag, 0666) : #endif open((const char *)path, oflag, 0666)); if (state->fd == -1) { free(state->path); free(state); return NULL; } if (state->mode == GZ_APPEND) { LSEEK(state->fd, 0, SEEK_END); /* so gzoffset() is correct */ state->mode = GZ_WRITE; /* simplify later checks */ } /* save the current position for rewinding (only if reading) */ if (state->mode == GZ_READ) { state->start = LSEEK(state->fd, 0, SEEK_CUR); if (state->start == -1) state->start = 0; } /* initialize stream */ gz_reset(state); /* return stream */ return (gzFile)state; } /* -- see zlib.h -- */ gzFile ZEXPORT gzopen(path, mode) const char *path; const char *mode; { return gz_open(path, -1, mode); } /* -- see zlib.h -- */ gzFile ZEXPORT gzopen64(path, mode) const char *path; const char *mode; { return gz_open(path, -1, mode); } /* -- see zlib.h -- */ gzFile ZEXPORT gzdopen(fd, mode) int fd; const char *mode; { char *path; /* identifier for error messages */ gzFile gz; if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) return NULL; #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd); #else sprintf(path, "<fd:%d>", fd); /* for debugging */ #endif gz = gz_open(path, fd, mode); free(path); return gz; } /* -- see zlib.h -- */ #ifdef WIDECHAR gzFile ZEXPORT gzopen_w(path, mode) const wchar_t *path; const char *mode; { return gz_open(path, -2, mode); } #endif /* -- see zlib.h -- */ int ZEXPORT gzbuffer(file, size) gzFile file; unsigned size; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* make sure we haven't already allocated memory */ if (state->size != 0) return -1; /* check and set requested size */ if ((size << 1) < size) return -1; /* need to be able to double it */ if (size < 2) size = 2; /* need two bytes to check magic header */ state->want = size; return 0; } /* -- see zlib.h -- */ int ZEXPORT gzrewind(file) gzFile file; { gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no error */ if (state->mode != GZ_READ || (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* back up and start over */ if (LSEEK(state->fd, state->start, SEEK_SET) == -1) return -1; gz_reset(state); return 0; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gzseek64(file, offset, whence) gzFile file; z_off64_t offset; int whence; { unsigned n; z_off64_t ret; gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* check that there's no error */ if (state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; /* can only seek from start or relative to current position */ if (whence != SEEK_SET && whence != SEEK_CUR) return -1; /* normalize offset to a SEEK_CUR specification */ if (whence == SEEK_SET) offset -= state->x.pos; else if (state->seek) offset += state->skip; state->seek = 0; /* if within raw area while reading, just go there */ if (state->mode == GZ_READ && state->how == COPY && state->x.pos + offset >= 0) { ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR); if (ret == -1) return -1; state->x.have = 0; state->eof = 0; state->past = 0; state->seek = 0; gz_error(state, Z_OK, NULL); state->strm.avail_in = 0; state->x.pos += offset; return state->x.pos; } /* calculate skip amount, rewinding if needed for back seek when reading */ if (offset < 0) { if (state->mode != GZ_READ) /* writing -- can't go backwards */ return -1; offset += state->x.pos; if (offset < 0) /* before start of file! */ return -1; if (gzrewind(file) == -1) /* rewind, then skip to offset */ return -1; } /* if reading, skip what's in output buffer (one less gzgetc() check) */ if (state->mode == GZ_READ) { n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ? (unsigned)offset : state->x.have; state->x.have -= n; state->x.next += n; state->x.pos += n; offset -= n; } /* request skip (if not zero) */ if (offset) { state->seek = 1; state->skip = offset; } return state->x.pos + offset; } /* -- see zlib.h -- */ z_off_t ZEXPORT gzseek(file, offset, whence) gzFile file; z_off_t offset; int whence; { z_off64_t ret; ret = gzseek64(file, (z_off64_t)offset, whence); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gztell64(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* return position */ return state->x.pos + (state->seek ? state->skip : 0); } /* -- see zlib.h -- */ z_off_t ZEXPORT gztell(file) gzFile file; { z_off64_t ret; ret = gztell64(file); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ z_off64_t ZEXPORT gzoffset64(file) gzFile file; { z_off64_t offset; gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return -1; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return -1; /* compute and return effective offset in file */ offset = LSEEK(state->fd, 0, SEEK_CUR); if (offset == -1) return -1; if (state->mode == GZ_READ) /* reading */ offset -= state->strm.avail_in; /* don't count buffered input */ return offset; } /* -- see zlib.h -- */ z_off_t ZEXPORT gzoffset(file) gzFile file; { z_off64_t ret; ret = gzoffset64(file); return ret == (z_off_t)ret ? (z_off_t)ret : -1; } /* -- see zlib.h -- */ int ZEXPORT gzeof(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return 0; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return 0; /* return end-of-file state */ return state->mode == GZ_READ ? state->past : 0; } /* -- see zlib.h -- */ const char * ZEXPORT gzerror(file, errnum) gzFile file; int *errnum; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return NULL; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return NULL; /* return error information */ if (errnum != NULL) *errnum = state->err; return state->err == Z_MEM_ERROR ? "out of memory" : (state->msg == NULL ? "" : state->msg); } /* -- see zlib.h -- */ void ZEXPORT gzclearerr(file) gzFile file; { gz_statep state; /* get internal structure and check integrity */ if (file == NULL) return; state = (gz_statep)file; if (state->mode != GZ_READ && state->mode != GZ_WRITE) return; /* clear error and end-of-file */ if (state->mode == GZ_READ) { state->eof = 0; state->past = 0; } gz_error(state, Z_OK, NULL); } /* Create an error message in allocated memory and set state->err and state->msg accordingly. Free any previous error message already there. Do not try to free or allocate space if the error is Z_MEM_ERROR (out of memory). Simply save the error message as a static string. If there is an allocation failure constructing the error message, then convert the error to out of memory. */ void ZLIB_INTERNAL gz_error(state, err, msg) gz_statep state; int err; const char *msg; { /* free previously allocated message and clear */ if (state->msg != NULL) { if (state->err != Z_MEM_ERROR) free(state->msg); state->msg = NULL; } /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ if (err != Z_OK && err != Z_BUF_ERROR) state->x.have = 0; /* set error code, and if no message, then done */ state->err = err; if (msg == NULL) return; /* for an out of memory error, return literal string when requested */ if (err == Z_MEM_ERROR) return; /* construct error message with path */ if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) == NULL) { state->err = Z_MEM_ERROR; return; } #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3, "%s%s%s", state->path, ": ", msg); #else strcpy(state->msg, state->path); strcat(state->msg, ": "); strcat(state->msg, msg); #endif } #ifndef INT_MAX /* portably return maximum value for an int (when limits.h presumed not available) -- we need to do this to cover cases where 2's complement not used, since C standard permits 1's complement and sign-bit representations, otherwise we could just use ((unsigned)-1) >> 1 */ unsigned ZLIB_INTERNAL gz_intmax() { unsigned p, q; p = 1; do { q = p; p <<= 1; p++; } while (p > q); return q >> 1; } #endif
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/visual/visual_server_scene.cpp
3,612
#include "visual_server_scene.h" #include "visual_server_global.h" #include "os/os.h" /* CAMERA API */ RID VisualServerScene::camera_create() { Camera * camera = memnew( Camera ); return camera_owner.make_rid( camera ); } void VisualServerScene::camera_set_perspective(RID p_camera,float p_fovy_degrees, float p_z_near, float p_z_far) { Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->type=Camera::PERSPECTIVE; camera->fov=p_fovy_degrees; camera->znear=p_z_near; camera->zfar=p_z_far; } void VisualServerScene::camera_set_orthogonal(RID p_camera,float p_size, float p_z_near, float p_z_far) { Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->type=Camera::ORTHOGONAL; camera->size=p_size; camera->znear=p_z_near; camera->zfar=p_z_far; } void VisualServerScene::camera_set_transform(RID p_camera,const Transform& p_transform) { Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->transform=p_transform.orthonormalized(); } void VisualServerScene::camera_set_cull_mask(RID p_camera,uint32_t p_layers) { Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->visible_layers=p_layers; } void VisualServerScene::camera_set_environment(RID p_camera,RID p_env) { Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->env=p_env; } void VisualServerScene::camera_set_use_vertical_aspect(RID p_camera,bool p_enable) { Camera *camera = camera_owner.get( p_camera ); ERR_FAIL_COND(!camera); camera->vaspect=p_enable; } /* SCENARIO API */ void* VisualServerScene::_instance_pair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int) { //VisualServerScene *self = (VisualServerScene*)p_self; Instance *A = p_A; Instance *B = p_B; //instance indices are designed so greater always contains lesser if (A->base_type > B->base_type) { SWAP(A,B); //lesser always first } if (B->base_type==VS::INSTANCE_LIGHT && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { InstanceLightData * light = static_cast<InstanceLightData*>(B->base_data); InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); InstanceLightData::PairInfo pinfo; pinfo.geometry=A; pinfo.L = geom->lighting.push_back(B); List<InstanceLightData::PairInfo>::Element *E = light->geometries.push_back(pinfo); if (geom->can_cast_shadows) { light->shadow_dirty=true; } geom->lighting_dirty=true; return E; //this element should make freeing faster } else if (B->base_type==VS::INSTANCE_REFLECTION_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(B->base_data); InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); InstanceReflectionProbeData::PairInfo pinfo; pinfo.geometry=A; pinfo.L = geom->reflection_probes.push_back(B); List<InstanceReflectionProbeData::PairInfo>::Element *E = reflection_probe->geometries.push_back(pinfo); geom->reflection_dirty=true; return E; //this element should make freeing faster } else if (B->base_type==VS::INSTANCE_GI_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data); InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); InstanceGIProbeData::PairInfo pinfo; pinfo.geometry=A; pinfo.L = geom->gi_probes.push_back(B); List<InstanceGIProbeData::PairInfo>::Element *E = gi_probe->geometries.push_back(pinfo); geom->gi_probes_dirty=true; return E; //this element should make freeing faster } else if (B->base_type==VS::INSTANCE_GI_PROBE && A->base_type==VS::INSTANCE_LIGHT) { InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data); InstanceLightData * light = static_cast<InstanceLightData*>(A->base_data); return gi_probe->lights.insert(A); } #if 0 if (A->base_type==INSTANCE_PORTAL) { ERR_FAIL_COND_V( B->base_type!=INSTANCE_PORTAL,NULL ); A->portal_info->candidate_set.insert(B); B->portal_info->candidate_set.insert(A); self->_portal_attempt_connect(A); //attempt to conncet portal A (will go through B anyway) //this is a little hackish, but works fine in practice } else if (A->base_type==INSTANCE_GI_PROBE || B->base_type==INSTANCE_GI_PROBE) { if (B->base_type==INSTANCE_GI_PROBE) { SWAP(A,B); } ERR_FAIL_COND_V(B->base_type!=INSTANCE_GI_PROBE_SAMPLER,NULL); B->gi_probe_sampler_info->gi_probes.insert(A); } else if (A->base_type==INSTANCE_ROOM || B->base_type==INSTANCE_ROOM) { if (B->base_type==INSTANCE_ROOM) SWAP(A,B); ERR_FAIL_COND_V(! ((1<<B->base_type)&INSTANCE_GEOMETRY_MASK ),NULL); B->auto_rooms.insert(A); A->room_info->owned_autoroom_geometry.insert(B); self->_instance_validate_autorooms(B); } else { if (B->base_type==INSTANCE_LIGHT) { SWAP(A,B); } else if (A->base_type!=INSTANCE_LIGHT) { return NULL; } A->light_info->affected.insert(B); B->lights.insert(A); B->light_cache_dirty=true; } #endif return NULL; } void VisualServerScene::_instance_unpair(void *p_self, OctreeElementID, Instance *p_A,int, OctreeElementID, Instance *p_B,int,void* udata) { //VisualServerScene *self = (VisualServerScene*)p_self; Instance *A = p_A; Instance *B = p_B; //instance indices are designed so greater always contains lesser if (A->base_type > B->base_type) { SWAP(A,B); //lesser always first } if (B->base_type==VS::INSTANCE_LIGHT && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { InstanceLightData * light = static_cast<InstanceLightData*>(B->base_data); InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); List<InstanceLightData::PairInfo>::Element *E = reinterpret_cast<List<InstanceLightData::PairInfo>::Element*>(udata); geom->lighting.erase(E->get().L); light->geometries.erase(E); if (geom->can_cast_shadows) { light->shadow_dirty=true; } geom->lighting_dirty=true; } else if (B->base_type==VS::INSTANCE_REFLECTION_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(B->base_data); InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); List<InstanceReflectionProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceReflectionProbeData::PairInfo>::Element*>(udata); geom->reflection_probes.erase(E->get().L); reflection_probe->geometries.erase(E); geom->reflection_dirty=true; } else if (B->base_type==VS::INSTANCE_GI_PROBE && (1<<A->base_type)&VS::INSTANCE_GEOMETRY_MASK) { InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data); InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(A->base_data); List<InstanceGIProbeData::PairInfo>::Element *E = reinterpret_cast<List<InstanceGIProbeData::PairInfo>::Element*>(udata); geom->gi_probes.erase(E->get().L); gi_probe->geometries.erase(E); geom->gi_probes_dirty=true; } else if (B->base_type==VS::INSTANCE_GI_PROBE && A->base_type==VS::INSTANCE_LIGHT) { InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(B->base_data); InstanceLightData * light = static_cast<InstanceLightData*>(A->base_data); Set<Instance*>::Element *E = reinterpret_cast<Set<Instance*>::Element*>(udata); gi_probe->lights.erase(E); } #if 0 if (A->base_type==INSTANCE_PORTAL) { ERR_FAIL_COND( B->base_type!=INSTANCE_PORTAL ); A->portal_info->candidate_set.erase(B); B->portal_info->candidate_set.erase(A); //after disconnecting them, see if they can connect again self->_portal_attempt_connect(A); self->_portal_attempt_connect(B); } else if (A->base_type==INSTANCE_GI_PROBE || B->base_type==INSTANCE_GI_PROBE) { if (B->base_type==INSTANCE_GI_PROBE) { SWAP(A,B); } ERR_FAIL_COND(B->base_type!=INSTANCE_GI_PROBE_SAMPLER); B->gi_probe_sampler_info->gi_probes.erase(A); } else if (A->base_type==INSTANCE_ROOM || B->base_type==INSTANCE_ROOM) { if (B->base_type==INSTANCE_ROOM) SWAP(A,B); ERR_FAIL_COND(! ((1<<B->base_type)&INSTANCE_GEOMETRY_MASK )); B->auto_rooms.erase(A); B->valid_auto_rooms.erase(A); A->room_info->owned_autoroom_geometry.erase(B); }else { if (B->base_type==INSTANCE_LIGHT) { SWAP(A,B); } else if (A->base_type!=INSTANCE_LIGHT) { return; } A->light_info->affected.erase(B); B->lights.erase(A); B->light_cache_dirty=true; } #endif } RID VisualServerScene::scenario_create() { Scenario *scenario = memnew( Scenario ); ERR_FAIL_COND_V(!scenario,RID()); RID scenario_rid = scenario_owner.make_rid( scenario ); scenario->self=scenario_rid; scenario->octree.set_pair_callback(_instance_pair,this); scenario->octree.set_unpair_callback(_instance_unpair,this); scenario->reflection_probe_shadow_atlas=VSG::scene_render->shadow_atlas_create(); VSG::scene_render->shadow_atlas_set_size(scenario->reflection_probe_shadow_atlas,1024); //make enough shadows for close distance, don't bother with rest VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,0,4); VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,1,4); VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,2,4); VSG::scene_render->shadow_atlas_set_quadrant_subdivision(scenario->reflection_probe_shadow_atlas,3,8); scenario->reflection_atlas=VSG::scene_render->reflection_atlas_create(); return scenario_rid; } void VisualServerScene::scenario_set_debug(RID p_scenario,VS::ScenarioDebugMode p_debug_mode) { Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); scenario->debug=p_debug_mode; } void VisualServerScene::scenario_set_environment(RID p_scenario, RID p_environment) { Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); scenario->environment=p_environment; } void VisualServerScene::scenario_set_fallback_environment(RID p_scenario, RID p_environment) { Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); scenario->fallback_environment=p_environment; } void VisualServerScene::scenario_set_reflection_atlas_size(RID p_scenario, int p_size,int p_subdiv) { Scenario *scenario = scenario_owner.get(p_scenario); ERR_FAIL_COND(!scenario); VSG::scene_render->reflection_atlas_set_size(scenario->reflection_atlas,p_size); VSG::scene_render->reflection_atlas_set_subdivision(scenario->reflection_atlas,p_subdiv); } /* INSTANCING API */ void VisualServerScene::_instance_queue_update(Instance *p_instance,bool p_update_aabb,bool p_update_materials) { if (p_update_aabb) p_instance->update_aabb=true; if (p_update_materials) p_instance->update_materials=true; if (p_instance->update_item.in_list()) return; _instance_update_list.add(&p_instance->update_item); } // from can be mesh, light, area and portal so far. RID VisualServerScene::instance_create(){ Instance *instance = memnew( Instance ); ERR_FAIL_COND_V(!instance,RID()); RID instance_rid = instance_owner.make_rid(instance); instance->self=instance_rid; return instance_rid; } void VisualServerScene::instance_set_base(RID p_instance, RID p_base){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); Scenario *scenario = instance->scenario; if (instance->base_type!=VS::INSTANCE_NONE) { //free anything related to that base VSG::storage->instance_remove_dependency(instance->base,instance); if (scenario && instance->octree_id) { scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away instance->octree_id=0; } switch(instance->base_type) { case VS::INSTANCE_LIGHT: { InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data); if (instance->scenario && light->D) { instance->scenario->directional_lights.erase( light->D ); light->D=NULL; } VSG::scene_render->free(light->instance); } break; case VS::INSTANCE_REFLECTION_PROBE: { InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(instance->base_data); VSG::scene_render->free(reflection_probe->instance); if (reflection_probe->update_list.in_list()) { reflection_probe_render_list.remove(&reflection_probe->update_list); } } break; case VS::INSTANCE_GI_PROBE: { InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data); while(gi_probe->dynamic.updating_stage==GI_UPDATE_STAGE_LIGHTING) { //wait until bake is done if it's baking OS::get_singleton()->delay_usec(1); } if (gi_probe->update_element.in_list()) { gi_probe_update_list.remove(&gi_probe->update_element); } if (gi_probe->dynamic.probe_data.is_valid()) { VSG::storage->free(gi_probe->dynamic.probe_data); } VSG::scene_render->free(gi_probe->probe_instance); } break; } if (instance->base_data) { memdelete( instance->base_data ); instance->base_data=NULL; } instance->blend_values.clear(); for(int i=0;i<instance->materials.size();i++) { if (instance->materials[i].is_valid()) { VSG::storage->material_remove_instance_owner(instance->materials[i],instance); } } instance->materials.clear(); #if 0 if (instance->light_info) { if (instance->scenario && instance->light_info->D) instance->scenario->directional_lights.erase( instance->light_info->D ); rasterizer->free(instance->light_info->instance); memdelete(instance->light_info); instance->light_info=NULL; } if ( instance->room ) { instance_set_room(p_instance,RID()); /* if((1<<instance->base_type)&INSTANCE_GEOMETRY_MASK) instance->room->room_info->owned_geometry_instances.erase(instance->RE); else if (instance->base_type==INSTANCE_PORTAL) { print_line("freeing portal, is it there? "+itos(instance->room->room_info->owned_portal_instances.(instance->RE))); instance->room->room_info->owned_portal_instances.erase(instance->RE); } else if (instance->base_type==INSTANCE_ROOM) instance->room->room_info->owned_room_instances.erase(instance->RE); else if (instance->base_type==INSTANCE_LIGHT) instance->room->room_info->owned_light_instances.erase(instance->RE); instance->RE=NULL;*/ } if (instance->portal_info) { _portal_disconnect(instance,true); memdelete(instance->portal_info); instance->portal_info=NULL; } if (instance->gi_probe_info) { while(instance->gi_probe_info->owned_instances.size()) { Instance *owned=instance->gi_probe_info->owned_instances.front()->get(); owned->gi_probe=NULL; owned->data.gi_probe=NULL; owned->data.gi_probe_octree_xform=NULL; owned->BLE=NULL; instance->gi_probe_info->owned_instances.pop_front(); } memdelete(instance->gi_probe_info); instance->gi_probe_info=NULL; } if (instance->scenario && instance->octree_id) { instance->scenario->octree.erase( instance->octree_id ); instance->octree_id=0; } if (instance->room_info) { for(List<Instance*>::Element *E=instance->room_info->owned_geometry_instances.front();E;E=E->next()) { Instance *owned = E->get(); owned->room=NULL; owned->RE=NULL; } for(List<Instance*>::Element *E=instance->room_info->owned_portal_instances.front();E;E=E->next()) { _portal_disconnect(E->get(),true); Instance *owned = E->get(); owned->room=NULL; owned->RE=NULL; } for(List<Instance*>::Element *E=instance->room_info->owned_room_instances.front();E;E=E->next()) { Instance *owned = E->get(); owned->room=NULL; owned->RE=NULL; } if (instance->room_info->disconnected_child_portals.size()) { ERR_PRINT("BUG: Disconnected portals remain!"); } memdelete(instance->room_info); instance->room_info=NULL; } if (instance->particles_info) { rasterizer->free( instance->particles_info->instance ); memdelete(instance->particles_info); instance->particles_info=NULL; } if (instance->gi_probe_sampler_info) { while (instance->gi_probe_sampler_info->owned_instances.size()) { instance_geometry_set_gi_probe_sampler(instance->gi_probe_sampler_info->owned_instances.front()->get()->self,RID()); } if (instance->gi_probe_sampler_info->sampled_light.is_valid()) { rasterizer->free(instance->gi_probe_sampler_info->sampled_light); } memdelete( instance->gi_probe_sampler_info ); instance->gi_probe_sampler_info=NULL; } #endif } instance->base_type=VS::INSTANCE_NONE; instance->base=RID(); if (p_base.is_valid()) { instance->base_type=VSG::storage->get_base_type(p_base); ERR_FAIL_COND(instance->base_type==VS::INSTANCE_NONE); switch(instance->base_type) { case VS::INSTANCE_LIGHT: { InstanceLightData *light = memnew( InstanceLightData ); if (scenario && VSG::storage->light_get_type(p_base)==VS::LIGHT_DIRECTIONAL) { light->D = scenario->directional_lights.push_back(instance); } light->instance = VSG::scene_render->light_instance_create(p_base); instance->base_data=light; } break; case VS::INSTANCE_MESH: case VS::INSTANCE_MULTIMESH: case VS::INSTANCE_IMMEDIATE: { InstanceGeometryData *geom = memnew( InstanceGeometryData ); instance->base_data=geom; } break; case VS::INSTANCE_REFLECTION_PROBE: { InstanceReflectionProbeData *reflection_probe = memnew( InstanceReflectionProbeData ); reflection_probe->owner=instance; instance->base_data=reflection_probe; reflection_probe->instance=VSG::scene_render->reflection_probe_instance_create(p_base); } break; case VS::INSTANCE_GI_PROBE: { InstanceGIProbeData *gi_probe = memnew( InstanceGIProbeData ); instance->base_data=gi_probe; gi_probe->owner=instance; if (scenario && !gi_probe->update_element.in_list()) { gi_probe_update_list.add(&gi_probe->update_element); } gi_probe->probe_instance=VSG::scene_render->gi_probe_instance_create(); } break; } VSG::storage->instance_add_dependency(p_base,instance); instance->base=p_base; if (scenario) _instance_queue_update(instance,true,true); #if 0 if (rasterizer->is_mesh(p_base)) { instance->base_type=INSTANCE_MESH; instance->data.morph_values.resize( rasterizer->mesh_get_morph_target_count(p_base)); instance->data.materials.resize( rasterizer->mesh_get_surface_count(p_base)); } else if (rasterizer->is_multimesh(p_base)) { instance->base_type=INSTANCE_MULTIMESH; } else if (rasterizer->is_immediate(p_base)) { instance->base_type=INSTANCE_IMMEDIATE; } else if (rasterizer->is_particles(p_base)) { instance->base_type=INSTANCE_PARTICLES; instance->particles_info=memnew( Instance::ParticlesInfo ); instance->particles_info->instance = rasterizer->particles_instance_create( p_base ); } else if (rasterizer->is_light(p_base)) { instance->base_type=INSTANCE_LIGHT; instance->light_info = memnew( Instance::LightInfo ); instance->light_info->instance = rasterizer->light_instance_create(p_base); if (instance->scenario && rasterizer->light_get_type(p_base)==LIGHT_DIRECTIONAL) { instance->light_info->D = instance->scenario->directional_lights.push_back(instance->self); } } else if (room_owner.owns(p_base)) { instance->base_type=INSTANCE_ROOM; instance->room_info = memnew( Instance::RoomInfo ); instance->room_info->room=room_owner.get(p_base); } else if (portal_owner.owns(p_base)) { instance->base_type=INSTANCE_PORTAL; instance->portal_info = memnew(Instance::PortalInfo); instance->portal_info->portal=portal_owner.get(p_base); } else if (gi_probe_owner.owns(p_base)) { instance->base_type=INSTANCE_GI_PROBE; instance->gi_probe_info=memnew(Instance::BakedLightInfo); instance->gi_probe_info->gi_probe=gi_probe_owner.get(p_base); //instance->portal_info = memnew(Instance::PortalInfo); //instance->portal_info->portal=portal_owner.get(p_base); } else if (gi_probe_sampler_owner.owns(p_base)) { instance->base_type=INSTANCE_GI_PROBE_SAMPLER; instance->gi_probe_sampler_info=memnew( Instance::BakedLightSamplerInfo); instance->gi_probe_sampler_info->sampler=gi_probe_sampler_owner.get(p_base); //instance->portal_info = memnew(Instance::PortalInfo); //instance->portal_info->portal=portal_owner.get(p_base); } else { ERR_EXPLAIN("Invalid base RID for instance!") ERR_FAIL(); } instance_dependency_map[ p_base ].insert( instance->self ); #endif } } void VisualServerScene::instance_set_scenario(RID p_instance, RID p_scenario){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->scenario) { instance->scenario->instances.remove( &instance->scenario_item ); if (instance->octree_id) { instance->scenario->octree.erase(instance->octree_id); //make dependencies generated by the octree go away instance->octree_id=0; } switch(instance->base_type) { case VS::INSTANCE_LIGHT: { InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data); if (light->D) { instance->scenario->directional_lights.erase( light->D ); light->D=NULL; } } break; case VS::INSTANCE_REFLECTION_PROBE: { InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(instance->base_data); VSG::scene_render->reflection_probe_release_atlas_index(reflection_probe->instance); } break; case VS::INSTANCE_GI_PROBE: { InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data); if (gi_probe->update_element.in_list()) { gi_probe_update_list.remove(&gi_probe->update_element); } } break; } instance->scenario=NULL; } if (p_scenario.is_valid()) { Scenario *scenario = scenario_owner.get( p_scenario ); ERR_FAIL_COND(!scenario); instance->scenario=scenario; scenario->instances.add( &instance->scenario_item ); switch(instance->base_type) { case VS::INSTANCE_LIGHT: { InstanceLightData *light = static_cast<InstanceLightData*>(instance->base_data); if (VSG::storage->light_get_type(instance->base)==VS::LIGHT_DIRECTIONAL) { light->D = scenario->directional_lights.push_back(instance); } } break; case VS::INSTANCE_GI_PROBE: { InstanceGIProbeData *gi_probe = static_cast<InstanceGIProbeData*>(instance->base_data); if (!gi_probe->update_element.in_list()) { gi_probe_update_list.add(&gi_probe->update_element); } } break; } _instance_queue_update(instance,true,true); } } void VisualServerScene::instance_set_layer_mask(RID p_instance, uint32_t p_mask){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); instance->layer_mask=p_mask; } void VisualServerScene::instance_set_transform(RID p_instance, const Transform& p_transform){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->transform==p_transform) return; //must be checked to avoid worst evil instance->transform=p_transform; _instance_queue_update(instance,true); } void VisualServerScene::instance_attach_object_instance_ID(RID p_instance,ObjectID p_ID){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); instance->object_ID=p_ID; } void VisualServerScene::instance_set_blend_shape_weight(RID p_instance,int p_shape, float p_weight){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->update_item.in_list()) { _update_dirty_instance(instance); } ERR_FAIL_INDEX(p_shape,instance->blend_values.size()); instance->blend_values[p_shape]=p_weight; } void VisualServerScene::instance_set_surface_material(RID p_instance,int p_surface, RID p_material){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->update_item.in_list()) { _update_dirty_instance(instance); } ERR_FAIL_INDEX(p_surface,instance->materials.size()); if (instance->materials[p_surface].is_valid()) { VSG::storage->material_remove_instance_owner(instance->materials[p_surface],instance); } instance->materials[p_surface]=p_material; instance->base_material_changed(); if (instance->materials[p_surface].is_valid()) { VSG::storage->material_add_instance_owner(instance->materials[p_surface],instance); } } void VisualServerScene::instance_set_visible(RID p_instance,bool p_visible) { Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->visible==p_visible) return; instance->visible=p_visible; switch(instance->base_type) { case VS::INSTANCE_LIGHT: { if (VSG::storage->light_get_type(instance->base)!=VS::LIGHT_DIRECTIONAL && instance->octree_id && instance->scenario) { instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_LIGHT,p_visible?VS::INSTANCE_GEOMETRY_MASK:0); } } break; case VS::INSTANCE_REFLECTION_PROBE: { if (instance->octree_id && instance->scenario) { instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_REFLECTION_PROBE,p_visible?VS::INSTANCE_GEOMETRY_MASK:0); } } break; case VS::INSTANCE_GI_PROBE: { if (instance->octree_id && instance->scenario) { instance->scenario->octree.set_pairable(instance->octree_id,p_visible,1<<VS::INSTANCE_GI_PROBE,p_visible?(VS::INSTANCE_GEOMETRY_MASK|(1<<VS::INSTANCE_LIGHT)):0); } } break; } } void VisualServerScene::instance_attach_skeleton(RID p_instance,RID p_skeleton){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->skeleton==p_skeleton) return; if (instance->skeleton.is_valid()) { VSG::storage->instance_remove_skeleton(p_skeleton,instance); } instance->skeleton=p_skeleton; if (instance->skeleton.is_valid()) { VSG::storage->instance_add_skeleton(p_skeleton,instance); } _instance_queue_update(instance,true); } void VisualServerScene::instance_set_exterior( RID p_instance, bool p_enabled ){ } void VisualServerScene::instance_set_room( RID p_instance, RID p_room ){ } void VisualServerScene::instance_set_extra_visibility_margin( RID p_instance, real_t p_margin ){ } Vector<ObjectID> VisualServerScene::instances_cull_aabb(const Rect3& p_aabb, RID p_scenario) const { Vector<ObjectID> instances; Scenario *scenario=scenario_owner.get(p_scenario); ERR_FAIL_COND_V(!scenario,instances); const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling int culled=0; Instance *cull[1024]; culled=scenario->octree.cull_AABB(p_aabb,cull,1024); for (int i=0;i<culled;i++) { Instance *instance=cull[i]; ERR_CONTINUE(!instance); if (instance->object_ID==0) continue; instances.push_back(instance->object_ID); } return instances; } Vector<ObjectID> VisualServerScene::instances_cull_ray(const Vector3& p_from, const Vector3& p_to, RID p_scenario) const{ Vector<ObjectID> instances; Scenario *scenario=scenario_owner.get(p_scenario); ERR_FAIL_COND_V(!scenario,instances); const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling int culled=0; Instance *cull[1024]; culled=scenario->octree.cull_segment(p_from,p_to*10000,cull,1024); for (int i=0;i<culled;i++) { Instance *instance=cull[i]; ERR_CONTINUE(!instance); if (instance->object_ID==0) continue; instances.push_back(instance->object_ID); } return instances; } Vector<ObjectID> VisualServerScene::instances_cull_convex(const Vector<Plane>& p_convex, RID p_scenario) const{ Vector<ObjectID> instances; Scenario *scenario=scenario_owner.get(p_scenario); ERR_FAIL_COND_V(!scenario,instances); const_cast<VisualServerScene*>(this)->update_dirty_instances(); // check dirty instances before culling int culled=0; Instance *cull[1024]; culled=scenario->octree.cull_convex(p_convex,cull,1024); for (int i=0;i<culled;i++) { Instance *instance=cull[i]; ERR_CONTINUE(!instance); if (instance->object_ID==0) continue; instances.push_back(instance->object_ID); } return instances; } void VisualServerScene::instance_geometry_set_flag(RID p_instance,VS::InstanceFlags p_flags,bool p_enabled){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); switch(p_flags) { case VS::INSTANCE_FLAG_BILLBOARD: { instance->billboard=p_enabled; } break; case VS::INSTANCE_FLAG_BILLBOARD_FIX_Y: { instance->billboard_y=p_enabled; } break; case VS::INSTANCE_FLAG_CAST_SHADOW: { if (p_enabled == true) { instance->cast_shadows = VS::SHADOW_CASTING_SETTING_ON; } else { instance->cast_shadows = VS::SHADOW_CASTING_SETTING_OFF; } instance->base_material_changed(); // to actually compute if shadows are visible or not } break; case VS::INSTANCE_FLAG_DEPH_SCALE: { instance->depth_scale=p_enabled; } break; case VS::INSTANCE_FLAG_VISIBLE_IN_ALL_ROOMS: { instance->visible_in_all_rooms=p_enabled; } break; } } void VisualServerScene::instance_geometry_set_cast_shadows_setting(RID p_instance, VS::ShadowCastingSetting p_shadow_casting_setting) { } void VisualServerScene::instance_geometry_set_material_override(RID p_instance, RID p_material){ Instance *instance = instance_owner.get( p_instance ); ERR_FAIL_COND( !instance ); if (instance->material_override.is_valid()) { VSG::storage->material_remove_instance_owner(instance->material_override,instance); } instance->material_override=p_material; instance->base_material_changed(); if (instance->material_override.is_valid()) { VSG::storage->material_add_instance_owner(instance->material_override,instance); } } void VisualServerScene::instance_geometry_set_draw_range(RID p_instance,float p_min,float p_max,float p_min_margin,float p_max_margin){ } void VisualServerScene::instance_geometry_set_as_instance_lod(RID p_instance,RID p_as_lod_of_instance){ } void VisualServerScene::_update_instance(Instance *p_instance) { p_instance->version++; if (p_instance->base_type == VS::INSTANCE_LIGHT) { InstanceLightData *light = static_cast<InstanceLightData*>(p_instance->base_data); VSG::scene_render->light_instance_set_transform( light->instance, p_instance->transform ); light->shadow_dirty=true; } if (p_instance->base_type == VS::INSTANCE_REFLECTION_PROBE) { InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(p_instance->base_data); VSG::scene_render->reflection_probe_instance_set_transform( reflection_probe->instance, p_instance->transform ); reflection_probe->reflection_dirty=true; } if (p_instance->aabb.has_no_surface()) return; #if 0 if (p_instance->base_type == VS::INSTANCE_PARTICLES) { rasterizer->particles_instance_set_transform( p_instance->particles_info->instance, p_instance->data.transform ); } #endif if ((1<<p_instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) { InstanceGeometryData *geom = static_cast<InstanceGeometryData*>(p_instance->base_data); //make sure lights are updated if it casts shadow if (geom->can_cast_shadows) { for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) { InstanceLightData *light = static_cast<InstanceLightData*>(E->get()->base_data); light->shadow_dirty=true; } } } #if 0 else if (p_instance->base_type == INSTANCE_ROOM) { p_instance->room_info->affine_inverse=p_instance->data.transform.affine_inverse(); } else if (p_instance->base_type == INSTANCE_GI_PROBE) { Transform scale; scale.basis.scale(p_instance->gi_probe_info->gi_probe->octree_aabb.size); scale.origin=p_instance->gi_probe_info->gi_probe->octree_aabb.pos; //print_line("scale: "+scale); p_instance->gi_probe_info->affine_inverse=(p_instance->data.transform*scale).affine_inverse(); } #endif p_instance->mirror = p_instance->transform.basis.determinant() < 0.0; Rect3 new_aabb; #if 0 if (p_instance->base_type==INSTANCE_PORTAL) { //portals need to be transformed in a special way, so they don't become too wide if they have scale.. Transform portal_xform = p_instance->data.transform; portal_xform.basis.set_axis(2,portal_xform.basis.get_axis(2).normalized()); p_instance->portal_info->plane_cache=Plane( p_instance->data.transform.origin, portal_xform.basis.get_axis(2)); int point_count=p_instance->portal_info->portal->shape.size(); p_instance->portal_info->transformed_point_cache.resize(point_count); AABB portal_aabb; for(int i=0;i<point_count;i++) { Point2 src = p_instance->portal_info->portal->shape[i]; Vector3 point = portal_xform.xform(Vector3(src.x,src.y,0)); p_instance->portal_info->transformed_point_cache[i]=point; if (i==0) portal_aabb.pos=point; else portal_aabb.expand_to(point); } portal_aabb.grow_by(p_instance->portal_info->portal->connect_range); new_aabb = portal_aabb; } else { #endif new_aabb = p_instance->transform.xform(p_instance->aabb); #if 0 } #endif p_instance->transformed_aabb=new_aabb; if (!p_instance->scenario) { return; } if (p_instance->octree_id==0) { uint32_t base_type = 1<<p_instance->base_type; uint32_t pairable_mask=0; bool pairable=false; if (p_instance->base_type == VS::INSTANCE_LIGHT || p_instance->base_type==VS::INSTANCE_REFLECTION_PROBE) { pairable_mask=p_instance->visible?VS::INSTANCE_GEOMETRY_MASK:0; pairable=true; } if (p_instance->base_type == VS::INSTANCE_GI_PROBE) { //lights and geometries pairable_mask=p_instance->visible?VS::INSTANCE_GEOMETRY_MASK|(1<<VS::INSTANCE_LIGHT):0; pairable=true; } #if 0 if (p_instance->base_type == VS::INSTANCE_PORTAL) { pairable_mask=(1<<INSTANCE_PORTAL); pairable=true; } if (p_instance->base_type == VS::INSTANCE_GI_PROBE_SAMPLER) { pairable_mask=(1<<INSTANCE_GI_PROBE); pairable=true; } if (!p_instance->room && (1<<p_instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) { base_type|=VS::INSTANCE_ROOMLESS_MASK; } if (p_instance->base_type == VS::INSTANCE_ROOM) { pairable_mask=INSTANCE_ROOMLESS_MASK; pairable=true; } #endif // not inside octree p_instance->octree_id = p_instance->scenario->octree.create(p_instance,new_aabb,0,pairable,base_type,pairable_mask); } else { /* if (new_aabb==p_instance->data.transformed_aabb) return; */ p_instance->scenario->octree.move(p_instance->octree_id,new_aabb); } #if 0 if (p_instance->base_type==INSTANCE_PORTAL) { _portal_attempt_connect(p_instance); } if (!p_instance->room && (1<<p_instance->base_type)&INSTANCE_GEOMETRY_MASK) { _instance_validate_autorooms(p_instance); } if (p_instance->base_type == INSTANCE_ROOM) { for(Set<Instance*>::Element *E=p_instance->room_info->owned_autoroom_geometry.front();E;E=E->next()) _instance_validate_autorooms(E->get()); } #endif } void VisualServerScene::_update_instance_aabb(Instance *p_instance) { Rect3 new_aabb; ERR_FAIL_COND(p_instance->base_type!=VS::INSTANCE_NONE && !p_instance->base.is_valid()); switch(p_instance->base_type) { case VisualServer::INSTANCE_NONE: { // do nothing } break; case VisualServer::INSTANCE_MESH: { new_aabb = VSG::storage->mesh_get_aabb(p_instance->base,p_instance->skeleton); } break; case VisualServer::INSTANCE_MULTIMESH: { new_aabb = VSG::storage->multimesh_get_aabb(p_instance->base); } break; case VisualServer::INSTANCE_IMMEDIATE: { new_aabb = VSG::storage->immediate_get_aabb(p_instance->base); } break; #if 0 case VisualServer::INSTANCE_PARTICLES: { new_aabb = rasterizer->particles_get_aabb(p_instance->base); } break; #endif case VisualServer::INSTANCE_LIGHT: { new_aabb = VSG::storage->light_get_aabb(p_instance->base); } break; case VisualServer::INSTANCE_REFLECTION_PROBE: { new_aabb = VSG::storage->reflection_probe_get_aabb(p_instance->base); } break; case VisualServer::INSTANCE_GI_PROBE: { new_aabb = VSG::storage->gi_probe_get_bounds(p_instance->base); } break; #if 0 case VisualServer::INSTANCE_ROOM: { Room *room = room_owner.get( p_instance->base ); ERR_FAIL_COND(!room); new_aabb=room->bounds.get_aabb(); } break; case VisualServer::INSTANCE_PORTAL: { Portal *portal = portal_owner.get( p_instance->base ); ERR_FAIL_COND(!portal); for (int i=0;i<portal->shape.size();i++) { Vector3 point( portal->shape[i].x, portal->shape[i].y, 0 ); if (i==0) { new_aabb.pos=point; new_aabb.size.z=0.01; // make it not flat for octree } else { new_aabb.expand_to(point); } } } break; case VisualServer::INSTANCE_GI_PROBE: { BakedLight *gi_probe = gi_probe_owner.get( p_instance->base ); ERR_FAIL_COND(!gi_probe); new_aabb=gi_probe->octree_aabb; } break; case VisualServer::INSTANCE_GI_PROBE_SAMPLER: { BakedLightSampler *gi_probe_sampler = gi_probe_sampler_owner.get( p_instance->base ); ERR_FAIL_COND(!gi_probe_sampler); float radius = gi_probe_sampler->params[VS::BAKED_LIGHT_SAMPLER_RADIUS]; new_aabb=AABB(Vector3(-radius,-radius,-radius),Vector3(radius*2,radius*2,radius*2)); } break; #endif default: {} } if (p_instance->extra_margin) new_aabb.grow_by(p_instance->extra_margin); p_instance->aabb=new_aabb; } void VisualServerScene::_light_instance_update_shadow(Instance *p_instance,const Transform p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_orthogonal,RID p_shadow_atlas,Scenario* p_scenario) { InstanceLightData * light = static_cast<InstanceLightData*>(p_instance->base_data); switch(VSG::storage->light_get_type(p_instance->base)) { case VS::LIGHT_DIRECTIONAL: { float max_distance =p_cam_projection.get_z_far(); float shadow_max = VSG::storage->light_get_param(p_instance->base,VS::LIGHT_PARAM_SHADOW_MAX_DISTANCE); if (shadow_max>0) { max_distance=MIN(shadow_max,max_distance); } max_distance=MAX(max_distance,p_cam_projection.get_z_near()+0.001); float range = max_distance-p_cam_projection.get_z_near(); int splits=0; switch(VSG::storage->light_directional_get_shadow_mode(p_instance->base)) { case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: splits=1; break; case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: splits=2; break; case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: splits=4; break; } float distances[5]; distances[0]=p_cam_projection.get_z_near(); for(int i=0;i<splits;i++) { distances[i+1]=p_cam_projection.get_z_near()+VSG::storage->light_get_param(p_instance->base,VS::LightParam(VS::LIGHT_PARAM_SHADOW_SPLIT_1_OFFSET+i))*range; }; distances[splits]=max_distance; float texture_size=VSG::scene_render->get_directional_light_shadow_size(light->instance); bool overlap = VSG::storage->light_directional_get_blend_splits(p_instance->base); for (int i=0;i<splits;i++) { // setup a camera matrix for that range! CameraMatrix camera_matrix; float aspect = p_cam_projection.get_aspect(); if (p_cam_orthogonal) { float w,h; p_cam_projection.get_viewport_size(w,h); camera_matrix.set_orthogonal(w,aspect,distances[(i==0 || !overlap )?i:i-1],distances[i+1],false); } else { float fov = p_cam_projection.get_fov(); camera_matrix.set_perspective(fov,aspect,distances[(i==0 || !overlap )?i:i-1],distances[i+1],false); } //obtain the frustum endpoints Vector3 endpoints[8]; // frustum plane endpoints bool res = camera_matrix.get_endpoints(p_cam_transform,endpoints); ERR_CONTINUE(!res); // obtain the light frustm ranges (given endpoints) Vector3 x_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_X ).normalized(); Vector3 y_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_Y ).normalized(); Vector3 z_vec=p_instance->transform.basis.get_axis( Vector3::AXIS_Z ).normalized(); //z_vec points agsint the camera, like in default opengl float x_min,x_max; float y_min,y_max; float z_min,z_max; float x_min_cam,x_max_cam; float y_min_cam,y_max_cam; float z_min_cam,z_max_cam; //used for culling for(int j=0;j<8;j++) { float d_x=x_vec.dot(endpoints[j]); float d_y=y_vec.dot(endpoints[j]); float d_z=z_vec.dot(endpoints[j]); if (j==0 || d_x<x_min) x_min=d_x; if (j==0 || d_x>x_max) x_max=d_x; if (j==0 || d_y<y_min) y_min=d_y; if (j==0 || d_y>y_max) y_max=d_y; if (j==0 || d_z<z_min) z_min=d_z; if (j==0 || d_z>z_max) z_max=d_z; } { //camera viewport stuff //this trick here is what stabilizes the shadow (make potential jaggies to not move) //at the cost of some wasted resolution. Still the quality increase is very well worth it Vector3 center; for(int j=0;j<8;j++) { center+=endpoints[j]; } center/=8.0; //center=x_vec*(x_max-x_min)*0.5 + y_vec*(y_max-y_min)*0.5 + z_vec*(z_max-z_min)*0.5; float radius=0; for(int j=0;j<8;j++) { float d = center.distance_to(endpoints[j]); if (d>radius) radius=d; } radius *= texture_size/(texture_size-2.0); //add a texel by each side, so stepified texture will always fit x_max_cam=x_vec.dot(center)+radius; x_min_cam=x_vec.dot(center)-radius; y_max_cam=y_vec.dot(center)+radius; y_min_cam=y_vec.dot(center)-radius; z_max_cam=z_vec.dot(center)+radius; z_min_cam=z_vec.dot(center)-radius; float unit = radius*2.0/texture_size; x_max_cam=Math::stepify(x_max_cam,unit); x_min_cam=Math::stepify(x_min_cam,unit); y_max_cam=Math::stepify(y_max_cam,unit); y_min_cam=Math::stepify(y_min_cam,unit); } //now that we now all ranges, we can proceed to make the light frustum planes, for culling octree Vector<Plane> light_frustum_planes; light_frustum_planes.resize(6); //right/left light_frustum_planes[0]=Plane( x_vec, x_max ); light_frustum_planes[1]=Plane( -x_vec, -x_min ); //top/bottom light_frustum_planes[2]=Plane( y_vec, y_max ); light_frustum_planes[3]=Plane( -y_vec, -y_min ); //near/far light_frustum_planes[4]=Plane( z_vec, z_max+1e6 ); light_frustum_planes[5]=Plane( -z_vec, -z_min ); // z_min is ok, since casters further than far-light plane are not needed int cull_count = p_scenario->octree.cull_convex(light_frustum_planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK); // a pre pass will need to be needed to determine the actual z-near to be used for (int j=0;j<cull_count;j++) { float min,max; Instance *instance = instance_shadow_cull_result[j]; if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) { cull_count--; SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]); j--; } instance->transformed_aabb.project_range_in_plane(Plane(z_vec,0),min,max); if (max>z_max) z_max=max; } { CameraMatrix ortho_camera; real_t half_x = (x_max_cam-x_min_cam) * 0.5; real_t half_y = (y_max_cam-y_min_cam) * 0.5; ortho_camera.set_orthogonal( -half_x, half_x,-half_y,half_y, 0, (z_max-z_min_cam) ); Transform ortho_transform; ortho_transform.basis=p_instance->transform.basis; ortho_transform.origin=x_vec*(x_min_cam+half_x)+y_vec*(y_min_cam+half_y)+z_vec*z_max; VSG::scene_render->light_instance_set_shadow_transform(light->instance,ortho_camera,ortho_transform,0,distances[i+1],i); } VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count); } } break; case VS::LIGHT_OMNI: { VS::LightOmniShadowMode shadow_mode = VSG::storage->light_omni_get_shadow_mode(p_instance->base); switch(shadow_mode) { case VS::LIGHT_OMNI_SHADOW_DUAL_PARABOLOID: { for(int i=0;i<2;i++) { //using this one ensures that raster deferred will have it float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE); float z =i==0?-1:1; Vector<Plane> planes; planes.resize(5); planes[0]=p_instance->transform.xform(Plane(Vector3(0,0,z),radius)); planes[1]=p_instance->transform.xform(Plane(Vector3(1,0,z).normalized(),radius)); planes[2]=p_instance->transform.xform(Plane(Vector3(-1,0,z).normalized(),radius)); planes[3]=p_instance->transform.xform(Plane(Vector3(0,1,z).normalized(),radius)); planes[4]=p_instance->transform.xform(Plane(Vector3(0,-1,z).normalized(),radius)); int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK); for (int j=0;j<cull_count;j++) { Instance *instance = instance_shadow_cull_result[j]; if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) { cull_count--; SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]); j--; } } VSG::scene_render->light_instance_set_shadow_transform(light->instance,CameraMatrix(),p_instance->transform,radius,0,i); VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count); } } break; case VS::LIGHT_OMNI_SHADOW_CUBE: { float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE); CameraMatrix cm; cm.set_perspective(90,1,0.01,radius); for(int i=0;i<6;i++) { //using this one ensures that raster deferred will have it static const Vector3 view_normals[6]={ Vector3(-1, 0, 0), Vector3(+1, 0, 0), Vector3( 0,-1, 0), Vector3( 0,+1, 0), Vector3( 0, 0,-1), Vector3( 0, 0,+1) }; static const Vector3 view_up[6]={ Vector3( 0,-1, 0), Vector3( 0,-1, 0), Vector3( 0, 0,-1), Vector3( 0, 0,+1), Vector3( 0,-1, 0), Vector3( 0,-1, 0) }; Transform xform = p_instance->transform * Transform().looking_at(view_normals[i],view_up[i]); Vector<Plane> planes = cm.get_projection_planes(xform); int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK); for (int j=0;j<cull_count;j++) { Instance *instance = instance_shadow_cull_result[j]; if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) { cull_count--; SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]); j--; } } VSG::scene_render->light_instance_set_shadow_transform(light->instance,cm,xform,radius,0,i); VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,i,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count); } //restore the regular DP matrix VSG::scene_render->light_instance_set_shadow_transform(light->instance,CameraMatrix(),p_instance->transform,radius,0,0); } break; } } break; case VS::LIGHT_SPOT: { float radius = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_RANGE); float angle = VSG::storage->light_get_param( p_instance->base, VS::LIGHT_PARAM_SPOT_ANGLE); CameraMatrix cm; cm.set_perspective( angle*2.0, 1.0, 0.01, radius ); Vector<Plane> planes = cm.get_projection_planes(p_instance->transform); int cull_count = p_scenario->octree.cull_convex(planes,instance_shadow_cull_result,MAX_INSTANCE_CULL,VS::INSTANCE_GEOMETRY_MASK); for (int j=0;j<cull_count;j++) { Instance *instance = instance_shadow_cull_result[j]; if (!instance->visible || !((1<<instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) || !static_cast<InstanceGeometryData*>(instance->base_data)->can_cast_shadows) { cull_count--; SWAP(instance_shadow_cull_result[j],instance_shadow_cull_result[cull_count]); j--; } } VSG::scene_render->light_instance_set_shadow_transform(light->instance,cm,p_instance->transform,radius,0,0); VSG::scene_render->render_shadow(light->instance,p_shadow_atlas,0,(RasterizerScene::InstanceBase**)instance_shadow_cull_result,cull_count); } break; } } void VisualServerScene::render_camera(RID p_camera, RID p_scenario,Size2 p_viewport_size,RID p_shadow_atlas) { Camera *camera = camera_owner.getornull(p_camera); ERR_FAIL_COND(!camera); /* STEP 1 - SETUP CAMERA */ CameraMatrix camera_matrix; bool ortho=false; switch(camera->type) { case Camera::ORTHOGONAL: { camera_matrix.set_orthogonal( camera->size, p_viewport_size.width / (float)p_viewport_size.height, camera->znear, camera->zfar, camera->vaspect ); ortho=true; } break; case Camera::PERSPECTIVE: { camera_matrix.set_perspective( camera->fov, p_viewport_size.width / (float)p_viewport_size.height, camera->znear, camera->zfar, camera->vaspect ); ortho=false; } break; } _render_scene(camera->transform,camera_matrix,ortho,camera->env,camera->visible_layers,p_scenario,p_shadow_atlas,RID(),-1); } void VisualServerScene::_render_scene(const Transform p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_orthogonal,RID p_force_environment,uint32_t p_visible_layers, RID p_scenario,RID p_shadow_atlas,RID p_reflection_probe,int p_reflection_probe_pass) { Scenario *scenario = scenario_owner.getornull(p_scenario); render_pass++; uint32_t camera_layer_mask=p_visible_layers; VSG::scene_render->set_scene_pass(render_pass); //rasterizer->set_camera(camera->transform, camera_matrix,ortho); Vector<Plane> planes = p_cam_projection.get_projection_planes(p_cam_transform); Plane near_plane(p_cam_transform.origin,-p_cam_transform.basis.get_axis(2).normalized()); float z_far = p_cam_projection.get_z_far(); /* STEP 2 - CULL */ int cull_count = scenario->octree.cull_convex(planes,instance_cull_result,MAX_INSTANCE_CULL); light_cull_count=0; reflection_probe_cull_count=0; //light_samplers_culled=0; /* print_line("OT: "+rtos( (OS::get_singleton()->get_ticks_usec()-t)/1000.0)); print_line("OTO: "+itos(p_scenario->octree.get_octant_count())); //print_line("OTE: "+itos(p_scenario->octree.get_elem_count())); print_line("OTP: "+itos(p_scenario->octree.get_pair_count())); */ /* STEP 3 - PROCESS PORTALS, VALIDATE ROOMS */ // compute portals #if 0 exterior_visited=false; exterior_portal_cull_count=0; if (room_cull_enabled) { for(int i=0;i<cull_count;i++) { Instance *ins = instance_cull_result[i]; ins->last_render_pass=render_pass; if (ins->base_type!=INSTANCE_PORTAL) continue; if (ins->room) continue; ERR_CONTINUE(exterior_portal_cull_count>=MAX_EXTERIOR_PORTALS); exterior_portal_cull_result[exterior_portal_cull_count++]=ins; } room_cull_count = p_scenario->octree.cull_point(camera->transform.origin,room_cull_result,MAX_ROOM_CULL,NULL,(1<<INSTANCE_ROOM)|(1<<INSTANCE_PORTAL)); Set<Instance*> current_rooms; Set<Instance*> portal_rooms; //add to set for(int i=0;i<room_cull_count;i++) { if (room_cull_result[i]->base_type==INSTANCE_ROOM) { current_rooms.insert(room_cull_result[i]); } if (room_cull_result[i]->base_type==INSTANCE_PORTAL) { //assume inside that room if also inside the portal.. if (room_cull_result[i]->room) { portal_rooms.insert(room_cull_result[i]->room); } SWAP(room_cull_result[i],room_cull_result[room_cull_count-1]); room_cull_count--; i--; } } //remove from set if it has a parent room or BSP doesn't contain for(int i=0;i<room_cull_count;i++) { Instance *r = room_cull_result[i]; //check inside BSP Vector3 room_local_point = r->room_info->affine_inverse.xform( camera->transform.origin ); if (!portal_rooms.has(r) && !r->room_info->room->bounds.point_is_inside(room_local_point)) { current_rooms.erase(r); continue; } //check parent while (r->room) {// has parent room current_rooms.erase(r); r=r->room; } } if (current_rooms.size()) { //camera is inside a room // go through rooms for(Set<Instance*>::Element *E=current_rooms.front();E;E=E->next()) { _cull_room(camera,E->get()); } } else { //start from exterior _cull_room(camera,NULL); } } #endif /* STEP 4 - REMOVE FURTHER CULLED OBJECTS, ADD LIGHTS */ for(int i=0;i<cull_count;i++) { Instance *ins = instance_cull_result[i]; bool keep=false; if ((camera_layer_mask&ins->layer_mask)==0) { //failure } else if (ins->base_type==VS::INSTANCE_LIGHT && ins->visible) { if (ins->visible && light_cull_count<MAX_LIGHTS_CULLED) { InstanceLightData * light = static_cast<InstanceLightData*>(ins->base_data); if (!light->geometries.empty()) { //do not add this light if no geometry is affected by it.. light_cull_result[light_cull_count]=ins; light_instance_cull_result[light_cull_count]=light->instance; if (p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(ins->base)) { VSG::scene_render->light_instance_mark_visible(light->instance); //mark it visible for shadow allocation later } light_cull_count++; } } } else if (ins->base_type==VS::INSTANCE_REFLECTION_PROBE && ins->visible) { if (ins->visible && reflection_probe_cull_count<MAX_REFLECTION_PROBES_CULLED) { InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(ins->base_data); if (p_reflection_probe!=reflection_probe->instance) { //avoid entering The Matrix if (!reflection_probe->geometries.empty()) { //do not add this light if no geometry is affected by it.. if (reflection_probe->reflection_dirty || VSG::scene_render->reflection_probe_instance_needs_redraw(reflection_probe->instance)) { if (!reflection_probe->update_list.in_list()) { reflection_probe->render_step=0; reflection_probe_render_list.add(&reflection_probe->update_list); } reflection_probe->reflection_dirty=false; } if (VSG::scene_render->reflection_probe_instance_has_reflection(reflection_probe->instance)) { reflection_probe_instance_cull_result[reflection_probe_cull_count]=reflection_probe->instance; reflection_probe_cull_count++; } } } } } else if (ins->base_type==VS::INSTANCE_GI_PROBE && ins->visible) { InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(ins->base_data); if (!gi_probe->update_element.in_list()) { gi_probe_update_list.add(&gi_probe->update_element); } } else if ((1<<ins->base_type)&VS::INSTANCE_GEOMETRY_MASK && ins->visible && ins->cast_shadows!=VS::SHADOW_CASTING_SETTING_SHADOWS_ONLY) { keep=true; #if 0 bool discarded=false; if (ins->draw_range_end>0) { float d = cull_range.nearp.distance_to(ins->data.transform.origin); if (d<0) d=0; discarded=(d<ins->draw_range_begin || d>=ins->draw_range_end); } if (!discarded) { // test if this geometry should be visible if (room_cull_enabled) { if (ins->visible_in_all_rooms) { keep=true; } else if (ins->room) { if (ins->room->room_info->last_visited_pass==render_pass) keep=true; } else if (ins->auto_rooms.size()) { for(Set<Instance*>::Element *E=ins->auto_rooms.front();E;E=E->next()) { if (E->get()->room_info->last_visited_pass==render_pass) { keep=true; break; } } } else if(exterior_visited) keep=true; } else { keep=true; } } if (keep) { // update cull range float min,max; ins->transformed_aabb.project_range_in_plane(cull_range.nearp,min,max); if (min<cull_range.min) cull_range.min=min; if (max>cull_range.max) cull_range.max=max; if (ins->sampled_light && ins->sampled_light->gi_probe_sampler_info->last_pass!=render_pass) { if (light_samplers_culled<MAX_LIGHT_SAMPLERS) { light_sampler_cull_result[light_samplers_culled++]=ins->sampled_light; ins->sampled_light->gi_probe_sampler_info->last_pass=render_pass; } } } #endif InstanceGeometryData * geom = static_cast<InstanceGeometryData*>(ins->base_data); if (geom->lighting_dirty) { int l=0; //only called when lights AABB enter/exit this geometry ins->light_instances.resize(geom->lighting.size()); for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) { InstanceLightData * light = static_cast<InstanceLightData*>(E->get()->base_data); ins->light_instances[l++]=light->instance; } geom->lighting_dirty=false; } if (geom->reflection_dirty) { int l=0; //only called when reflection probe AABB enter/exit this geometry ins->reflection_probe_instances.resize(geom->reflection_probes.size()); for (List<Instance*>::Element *E=geom->reflection_probes.front();E;E=E->next()) { InstanceReflectionProbeData * reflection_probe = static_cast<InstanceReflectionProbeData*>(E->get()->base_data); ins->reflection_probe_instances[l++]=reflection_probe->instance; } geom->reflection_dirty=false; } if (geom->gi_probes_dirty) { int l=0; //only called when reflection probe AABB enter/exit this geometry ins->gi_probe_instances.resize(geom->gi_probes.size()); for (List<Instance*>::Element *E=geom->gi_probes.front();E;E=E->next()) { InstanceGIProbeData * gi_probe = static_cast<InstanceGIProbeData*>(E->get()->base_data); ins->gi_probe_instances[l++]=gi_probe->probe_instance; } geom->gi_probes_dirty=false; } ins->depth = near_plane.distance_to(ins->transform.origin); ins->depth_layer=CLAMP(int(ins->depth*8/z_far),0,7); } if (!keep) { // remove, no reason to keep cull_count--; SWAP( instance_cull_result[i], instance_cull_result[ cull_count ] ); i--; ins->last_render_pass=0; // make invalid } else { ins->last_render_pass=render_pass; } } /* STEP 5 - PROCESS LIGHTS */ RID *directional_light_ptr=&light_instance_cull_result[light_cull_count]; int directional_light_count=0; // directional lights { Instance** lights_with_shadow = (Instance**)alloca(sizeof(Instance*)*scenario->directional_lights.size()); int directional_shadow_count=0; for (List<Instance*>::Element *E=scenario->directional_lights.front();E;E=E->next()) { if (light_cull_count+directional_light_count>=MAX_LIGHTS_CULLED) { break; } if (!E->get()->visible) continue; InstanceLightData * light = static_cast<InstanceLightData*>(E->get()->base_data); //check shadow.. if (light && p_shadow_atlas.is_valid() && VSG::storage->light_has_shadow(E->get()->base)) { lights_with_shadow[directional_shadow_count++]=E->get(); } //add to list directional_light_ptr[directional_light_count++]=light->instance; } VSG::scene_render->set_directional_shadow_count(directional_shadow_count); for(int i=0;i<directional_shadow_count;i++) { _light_instance_update_shadow(lights_with_shadow[i],p_cam_transform,p_cam_projection,p_cam_orthogonal,p_shadow_atlas,scenario); } } { //setup shadow maps //SortArray<Instance*,_InstanceLightsort> sorter; //sorter.sort(light_cull_result,light_cull_count); for (int i=0;i<light_cull_count;i++) { Instance *ins = light_cull_result[i]; if (!p_shadow_atlas.is_valid() || !VSG::storage->light_has_shadow(ins->base)) continue; InstanceLightData * light = static_cast<InstanceLightData*>(ins->base_data); float coverage; { //compute coverage Transform cam_xf = p_cam_transform; float zn = p_cam_projection.get_z_near(); Plane p (cam_xf.origin + cam_xf.basis.get_axis(2) * -zn, -cam_xf.basis.get_axis(2) ); //camera near plane float vp_w,vp_h; //near plane size in screen coordinates p_cam_projection.get_viewport_size(vp_w,vp_h); switch(VSG::storage->light_get_type(ins->base)) { case VS::LIGHT_OMNI: { float radius = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_RANGE); //get two points parallel to near plane Vector3 points[2]={ ins->transform.origin, ins->transform.origin+cam_xf.basis.get_axis(0)*radius }; if (!p_cam_orthogonal) { //if using perspetive, map them to near plane for(int j=0;j<2;j++) { if (p.distance_to(points[j]) < 0 ) { points[j].z=-zn; //small hack to keep size constant when hitting the screen } p.intersects_segment(cam_xf.origin,points[j],&points[j]); //map to plane } } float screen_diameter = points[0].distance_to(points[1])*2; coverage = screen_diameter / (vp_w+vp_h); } break; case VS::LIGHT_SPOT: { float radius = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_RANGE); float angle = VSG::storage->light_get_param(ins->base,VS::LIGHT_PARAM_SPOT_ANGLE); float w = radius*Math::sin(Math::deg2rad(angle)); float d = radius*Math::cos(Math::deg2rad(angle)); Vector3 base = ins->transform.origin-ins->transform.basis.get_axis(2).normalized()*d; Vector3 points[2]={ base, base+cam_xf.basis.get_axis(0)*w }; if (!p_cam_orthogonal) { //if using perspetive, map them to near plane for(int j=0;j<2;j++) { if (p.distance_to(points[j]) < 0 ) { points[j].z=-zn; //small hack to keep size constant when hitting the screen } p.intersects_segment(cam_xf.origin,points[j],&points[j]); //map to plane } } float screen_diameter = points[0].distance_to(points[1])*2; coverage = screen_diameter / (vp_w+vp_h); } break; default: { ERR_PRINT("Invalid Light Type"); } } } if (light->shadow_dirty) { light->last_version++; light->shadow_dirty=false; } bool redraw = VSG::scene_render->shadow_atlas_update_light(p_shadow_atlas,light->instance,coverage,light->last_version); if (redraw) { print_line("redraw shadow"); //must redraw! _light_instance_update_shadow(ins,p_cam_transform,p_cam_projection,p_cam_orthogonal,p_shadow_atlas,scenario); } } } /* ENVIRONMENT */ RID environment; if (p_force_environment.is_valid()) //camera has more environment priority environment=p_force_environment; else if (scenario->environment.is_valid()) environment=scenario->environment; else environment=scenario->fallback_environment; #if 0 /* STEP 6 - SAMPLE BAKED LIGHT */ bool islinear =false; if (environment.is_valid()) { islinear = rasterizer->environment_is_fx_enabled(environment,VS::ENV_FX_SRGB); } for(int i=0;i<light_samplers_culled;i++) { _process_sampled_light(camera->transform,light_sampler_cull_result[i],islinear); } #endif /* STEP 7 - PROCESS GEOMETRY AND DRAW SCENE*/ VSG::scene_render->render_scene(p_cam_transform, p_cam_projection,p_cam_orthogonal,(RasterizerScene::InstanceBase**)instance_cull_result,cull_count,light_instance_cull_result,light_cull_count+directional_light_count,reflection_probe_instance_cull_result,reflection_probe_cull_count,environment,p_shadow_atlas,scenario->reflection_atlas,p_reflection_probe,p_reflection_probe_pass); } bool VisualServerScene::_render_reflection_probe_step(Instance* p_instance,int p_step) { InstanceReflectionProbeData *reflection_probe = static_cast<InstanceReflectionProbeData*>(p_instance->base_data); Scenario *scenario = p_instance->scenario; ERR_FAIL_COND_V(!scenario,true); if (p_step==0) { if (!VSG::scene_render->reflection_probe_instance_begin_render(reflection_probe->instance,scenario->reflection_atlas)) { return true; //sorry, all full :( } } if (p_step>=0 && p_step<6) { static const Vector3 view_normals[6]={ Vector3(-1, 0, 0), Vector3(+1, 0, 0), Vector3( 0,-1, 0), Vector3( 0,+1, 0), Vector3( 0, 0,-1), Vector3( 0, 0,+1) }; Vector3 extents = VSG::storage->reflection_probe_get_extents(p_instance->base); Vector3 origin_offset = VSG::storage->reflection_probe_get_origin_offset(p_instance->base); float max_distance = VSG::storage->reflection_probe_get_origin_max_distance(p_instance->base); Vector3 edge = view_normals[p_step]*extents; float distance = ABS(view_normals[p_step].dot(edge)-view_normals[p_step].dot(origin_offset)); //distance from origin offset to actual view distance limit max_distance = MAX(max_distance,distance); //render cubemap side CameraMatrix cm; cm.set_perspective(90,1,0.01,max_distance); static const Vector3 view_up[6]={ Vector3( 0,-1, 0), Vector3( 0,-1, 0), Vector3( 0, 0,-1), Vector3( 0, 0,+1), Vector3( 0,-1, 0), Vector3( 0,-1, 0) }; Transform local_view; local_view.set_look_at(origin_offset,origin_offset+view_normals[p_step],view_up[p_step]); Transform xform = p_instance->transform * local_view; RID shadow_atlas; if (VSG::storage->reflection_probe_renders_shadows(p_instance->base)) { shadow_atlas=scenario->reflection_probe_shadow_atlas; } _render_scene(xform,cm,false,RID(),VSG::storage->reflection_probe_get_cull_mask(p_instance->base),p_instance->scenario->self,shadow_atlas,reflection_probe->instance,p_step); } else { //do roughness postprocess step until it belives it's done return VSG::scene_render->reflection_probe_instance_postprocess_step(reflection_probe->instance); } return false; } void VisualServerScene::_gi_probe_fill_local_data(int p_idx, int p_level, int p_x, int p_y, int p_z, const GIProbeDataCell* p_cell, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data, Vector<uint32_t> *prev_cell) { if (p_level==p_header->cell_subdiv-1) { Vector3 emission; emission.x=(p_cell[p_idx].emission>>24)/255.0; emission.y=((p_cell[p_idx].emission>>16)&0xFF)/255.0; emission.z=((p_cell[p_idx].emission>>8)&0xFF)/255.0; float l = (p_cell[p_idx].emission&0xFF)/255.0; l*=8.0; emission*=l; p_local_data[p_idx].energy[0]=uint16_t(emission.x*1024); //go from 0 to 1024 for light p_local_data[p_idx].energy[1]=uint16_t(emission.y*1024); //go from 0 to 1024 for light p_local_data[p_idx].energy[2]=uint16_t(emission.z*1024); //go from 0 to 1024 for light } else { p_local_data[p_idx].energy[0]=0; p_local_data[p_idx].energy[1]=0; p_local_data[p_idx].energy[2]=0; int half=(1<<(p_header->cell_subdiv-1))>>(p_level+1); for(int i=0;i<8;i++) { uint32_t child = p_cell[p_idx].children[i]; if (child==0xFFFFFFFF) continue; int x = p_x; int y = p_y; int z = p_z; if (i&1) x+=half; if (i&2) y+=half; if (i&4) z+=half; _gi_probe_fill_local_data(child,p_level+1,x,y,z,p_cell,p_header,p_local_data,prev_cell); } } //position for each part of the mipmaped texture p_local_data[p_idx].pos[0]=p_x>>(p_header->cell_subdiv-p_level-1); p_local_data[p_idx].pos[1]=p_y>>(p_header->cell_subdiv-p_level-1); p_local_data[p_idx].pos[2]=p_z>>(p_header->cell_subdiv-p_level-1); prev_cell[p_level].push_back(p_idx); } void VisualServerScene::_gi_probe_bake_threads(void* self) { VisualServerScene* vss = (VisualServerScene*)self; vss->_gi_probe_bake_thread(); } void VisualServerScene::_setup_gi_probe(Instance *p_instance) { InstanceGIProbeData *probe = static_cast<InstanceGIProbeData*>(p_instance->base_data); if (probe->dynamic.probe_data.is_valid()) { VSG::storage->free(probe->dynamic.probe_data); probe->dynamic.probe_data=RID(); } probe->dynamic.light_data=VSG::storage->gi_probe_get_dynamic_data(p_instance->base); if (probe->dynamic.light_data.size()==0) return; //using dynamic data PoolVector<int>::Read r=probe->dynamic.light_data.read(); const GIProbeDataHeader *header = (GIProbeDataHeader *)r.ptr(); probe->dynamic.local_data.resize(header->cell_count); int cell_count = probe->dynamic.local_data.size(); PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe->dynamic.local_data.write(); const GIProbeDataCell *cells = (GIProbeDataCell*)&r[16]; probe->dynamic.level_cell_lists.resize(header->cell_subdiv); _gi_probe_fill_local_data(0,0,0,0,0,cells,header,ldw.ptr(),probe->dynamic.level_cell_lists.ptr()); bool compress = VSG::storage->gi_probe_is_compressed(p_instance->base); probe->dynamic.compression = compress ? VSG::storage->gi_probe_get_dynamic_data_get_preferred_compression() : RasterizerStorage::GI_PROBE_UNCOMPRESSED; probe->dynamic.probe_data=VSG::storage->gi_probe_dynamic_data_create(header->width,header->height,header->depth,probe->dynamic.compression); probe->dynamic.bake_dynamic_range=VSG::storage->gi_probe_get_dynamic_range(p_instance->base); probe->dynamic.mipmaps_3d.clear(); probe->dynamic.grid_size[0]=header->width; probe->dynamic.grid_size[1]=header->height; probe->dynamic.grid_size[2]=header->depth; int size_limit = 1; int size_divisor = 1; if (probe->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) { print_line("S3TC"); size_limit=4; size_divisor=4; } for(int i=0;i<(int)header->cell_subdiv;i++) { uint32_t x = header->width >> i; uint32_t y = header->height >> i; uint32_t z = header->depth >> i; //create and clear mipmap PoolVector<uint8_t> mipmap; int size = x*y*z*4; size/=size_divisor; mipmap.resize(size); PoolVector<uint8_t>::Write w = mipmap.write(); zeromem(w.ptr(),size); w = PoolVector<uint8_t>::Write(); probe->dynamic.mipmaps_3d.push_back(mipmap); if (x<=size_limit || y<=size_limit || z<=size_limit) break; } probe->dynamic.updating_stage=GI_UPDATE_STAGE_CHECK; probe->invalid=false; probe->dynamic.enabled=true; Transform cell_to_xform = VSG::storage->gi_probe_get_to_cell_xform(p_instance->base); Rect3 bounds = VSG::storage->gi_probe_get_bounds(p_instance->base); float cell_size = VSG::storage->gi_probe_get_cell_size(p_instance->base); probe->dynamic.light_to_cell_xform=cell_to_xform * p_instance->transform.affine_inverse(); VSG::scene_render->gi_probe_instance_set_light_data(probe->probe_instance,p_instance->base,probe->dynamic.probe_data); VSG::scene_render->gi_probe_instance_set_transform_to_data(probe->probe_instance,probe->dynamic.light_to_cell_xform); VSG::scene_render->gi_probe_instance_set_bounds(probe->probe_instance,bounds.size/cell_size); probe->base_version=VSG::storage->gi_probe_get_version(p_instance->base); //if compression is S3TC, fill it up if (probe->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) { //create all blocks Vector<Map<uint32_t,InstanceGIProbeData::CompBlockS3TC> > comp_blocks; int mipmap_count = probe->dynamic.mipmaps_3d.size(); comp_blocks.resize(mipmap_count); for(int i=0;i<cell_count;i++) { const GIProbeDataCell &c = cells[i]; const InstanceGIProbeData::LocalData &ld = ldw[i]; int level = c.level_alpha>>16; int mipmap = header->cell_subdiv - level -1; if (mipmap >= mipmap_count) continue;//uninteresting int blockx = (ld.pos[0]>>2); int blocky = (ld.pos[1]>>2); int blockz = (ld.pos[2]); //compression is x/y only int blockw = (header->width >> mipmap) >> 2; int blockh = (header->height >> mipmap) >> 2; //print_line("cell "+itos(i)+" level "+itos(level)+"mipmap: "+itos(mipmap)+" pos: "+Vector3(blockx,blocky,blockz)+" size "+Vector2(blockw,blockh)); uint32_t key = blockz * blockw*blockh + blocky * blockw + blockx; Map<uint32_t,InstanceGIProbeData::CompBlockS3TC> & cmap = comp_blocks[mipmap]; if (!cmap.has(key)) { InstanceGIProbeData::CompBlockS3TC k; k.offset=key; //use offset as counter first k.source_count=0; cmap[key]=k; } InstanceGIProbeData::CompBlockS3TC &k=cmap[key]; ERR_CONTINUE(k.source_count==16); k.sources[k.source_count++]=i; } //fix the blocks, precomputing what is needed probe->dynamic.mipmaps_s3tc.resize(mipmap_count); for(int i=0;i<mipmap_count;i++) { print_line("S3TC level: "+itos(i)+" blocks: "+itos(comp_blocks[i].size())); probe->dynamic.mipmaps_s3tc[i].resize(comp_blocks[i].size()); PoolVector<InstanceGIProbeData::CompBlockS3TC>::Write w = probe->dynamic.mipmaps_s3tc[i].write(); int block_idx=0; for (Map<uint32_t,InstanceGIProbeData::CompBlockS3TC>::Element *E=comp_blocks[i].front();E;E=E->next()) { InstanceGIProbeData::CompBlockS3TC k = E->get(); //PRECOMPUTE ALPHA int max_alpha=-100000; int min_alpha=k.source_count==16 ?100000 :0; //if the block is not completely full, minimum is always 0, (and those blocks will map to 1, which will be zero) uint8_t alpha_block[4][4]={ {0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0} }; for(int j=0;j<k.source_count;j++) { int alpha = (cells[k.sources[j]].level_alpha>>8)&0xFF; if (alpha<min_alpha) min_alpha=alpha; if (alpha>max_alpha) max_alpha=alpha; //fill up alpha block alpha_block[ldw[k.sources[j]].pos[0]%4][ldw[k.sources[j]].pos[1]%4]=alpha; } //use the first mode (8 adjustable levels) k.alpha[0]=max_alpha; k.alpha[1]=min_alpha; uint64_t alpha_bits=0; if (max_alpha!=min_alpha) { int idx=0; for(int y=0;y<4;y++) { for(int x=0;x<4;x++) { //substract minimum uint32_t a = uint32_t(alpha_block[x][y])-min_alpha; //convert range to 3 bits a =int((a * 7.0 / (max_alpha-min_alpha))+0.5); a = CLAMP(a,0,7); //just to be sure a = 7-a; //because range is inverted in this mode if (a==0) { //do none, remain } else if (a==7) { a=1; } else { a=a+1; } alpha_bits|=uint64_t(a)<<(idx*3); idx++; } } } k.alpha[2]=(alpha_bits >> 0)&0xFF; k.alpha[3]=(alpha_bits >> 8)&0xFF; k.alpha[4]=(alpha_bits >> 16)&0xFF; k.alpha[5]=(alpha_bits >> 24)&0xFF; k.alpha[6]=(alpha_bits >> 32)&0xFF; k.alpha[7]=(alpha_bits >> 40)&0xFF; w[block_idx++]=k; } } } } void VisualServerScene::_gi_probe_bake_thread() { while(true) { probe_bake_sem->wait(); if (probe_bake_thread_exit) { break; } Instance* to_bake=NULL; probe_bake_mutex->lock(); if (!probe_bake_list.empty()) { to_bake=probe_bake_list.front()->get(); probe_bake_list.pop_front(); } probe_bake_mutex->unlock(); if (!to_bake) continue; _bake_gi_probe(to_bake); } } uint32_t VisualServerScene::_gi_bake_find_cell(const GIProbeDataCell *cells,int x,int y, int z,int p_cell_subdiv) { uint32_t cell=0; int ofs_x=0; int ofs_y=0; int ofs_z=0; int size = 1<<(p_cell_subdiv-1); int half=size/2; if (x<0 || x>=size) return -1; if (y<0 || y>=size) return -1; if (z<0 || z>=size) return -1; for(int i=0;i<p_cell_subdiv-1;i++) { const GIProbeDataCell *bc = &cells[cell]; int child = 0; if (x >= ofs_x + half) { child|=1; ofs_x+=half; } if (y >= ofs_y + half) { child|=2; ofs_y+=half; } if (z >= ofs_z + half) { child|=4; ofs_z+=half; } cell = bc->children[child]; if (cell==0xFFFFFFFF) return 0xFFFFFFFF; half>>=1; } return cell; } static float _get_normal_advance(const Vector3& p_normal ) { Vector3 normal = p_normal; Vector3 unorm = normal.abs(); if ( (unorm.x >= unorm.y) && (unorm.x >= unorm.z) ) { // x code unorm = normal.x > 0.0 ? Vector3( 1.0, 0.0, 0.0 ) : Vector3( -1.0, 0.0, 0.0 ) ; } else if ( (unorm.y > unorm.x) && (unorm.y >= unorm.z) ) { // y code unorm = normal.y > 0.0 ? Vector3( 0.0, 1.0, 0.0 ) : Vector3( 0.0, -1.0, 0.0 ) ; } else if ( (unorm.z > unorm.x) && (unorm.z > unorm.y) ) { // z code unorm = normal.z > 0.0 ? Vector3( 0.0, 0.0, 1.0 ) : Vector3( 0.0, 0.0, -1.0 ) ; } else { // oh-no we messed up code // has to be unorm = Vector3( 1.0, 0.0, 0.0 ); } return 1.0/normal.dot(unorm); } void VisualServerScene::_bake_gi_probe_light(const GIProbeDataHeader *header,const GIProbeDataCell *cells,InstanceGIProbeData::LocalData *local_data,const uint32_t *leaves,int leaf_count, const InstanceGIProbeData::LightCache& light_cache,int sign) { int light_r = int(light_cache.color.r * light_cache.energy * 1024.0)*sign; int light_g = int(light_cache.color.g * light_cache.energy * 1024.0)*sign; int light_b = int(light_cache.color.b * light_cache.energy * 1024.0)*sign; float limits[3]={float(header->width),float(header->height),float(header->depth)}; Plane clip[3]; int clip_planes=0; switch(light_cache.type) { case VS::LIGHT_DIRECTIONAL: { float max_len = Vector3(limits[0],limits[1],limits[2]).length()*1.1; Vector3 light_axis = -light_cache.transform.basis.get_axis(2).normalized(); for(int i=0;i<3;i++) { if (ABS(light_axis[i])<CMP_EPSILON) continue; clip[clip_planes].normal[i]=1.0; if (light_axis[i]<0) { clip[clip_planes].d=limits[i]+1; } else { clip[clip_planes].d-=1.0; } clip_planes++; } float distance_adv = _get_normal_advance(light_axis); int success_count=0; uint64_t us = OS::get_singleton()->get_ticks_usec(); for(int i=0;i<leaf_count;i++) { uint32_t idx = leaves[i]; const GIProbeDataCell *cell = &cells[idx]; InstanceGIProbeData::LocalData *light = &local_data[idx]; Vector3 to(light->pos[0]+0.5,light->pos[1]+0.5,light->pos[2]+0.5); Vector3 norm ( (((cells[idx].normal>>16)&0xFF)/255.0)*2.0-1.0, (((cells[idx].normal>>8)&0xFF)/255.0)*2.0-1.0, (((cells[idx].normal>>0)&0xFF)/255.0)*2.0-1.0 ); float att = norm.dot(-light_axis); if (att<0.001) { //not lighting towards this continue; } Vector3 from = to - max_len * light_axis; for(int j=0;j<clip_planes;j++) { clip[j].intersects_segment(from,to,&from); } float distance = (to - from).length(); distance+=distance_adv-Math::fmod(distance,distance_adv); //make it reach the center of the box always from = to - light_axis * distance; uint32_t result=0xFFFFFFFF; while(distance>-distance_adv) { //use this to avoid precision errors result = _gi_bake_find_cell(cells,int(floor(from.x)),int(floor(from.y)),int(floor(from.z)),header->cell_subdiv); if (result!=0xFFFFFFFF) { break; } from+=light_axis*distance_adv; distance-=distance_adv; } if (result==idx) { //cell hit itself! hooray! light->energy[0]+=int32_t(light_r*att*((cell->albedo>>16)&0xFF)/255.0); light->energy[1]+=int32_t(light_g*att*((cell->albedo>>8)&0xFF)/255.0); light->energy[2]+=int32_t(light_b*att*((cell->albedo)&0xFF)/255.0); success_count++; } } print_line("BAKE TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0)); print_line("valid cells: "+itos(success_count)); } break; case VS::LIGHT_OMNI: case VS::LIGHT_SPOT: { uint64_t us = OS::get_singleton()->get_ticks_usec(); Vector3 light_pos = light_cache.transform.origin; Vector3 spot_axis = -light_cache.transform.basis.get_axis(2).normalized(); float local_radius = light_cache.radius * light_cache.transform.basis.get_axis(2).length(); for(int i=0;i<leaf_count;i++) { uint32_t idx = leaves[i]; const GIProbeDataCell *cell = &cells[idx]; InstanceGIProbeData::LocalData *light = &local_data[idx]; Vector3 to(light->pos[0]+0.5,light->pos[1]+0.5,light->pos[2]+0.5); Vector3 norm ( (((cells[idx].normal>>16)&0xFF)/255.0)*2.0-1.0, (((cells[idx].normal>>8)&0xFF)/255.0)*2.0-1.0, (((cells[idx].normal>>0)&0xFF)/255.0)*2.0-1.0 ); Vector3 light_axis = (to - light_pos).normalized(); float distance_adv = _get_normal_advance(light_axis); float att = norm.dot(-light_axis); if (att<0.001) { //not lighting towards this continue; } { float d = light_pos.distance_to(to); if (d+distance_adv > local_radius) continue; // too far away float dt = CLAMP((d+distance_adv)/local_radius,0,1); att*= powf(1.0-dt,light_cache.attenuation); } if (light_cache.type==VS::LIGHT_SPOT) { float angle = Math::rad2deg(acos(light_axis.dot(spot_axis))); if (angle > light_cache.spot_angle) continue; float d = CLAMP(angle/light_cache.spot_angle,1,0); att*= powf(1.0-d,light_cache.spot_attenuation); } clip_planes=0; for(int c=0;c<3;c++) { if (ABS(light_axis[c])<CMP_EPSILON) continue; clip[clip_planes].normal[c]=1.0; if (light_axis[c]<0) { clip[clip_planes].d=limits[c]+1; } else { clip[clip_planes].d-=1.0; } clip_planes++; } Vector3 from = light_pos; for(int j=0;j<clip_planes;j++) { clip[j].intersects_segment(from,to,&from); } float distance = (to - from).length(); distance-=Math::fmod(distance,distance_adv); //make it reach the center of the box always, but this tame make it closer from = to - light_axis * distance; uint32_t result=0xFFFFFFFF; while(distance>-distance_adv) { //use this to avoid precision errors result = _gi_bake_find_cell(cells,int(floor(from.x)),int(floor(from.y)),int(floor(from.z)),header->cell_subdiv); if (result!=0xFFFFFFFF) { break; } from+=light_axis*distance_adv; distance-=distance_adv; } if (result==idx) { //cell hit itself! hooray! light->energy[0]+=int32_t(light_r*att*((cell->albedo>>16)&0xFF)/255.0); light->energy[1]+=int32_t(light_g*att*((cell->albedo>>8)&0xFF)/255.0); light->energy[2]+=int32_t(light_b*att*((cell->albedo)&0xFF)/255.0); } } print_line("BAKE TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0)); } break; } } void VisualServerScene::_bake_gi_downscale_light(int p_idx, int p_level, const GIProbeDataCell* p_cells, const GIProbeDataHeader *p_header, InstanceGIProbeData::LocalData *p_local_data) { //average light to upper level p_local_data[p_idx].energy[0]=0; p_local_data[p_idx].energy[1]=0; p_local_data[p_idx].energy[2]=0; int divisor=0; for(int i=0;i<8;i++) { uint32_t child = p_cells[p_idx].children[i]; if (child==0xFFFFFFFF) continue; if (p_level+1 < (int)p_header->cell_subdiv-1) { _bake_gi_downscale_light(child,p_level+1,p_cells,p_header,p_local_data); } p_local_data[p_idx].energy[0]+=p_local_data[child].energy[0]; p_local_data[p_idx].energy[1]+=p_local_data[child].energy[1]; p_local_data[p_idx].energy[2]+=p_local_data[child].energy[2]; divisor++; } //divide by eight for average p_local_data[p_idx].energy[0]/=divisor; p_local_data[p_idx].energy[1]/=divisor; p_local_data[p_idx].energy[2]/=divisor; } void VisualServerScene::_bake_gi_probe(Instance *p_gi_probe) { InstanceGIProbeData * probe_data = static_cast<InstanceGIProbeData*>(p_gi_probe->base_data); PoolVector<int>::Read r=probe_data->dynamic.light_data.read(); const GIProbeDataHeader *header = (const GIProbeDataHeader *)r.ptr(); const GIProbeDataCell *cells = (const GIProbeDataCell*)&r[16]; int leaf_count = probe_data->dynamic.level_cell_lists[ header->cell_subdiv -1 ].size(); const uint32_t *leaves = probe_data->dynamic.level_cell_lists[ header->cell_subdiv -1 ].ptr(); PoolVector<InstanceGIProbeData::LocalData>::Write ldw = probe_data->dynamic.local_data.write(); InstanceGIProbeData::LocalData *local_data = ldw.ptr(); //remove what must be removed for (Map<RID,InstanceGIProbeData::LightCache>::Element *E=probe_data->dynamic.light_cache.front();E;E=E->next()) { RID rid = E->key(); const InstanceGIProbeData::LightCache& lc = E->get(); if (!probe_data->dynamic.light_cache_changes.has(rid) || !(probe_data->dynamic.light_cache_changes[rid]==lc)) { //erase light data _bake_gi_probe_light(header,cells,local_data,leaves,leaf_count,lc,-1); } } //add what must be added for (Map<RID,InstanceGIProbeData::LightCache>::Element *E=probe_data->dynamic.light_cache_changes.front();E;E=E->next()) { RID rid = E->key(); const InstanceGIProbeData::LightCache& lc = E->get(); if (!probe_data->dynamic.light_cache.has(rid) || !(probe_data->dynamic.light_cache[rid]==lc)) { //add light data _bake_gi_probe_light(header,cells,local_data,leaves,leaf_count,lc,1); } } SWAP(probe_data->dynamic.light_cache_changes,probe_data->dynamic.light_cache); //downscale to lower res levels _bake_gi_downscale_light(0,0,cells,header,local_data); //plot result to 3D texture! if (probe_data->dynamic.compression==RasterizerStorage::GI_PROBE_UNCOMPRESSED) { for(int i=0;i<(int)header->cell_subdiv;i++) { int stage = header->cell_subdiv - i -1; if (stage >= probe_data->dynamic.mipmaps_3d.size()) continue; //no mipmap for this one print_line("generating mipmap stage: "+itos(stage)); int level_cell_count = probe_data->dynamic.level_cell_lists[ i ].size(); const uint32_t *level_cells = probe_data->dynamic.level_cell_lists[ i ].ptr(); PoolVector<uint8_t>::Write lw = probe_data->dynamic.mipmaps_3d[stage].write(); uint8_t *mipmapw = lw.ptr(); uint32_t sizes[3]={header->width>>stage,header->height>>stage,header->depth>>stage}; for(int j=0;j<level_cell_count;j++) { uint32_t idx = level_cells[j]; uint32_t r = (uint32_t(local_data[idx].energy[0])/probe_data->dynamic.bake_dynamic_range)>>2; uint32_t g = (uint32_t(local_data[idx].energy[1])/probe_data->dynamic.bake_dynamic_range)>>2; uint32_t b = (uint32_t(local_data[idx].energy[2])/probe_data->dynamic.bake_dynamic_range)>>2; uint32_t a = (cells[idx].level_alpha>>8)&0xFF; uint32_t mm_ofs = sizes[0]*sizes[1]*(local_data[idx].pos[2]) + sizes[0]*(local_data[idx].pos[1]) + (local_data[idx].pos[0]); mm_ofs*=4; //for RGBA (4 bytes) mipmapw[mm_ofs+0]=uint8_t(CLAMP(r,0,255)); mipmapw[mm_ofs+1]=uint8_t(CLAMP(g,0,255)); mipmapw[mm_ofs+2]=uint8_t(CLAMP(b,0,255)); mipmapw[mm_ofs+3]=uint8_t(CLAMP(a,0,255)); } } } else if (probe_data->dynamic.compression==RasterizerStorage::GI_PROBE_S3TC) { int mipmap_count = probe_data->dynamic.mipmaps_3d.size(); for(int mmi=0;mmi<mipmap_count;mmi++) { PoolVector<uint8_t>::Write mmw = probe_data->dynamic.mipmaps_3d[mmi].write(); int block_count = probe_data->dynamic.mipmaps_s3tc[mmi].size(); PoolVector<InstanceGIProbeData::CompBlockS3TC>::Read mmr = probe_data->dynamic.mipmaps_s3tc[mmi].read(); for(int i=0;i<block_count;i++) { const InstanceGIProbeData::CompBlockS3TC& b = mmr[i]; uint8_t *blockptr = &mmw[b.offset*16]; copymem(blockptr,b.alpha,8); //copy alpha part, which is precomputed Vector3 colors[16]; for(int j=0;j<b.source_count;j++) { colors[j].x=(local_data[b.sources[j]].energy[0]/float(probe_data->dynamic.bake_dynamic_range))/1024.0; colors[j].y=(local_data[b.sources[j]].energy[1]/float(probe_data->dynamic.bake_dynamic_range))/1024.0; colors[j].z=(local_data[b.sources[j]].energy[2]/float(probe_data->dynamic.bake_dynamic_range))/1024.0; } //super quick and dirty compression //find 2 most futher apart float distance=0; Vector3 from,to; if (b.source_count==16) { //all cells are used so, find minmax between them int further_apart[2]={0,0}; for(int j=0;j<b.source_count;j++) { for(int k=j+1;k<b.source_count;k++) { float d = colors[j].distance_squared_to(colors[k]); if (d>distance) { distance=d; further_apart[0]=j; further_apart[1]=k; } } } from = colors[further_apart[0]]; to = colors[further_apart[1]]; } else { //if a block is missing, the priority is that this block remains black, //otherwise the geometry will appear deformed //correct shape wins over correct color in this case //average all colors first Vector3 average; for(int j=0;j<b.source_count;j++) { average+=colors[j]; } average.normalize(); //find max distance in normal from average for(int j=0;j<b.source_count;j++) { float d = average.dot(colors[j]); distance=MAX(d,distance); } from = Vector3(); //from black to = average * distance; //find max distance } int indices[16]; uint16_t color_0=0; color_0 = CLAMP(int(from.x*31),0,31)<<11; color_0 |= CLAMP(int(from.y*63),0,63)<<5; color_0 |= CLAMP(int(from.z*31),0,31); uint16_t color_1=0; color_1 = CLAMP(int(to.x*31),0,31)<<11; color_1 |= CLAMP(int(to.y*63),0,63)<<5; color_1 |= CLAMP(int(to.z*31),0,31); if (color_1 > color_0) { SWAP(color_1,color_0); SWAP(from,to); } if (distance>0) { Vector3 dir = (to-from).normalized(); for(int j=0;j<b.source_count;j++) { float d = (colors[j]-from).dot(dir) / distance; indices[j]=int(d*3+0.5); static const int index_swap[4]={0,3,1,2}; indices[j]=index_swap[CLAMP(indices[j],0,3)]; } } else { for(int j=0;j<b.source_count;j++) { indices[j]=0; } } //by default, 1 is black, otherwise it will be overriden by source uint32_t index_block[16]={1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1 }; for(int j=0;j<b.source_count;j++) { int x=local_data[b.sources[j]].pos[0]%4; int y=local_data[b.sources[j]].pos[1]%4; index_block[y*4+x]=indices[j]; } uint32_t encode=0; for(int j=0;j<16;j++) { encode|=index_block[j]<<(j*2); } blockptr[8]=color_0&0xFF; blockptr[9]=(color_0>>8)&0xFF; blockptr[10]=color_1&0xFF; blockptr[11]=(color_1>>8)&0xFF; blockptr[12]=encode&0xFF; blockptr[13]=(encode>>8)&0xFF; blockptr[14]=(encode>>16)&0xFF; blockptr[15]=(encode>>24)&0xFF; } } } //send back to main thread to update un little chunks probe_data->dynamic.updating_stage=GI_UPDATE_STAGE_UPLOADING; } bool VisualServerScene::_check_gi_probe(Instance *p_gi_probe) { InstanceGIProbeData * probe_data = static_cast<InstanceGIProbeData*>(p_gi_probe->base_data); probe_data->dynamic.light_cache_changes.clear(); bool all_equal=true; for (List<Instance*>::Element *E=p_gi_probe->scenario->directional_lights.front();E;E=E->next()) { InstanceGIProbeData::LightCache lc; lc.type=VSG::storage->light_get_type(E->get()->base); lc.color=VSG::storage->light_get_color(E->get()->base); lc.energy=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ENERGY); lc.radius=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_RANGE); lc.attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ATTENUATION); lc.spot_angle=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ANGLE); lc.spot_attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ATTENUATION); lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform; if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self]==lc)) { all_equal=false; } probe_data->dynamic.light_cache_changes[E->get()->self]=lc; } for (Set<Instance*>::Element *E=probe_data->lights.front();E;E=E->next()) { InstanceGIProbeData::LightCache lc; lc.type=VSG::storage->light_get_type(E->get()->base); lc.color=VSG::storage->light_get_color(E->get()->base); lc.energy=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ENERGY); lc.radius=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_RANGE); lc.attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_ATTENUATION); lc.spot_angle=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ANGLE); lc.spot_attenuation=VSG::storage->light_get_param(E->get()->base,VS::LIGHT_PARAM_SPOT_ATTENUATION); lc.transform = probe_data->dynamic.light_to_cell_xform * E->get()->transform; if (!probe_data->dynamic.light_cache.has(E->get()->self) || !(probe_data->dynamic.light_cache[E->get()->self]==lc)) { all_equal=false; } probe_data->dynamic.light_cache_changes[E->get()->self]=lc; } //lighting changed from after to before, must do some updating return !all_equal || probe_data->dynamic.light_cache_changes.size()!=probe_data->dynamic.light_cache.size(); } void VisualServerScene::render_probes() { /* REFLECTION PROBES */ SelfList<InstanceReflectionProbeData> *ref_probe = reflection_probe_render_list.first(); bool busy=false; while(ref_probe) { SelfList<InstanceReflectionProbeData> *next=ref_probe->next(); RID base = ref_probe->self()->owner->base; switch(VSG::storage->reflection_probe_get_update_mode(base)) { case VS::REFLECTION_PROBE_UPDATE_ONCE: { if (busy) //already rendering something break; bool done = _render_reflection_probe_step(ref_probe->self()->owner,ref_probe->self()->render_step); if (done) { reflection_probe_render_list.remove(ref_probe); } else { ref_probe->self()->render_step++; } busy=true; //do not render another one of this kind } break; case VS::REFLECTION_PROBE_UPDATE_ALWAYS: { int step=0; bool done=false; while(!done) { done = _render_reflection_probe_step(ref_probe->self()->owner,step); step++; } reflection_probe_render_list.remove(ref_probe); } break; } ref_probe=next; } /* GI PROBES */ SelfList<InstanceGIProbeData> *gi_probe = gi_probe_update_list.first(); while(gi_probe) { SelfList<InstanceGIProbeData> *next=gi_probe->next(); InstanceGIProbeData *probe = gi_probe->self(); Instance *instance_probe = probe->owner; //check if probe must be setup, but don't do if on the lighting thread bool force_lighting=false; if (probe->invalid || (probe->dynamic.updating_stage==GI_UPDATE_STAGE_CHECK && probe->base_version!=VSG::storage->gi_probe_get_version(instance_probe->base))) { _setup_gi_probe(instance_probe); force_lighting=true; } if (probe->invalid==false && probe->dynamic.enabled) { switch(probe->dynamic.updating_stage) { case GI_UPDATE_STAGE_CHECK: { if (_check_gi_probe(instance_probe) || force_lighting) { //send to lighting thread probe->dynamic.updating_stage=GI_UPDATE_STAGE_LIGHTING; #ifndef NO_THREADS probe_bake_mutex->lock(); probe_bake_list.push_back(instance_probe); probe_bake_mutex->unlock(); probe_bake_sem->post(); #else _bake_gi_probe(instance_probe); #endif } } break; case GI_UPDATE_STAGE_LIGHTING: { //do none, wait til done! } break; case GI_UPDATE_STAGE_UPLOADING: { uint64_t us = OS::get_singleton()->get_ticks_usec(); for(int i=0;i<(int)probe->dynamic.mipmaps_3d.size();i++) { int mmsize = probe->dynamic.mipmaps_3d[i].size(); PoolVector<uint8_t>::Read r = probe->dynamic.mipmaps_3d[i].read(); VSG::storage->gi_probe_dynamic_data_update(probe->dynamic.probe_data,0,probe->dynamic.grid_size[2]>>i,i,r.ptr()); } probe->dynamic.updating_stage=GI_UPDATE_STAGE_CHECK; //print_line("UPLOAD TIME: "+rtos((OS::get_singleton()->get_ticks_usec()-us)/1000000.0)); } break; } } //_update_gi_probe(gi_probe->self()->owner); gi_probe=next; } } void VisualServerScene::_update_dirty_instance(Instance *p_instance) { if (p_instance->update_aabb) _update_instance_aabb(p_instance); if (p_instance->update_materials) { if (p_instance->base_type==VS::INSTANCE_MESH) { //remove materials no longer used and un-own them int new_mat_count = VSG::storage->mesh_get_surface_count(p_instance->base); for(int i=p_instance->materials.size()-1;i>=new_mat_count;i--) { if (p_instance->materials[i].is_valid()) { VSG::storage->material_remove_instance_owner(p_instance->materials[i],p_instance); } } p_instance->materials.resize(new_mat_count); int new_blend_shape_count = VSG::storage->mesh_get_blend_shape_count(p_instance->base); if (new_blend_shape_count!=p_instance->blend_values.size()) { p_instance->blend_values.resize(new_blend_shape_count); for(int i=0;i<new_blend_shape_count;i++) { p_instance->blend_values[i]=0; } } } if ((1<<p_instance->base_type)&VS::INSTANCE_GEOMETRY_MASK) { InstanceGeometryData *geom = static_cast<InstanceGeometryData*>(p_instance->base_data); bool can_cast_shadows=true; if (p_instance->cast_shadows==VS::SHADOW_CASTING_SETTING_OFF) { can_cast_shadows=false; } else if (p_instance->material_override.is_valid()) { can_cast_shadows=VSG::storage->material_casts_shadows(p_instance->material_override); } else { if (p_instance->base_type==VS::INSTANCE_MESH) { RID mesh=p_instance->base; if (mesh.is_valid()) { bool cast_shadows=false; for(int i=0;i<p_instance->materials.size();i++) { RID mat = p_instance->materials[i].is_valid()?p_instance->materials[i]:VSG::storage->mesh_surface_get_material(mesh,i); if (!mat.is_valid()) { cast_shadows=true; break; } if (VSG::storage->material_casts_shadows(mat)) { cast_shadows=true; break; } } if (!cast_shadows) { can_cast_shadows=false; } } } else if (p_instance->base_type==VS::INSTANCE_MULTIMESH) { RID mesh = VSG::storage->multimesh_get_mesh(p_instance->base); if (mesh.is_valid()) { bool cast_shadows=false; int sc = VSG::storage->mesh_get_surface_count(mesh); for(int i=0;i<sc;i++) { RID mat =VSG::storage->mesh_surface_get_material(mesh,i); if (!mat.is_valid()) { cast_shadows=true; break; } if (VSG::storage->material_casts_shadows(mat)) { cast_shadows=true; break; } } if (!cast_shadows) { can_cast_shadows=false; } } } else if (p_instance->base_type==VS::INSTANCE_IMMEDIATE) { RID mat = VSG::storage->immediate_get_material(p_instance->base); if (!mat.is_valid() || VSG::storage->material_casts_shadows(mat)) { can_cast_shadows=true; } else { can_cast_shadows=false; } } } if (can_cast_shadows!=geom->can_cast_shadows) { //ability to cast shadows change, let lights now for (List<Instance*>::Element *E=geom->lighting.front();E;E=E->next()) { InstanceLightData *light = static_cast<InstanceLightData*>(E->get()->base_data); light->shadow_dirty=true; } geom->can_cast_shadows=can_cast_shadows; } } } _update_instance(p_instance); p_instance->update_aabb=false; p_instance->update_materials=false; _instance_update_list.remove( &p_instance->update_item ); } void VisualServerScene::update_dirty_instances() { while(_instance_update_list.first()) { _update_dirty_instance( _instance_update_list.first()->self() ); } } bool VisualServerScene::free(RID p_rid) { if (camera_owner.owns(p_rid)) { Camera *camera = camera_owner.get( p_rid ); camera_owner.free(p_rid); memdelete(camera); } else if (scenario_owner.owns(p_rid)) { Scenario *scenario = scenario_owner.get( p_rid ); while(scenario->instances.first()) { instance_set_scenario(scenario->instances.first()->self()->self,RID()); } VSG::scene_render->free(scenario->reflection_probe_shadow_atlas); VSG::scene_render->free(scenario->reflection_atlas); scenario_owner.free(p_rid); memdelete(scenario); } else if (instance_owner.owns(p_rid)) { // delete the instance update_dirty_instances(); Instance *instance = instance_owner.get(p_rid); instance_set_room(p_rid,RID()); instance_set_scenario(p_rid,RID()); instance_set_base(p_rid,RID()); instance_geometry_set_material_override(p_rid,RID()); instance_attach_skeleton(p_rid,RID()); update_dirty_instances(); //in case something changed this instance_owner.free(p_rid); memdelete(instance); } else { return false; } return true; } VisualServerScene *VisualServerScene::singleton=NULL; VisualServerScene::VisualServerScene() { #ifndef NO_THREADS probe_bake_sem = Semaphore::create(); probe_bake_mutex = Mutex::create(); probe_bake_thread = Thread::create(_gi_probe_bake_threads,this); probe_bake_thread_exit=false; #endif render_pass=1; singleton=this; } VisualServerScene::~VisualServerScene() { #ifndef NO_THREADS probe_bake_thread_exit=true; Thread::wait_to_finish(probe_bake_thread); memdelete(probe_bake_thread); memdelete(probe_bake_sem); memdelete(probe_bake_mutex); #endif }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
main/tests/test_shader_lang.cpp
361
/*************************************************************************/ /* test_shader_lang.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "test_shader_lang.h" #include "os/main_loop.h" #include "os/os.h" #include "os/file_access.h" #include "scene/gui/control.h" #include "scene/gui/text_edit.h" #include "print_string.h" #include "servers/visual/shader_language.h" //#include "drivers/gles2/shader_compiler_gles2.h" typedef ShaderLanguage SL; namespace TestShaderLang { static String _mktab(int p_level) { String tb; for(int i=0;i<p_level;i++) { tb+="\t"; } return tb; } static String _typestr(SL::DataType p_type) { return ShaderLanguage::get_datatype_name(p_type); return ""; } static String _prestr(SL::DataPrecision p_pres) { switch(p_pres) { case SL::PRECISION_LOWP: return "lowp "; case SL::PRECISION_MEDIUMP: return "mediump "; case SL::PRECISION_HIGHP: return "highp "; case SL::PRECISION_DEFAULT: return ""; } return ""; } static String _opstr(SL::Operator p_op) { return ShaderLanguage::get_operator_text(p_op); } static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value>& p_values) { switch(p_type) { case SL::TYPE_BOOL: return p_values[0].boolean?"true":"false"; case SL::TYPE_BVEC2: return String()+"bvec2("+(p_values[0].boolean?"true":"false")+(p_values[1].boolean?"true":"false")+")"; case SL::TYPE_BVEC3: return String()+"bvec3("+(p_values[0].boolean?"true":"false")+","+(p_values[1].boolean?"true":"false")+","+(p_values[2].boolean?"true":"false")+")"; case SL::TYPE_BVEC4: return String()+"bvec4("+(p_values[0].boolean?"true":"false")+","+(p_values[1].boolean?"true":"false")+","+(p_values[2].boolean?"true":"false")+","+(p_values[3].boolean?"true":"false")+")"; case SL::TYPE_INT: return rtos(p_values[0].sint); case SL::TYPE_IVEC2: return String()+"ivec2("+rtos(p_values[0].sint)+","+rtos(p_values[1].sint)+")"; case SL::TYPE_IVEC3: return String()+"ivec3("+rtos(p_values[0].sint)+","+rtos(p_values[1].sint)+","+rtos(p_values[2].sint)+")"; case SL::TYPE_IVEC4: return String()+"ivec4("+rtos(p_values[0].sint)+","+rtos(p_values[1].sint)+","+rtos(p_values[2].sint)+","+rtos(p_values[3].sint)+")"; case SL::TYPE_UINT: return rtos(p_values[0].real); case SL::TYPE_UVEC2: return String()+"uvec2("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+")"; case SL::TYPE_UVEC3: return String()+"uvec3("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+","+rtos(p_values[2].real)+")"; case SL::TYPE_UVEC4: return String()+"uvec4("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+","+rtos(p_values[2].real)+","+rtos(p_values[3].real)+")"; case SL::TYPE_FLOAT: return rtos(p_values[0].real); case SL::TYPE_VEC2: return String()+"vec2("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+")"; case SL::TYPE_VEC3: return String()+"vec3("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+","+rtos(p_values[2].real)+")"; case SL::TYPE_VEC4: return String()+"vec4("+rtos(p_values[0].real)+","+rtos(p_values[1].real)+","+rtos(p_values[2].real)+","+rtos(p_values[3].real)+")"; default: ERR_FAIL_V(String()); } } static String dump_node_code(SL::Node *p_node,int p_level) { String code; switch(p_node->type) { case SL::Node::TYPE_SHADER: { SL::ShaderNode *pnode=(SL::ShaderNode*)p_node; for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) { String ucode="uniform "; ucode+=_prestr(E->get().precission); ucode+=_typestr(E->get().type); ucode+=" "+String(E->key()); if (E->get().default_value.size()) { ucode+=" = "+get_constant_text(E->get().type,E->get().default_value); } static const char*hint_name[SL::ShaderNode::Uniform::HINT_MAX]={ "", "color", "range", "albedo", "normal", "black", "white" }; if (E->get().hint) ucode+=" : "+String(hint_name[E->get().hint]); code+=ucode+"\n"; } for(Map<StringName,SL::ShaderNode::Varying>::Element *E=pnode->varyings.front();E;E=E->next()) { String vcode="varying "; vcode+=_prestr(E->get().precission); vcode+=_typestr(E->get().type); vcode+=" "+String(E->key()); code+=vcode+"\n"; } for(int i=0;i<pnode->functions.size();i++) { SL::FunctionNode *fnode=pnode->functions[i].function; String header; header=_typestr(fnode->return_type)+" "+fnode->name+"("; for(int i=0;i<fnode->arguments.size();i++) { if (i>0) header+=", "; header+=_prestr(fnode->arguments[i].precision)+_typestr(fnode->arguments[i].type)+" "+fnode->arguments[i].name; } header+=")\n"; code+=header; code+=dump_node_code(fnode->body,p_level+1); } //code+=dump_node_code(pnode->body,p_level); } break; case SL::Node::TYPE_FUNCTION: { } break; case SL::Node::TYPE_BLOCK: { SL::BlockNode *bnode=(SL::BlockNode*)p_node; //variables code+=_mktab(p_level-1)+"{\n"; for(Map<StringName,SL::BlockNode::Variable>::Element *E=bnode->variables.front();E;E=E->next()) { code+=_mktab(p_level)+_prestr(E->get().precision)+_typestr(E->get().type)+" "+E->key()+";\n"; } for(int i=0;i<bnode->statements.size();i++) { String scode = dump_node_code(bnode->statements[i],p_level); if (bnode->statements[i]->type==SL::Node::TYPE_CONTROL_FLOW || bnode->statements[i]->type==SL::Node::TYPE_CONTROL_FLOW) { code+=scode; //use directly } else { code+=_mktab(p_level)+scode+";\n"; } } code+=_mktab(p_level-1)+"}\n"; } break; case SL::Node::TYPE_VARIABLE: { SL::VariableNode *vnode=(SL::VariableNode*)p_node; code=vnode->name; } break; case SL::Node::TYPE_CONSTANT: { SL::ConstantNode *cnode=(SL::ConstantNode*)p_node; return get_constant_text(cnode->datatype,cnode->values); } break; case SL::Node::TYPE_OPERATOR: { SL::OperatorNode *onode=(SL::OperatorNode*)p_node; switch(onode->op) { case SL::OP_ASSIGN: case SL::OP_ASSIGN_ADD: case SL::OP_ASSIGN_SUB: case SL::OP_ASSIGN_MUL: case SL::OP_ASSIGN_DIV: case SL::OP_ASSIGN_SHIFT_LEFT: case SL::OP_ASSIGN_SHIFT_RIGHT: case SL::OP_ASSIGN_MOD: case SL::OP_ASSIGN_BIT_AND: case SL::OP_ASSIGN_BIT_OR: case SL::OP_ASSIGN_BIT_XOR: code=dump_node_code(onode->arguments[0],p_level)+_opstr(onode->op)+dump_node_code(onode->arguments[1],p_level); break; case SL::OP_BIT_INVERT: case SL::OP_NEGATE: case SL::OP_NOT: case SL::OP_DECREMENT: case SL::OP_INCREMENT: code=_opstr(onode->op)+dump_node_code(onode->arguments[0],p_level); break; case SL::OP_POST_DECREMENT: case SL::OP_POST_INCREMENT: code=dump_node_code(onode->arguments[0],p_level)+_opstr(onode->op); break; case SL::OP_CALL: case SL::OP_CONSTRUCT: code=dump_node_code(onode->arguments[0],p_level)+"("; for(int i=1;i<onode->arguments.size();i++) { if (i>1) code+=", "; code+=dump_node_code(onode->arguments[i],p_level); } code+=")"; break; default: { code="("+dump_node_code(onode->arguments[0],p_level)+_opstr(onode->op)+dump_node_code(onode->arguments[1],p_level)+")"; break; } } } break; case SL::Node::TYPE_CONTROL_FLOW: { SL::ControlFlowNode *cfnode=(SL::ControlFlowNode*)p_node; if (cfnode->flow_op==SL::FLOW_OP_IF) { code+=_mktab(p_level)+"if ("+dump_node_code(cfnode->expressions[0],p_level)+")\n"; code+=dump_node_code(cfnode->blocks[0],p_level+1); if (cfnode->blocks.size()==2) { code+=_mktab(p_level)+"else\n"; code+=dump_node_code(cfnode->blocks[1],p_level+1); } } else if (cfnode->flow_op==SL::FLOW_OP_RETURN) { if (cfnode->blocks.size()) { code="return "+dump_node_code(cfnode->blocks[0],p_level); } else { code="return"; } } } break; case SL::Node::TYPE_MEMBER: { SL::MemberNode *mnode=(SL::MemberNode*)p_node; code=dump_node_code(mnode->owner,p_level)+"."+mnode->name; } break; } return code; } static Error recreate_code(void *p_str,SL::ShaderNode *p_program) { String *str=(String*)p_str; *str=dump_node_code(p_program,0); return OK; } MainLoop* test() { List<String> cmdlargs = OS::get_singleton()->get_cmdline_args(); if (cmdlargs.empty()) { //try editor! print_line("usage: godot -test shader_lang <shader>"); return NULL; } String test = cmdlargs.back()->get(); FileAccess *fa = FileAccess::open(test,FileAccess::READ); if (!fa) { ERR_FAIL_V(NULL); } String code; while(true) { CharType c = fa->get_8(); if (fa->eof_reached()) break; code+=c; } SL sl; print_line("tokens:\n\n"+sl.token_debug(code)); Map<StringName,Map<StringName,SL::DataType> > dt; dt["fragment"]["ALBEDO"]=SL::TYPE_VEC3; Set<String> rm; rm.insert("popo"); Error err = sl.compile(code,dt,rm); if (err) { print_line("Error at line: "+rtos(sl.get_error_line())+": "+sl.get_error_text()); return NULL; } else { String code; recreate_code(&code,sl.get_shader()); print_line("code:\n\n"+code); } return NULL; } }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
thirdparty/stb_vorbis/stb_vorbis.c
5,399
// Ogg Vorbis audio decoder - v1.09 - public domain // http://nothings.org/stb_vorbis/ // // Original version written by Sean Barrett in 2007. // // Originally sponsored by RAD Game Tools. Seeking sponsored // by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software, // Aras Pranckevicius, and Sean Barrett. // // LICENSE // // This software is dual-licensed to the public domain and under the following // license: you are granted a perpetual, irrevocable license to copy, modify, // publish, and distribute this file as you see fit. // // No warranty for any purpose is expressed or implied by the author (nor // by RAD Game Tools). Report bugs and send enhancements to the author. // // Limitations: // // - floor 0 not supported (used in old ogg vorbis files pre-2004) // - lossless sample-truncation at beginning ignored // - cannot concatenate multiple vorbis streams // - sample positions are 32-bit, limiting seekable 192Khz // files to around 6 hours (Ogg supports 64-bit) // // Feature contributors: // Dougall Johnson (sample-exact seeking) // // Bugfix/warning contributors: // Terje Mathisen Niklas Frykholm Andy Hill // Casey Muratori John Bolton Gargaj // Laurent Gomila Marc LeBlanc Ronny Chevalier // Bernhard Wodo Evan Balster alxprd@github // Tom Beaumont Ingo Leitgeb Nicolas Guillemot // Phillip Bennefall Rohit Thiago Goulart // manxorist@github saga musix // // Partial history: // 1.09 - 2016/04/04 - back out 'truncation of last frame' fix from previous version // 1.08 - 2016/04/02 - warnings; setup memory leaks; truncation of last frame // 1.07 - 2015/01/16 - fixes for crashes on invalid files; warning fixes; const // 1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson) // some crash fixes when out of memory or with corrupt files // fix some inappropriately signed shifts // 1.05 - 2015/04/19 - don't define __forceinline if it's redundant // 1.04 - 2014/08/27 - fix missing const-correct case in API // 1.03 - 2014/08/07 - warning fixes // 1.02 - 2014/07/09 - declare qsort comparison as explicitly _cdecl in Windows // 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float (interleaved was correct) // 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in >2-channel; // (API change) report sample rate for decode-full-file funcs // // See end of file for full version history. ////////////////////////////////////////////////////////////////////////////// // // HEADER BEGINS HERE // #ifndef STB_VORBIS_INCLUDE_STB_VORBIS_H #define STB_VORBIS_INCLUDE_STB_VORBIS_H #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifdef __cplusplus extern "C" { #endif /////////// THREAD SAFETY // Individual stb_vorbis* handles are not thread-safe; you cannot decode from // them from multiple threads at the same time. However, you can have multiple // stb_vorbis* handles and decode from them independently in multiple thrads. /////////// MEMORY ALLOCATION // normally stb_vorbis uses malloc() to allocate memory at startup, // and alloca() to allocate temporary memory during a frame on the // stack. (Memory consumption will depend on the amount of setup // data in the file and how you set the compile flags for speed // vs. size. In my test files the maximal-size usage is ~150KB.) // // You can modify the wrapper functions in the source (setup_malloc, // setup_temp_malloc, temp_malloc) to change this behavior, or you // can use a simpler allocation model: you pass in a buffer from // which stb_vorbis will allocate _all_ its memory (including the // temp memory). "open" may fail with a VORBIS_outofmem if you // do not pass in enough data; there is no way to determine how // much you do need except to succeed (at which point you can // query get_info to find the exact amount required. yes I know // this is lame). // // If you pass in a non-NULL buffer of the type below, allocation // will occur from it as described above. Otherwise just pass NULL // to use malloc()/alloca() typedef struct { char *alloc_buffer; int alloc_buffer_length_in_bytes; } stb_vorbis_alloc; /////////// FUNCTIONS USEABLE WITH ALL INPUT MODES typedef struct stb_vorbis stb_vorbis; typedef struct { unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int setup_temp_memory_required; unsigned int temp_memory_required; int max_frame_size; } stb_vorbis_info; // get general information about the file extern stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f); // get the last error detected (clears it, too) extern int stb_vorbis_get_error(stb_vorbis *f); // close an ogg vorbis file and free all memory in use extern void stb_vorbis_close(stb_vorbis *f); // this function returns the offset (in samples) from the beginning of the // file that will be returned by the next decode, if it is known, or -1 // otherwise. after a flush_pushdata() call, this may take a while before // it becomes valid again. // NOT WORKING YET after a seek with PULLDATA API extern int stb_vorbis_get_sample_offset(stb_vorbis *f); // returns the current seek point within the file, or offset from the beginning // of the memory buffer. In pushdata mode it returns 0. extern unsigned int stb_vorbis_get_file_offset(stb_vorbis *f); /////////// PUSHDATA API #ifndef STB_VORBIS_NO_PUSHDATA_API // this API allows you to get blocks of data from any source and hand // them to stb_vorbis. you have to buffer them; stb_vorbis will tell // you how much it used, and you have to give it the rest next time; // and stb_vorbis may not have enough data to work with and you will // need to give it the same data again PLUS more. Note that the Vorbis // specification does not bound the size of an individual frame. extern stb_vorbis *stb_vorbis_open_pushdata( const unsigned char * datablock, int datablock_length_in_bytes, int *datablock_memory_consumed_in_bytes, int *error, const stb_vorbis_alloc *alloc_buffer); // create a vorbis decoder by passing in the initial data block containing // the ogg&vorbis headers (you don't need to do parse them, just provide // the first N bytes of the file--you're told if it's not enough, see below) // on success, returns an stb_vorbis *, does not set error, returns the amount of // data parsed/consumed on this call in *datablock_memory_consumed_in_bytes; // on failure, returns NULL on error and sets *error, does not change *datablock_memory_consumed // if returns NULL and *error is VORBIS_need_more_data, then the input block was // incomplete and you need to pass in a larger block from the start of the file extern int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, const unsigned char *datablock, int datablock_length_in_bytes, int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ); // decode a frame of audio sample data if possible from the passed-in data block // // return value: number of bytes we used from datablock // // possible cases: // 0 bytes used, 0 samples output (need more data) // N bytes used, 0 samples output (resynching the stream, keep going) // N bytes used, M samples output (one frame of data) // note that after opening a file, you will ALWAYS get one N-bytes,0-sample // frame, because Vorbis always "discards" the first frame. // // Note that on resynch, stb_vorbis will rarely consume all of the buffer, // instead only datablock_length_in_bytes-3 or less. This is because it wants // to avoid missing parts of a page header if they cross a datablock boundary, // without writing state-machiney code to record a partial detection. // // The number of channels returned are stored in *channels (which can be // NULL--it is always the same as the number of channels reported by // get_info). *output will contain an array of float* buffers, one per // channel. In other words, (*output)[0][0] contains the first sample from // the first channel, and (*output)[1][0] contains the first sample from // the second channel. extern void stb_vorbis_flush_pushdata(stb_vorbis *f); // inform stb_vorbis that your next datablock will not be contiguous with // previous ones (e.g. you've seeked in the data); future attempts to decode // frames will cause stb_vorbis to resynchronize (as noted above), and // once it sees a valid Ogg page (typically 4-8KB, as large as 64KB), it // will begin decoding the _next_ frame. // // if you want to seek using pushdata, you need to seek in your file, then // call stb_vorbis_flush_pushdata(), then start calling decoding, then once // decoding is returning you data, call stb_vorbis_get_sample_offset, and // if you don't like the result, seek your file again and repeat. #endif ////////// PULLING INPUT API #ifndef STB_VORBIS_NO_PULLDATA_API // This API assumes stb_vorbis is allowed to pull data from a source-- // either a block of memory containing the _entire_ vorbis stream, or a // FILE * that you or it create, or possibly some other reading mechanism // if you go modify the source to replace the FILE * case with some kind // of callback to your code. (But if you don't support seeking, you may // just want to go ahead and use pushdata.) #if !defined(STB_VORBIS_NO_STDIO) && !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output); #endif #if !defined(STB_VORBIS_NO_INTEGER_CONVERSION) extern int stb_vorbis_decode_memory(const unsigned char *mem, int len, int *channels, int *sample_rate, short **output); #endif // decode an entire file and output the data interleaved into a malloc()ed // buffer stored in *output. The return value is the number of samples // decoded, or -1 if the file could not be opened or was not an ogg vorbis file. // When you're done with it, just free() the pointer returned in *output. extern stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an ogg vorbis stream in memory (note // this must be the entire stream!). on failure, returns NULL and sets *error #ifndef STB_VORBIS_NO_STDIO extern stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from a filename via fopen(). on failure, // returns NULL and sets *error (possibly to VORBIS_file_open_failure). extern stb_vorbis * stb_vorbis_open_file(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell). on failure, returns NULL and sets *error. // note that stb_vorbis must "own" this stream; if you seek it in between // calls to stb_vorbis, it will become confused. Morever, if you attempt to // perform stb_vorbis_seek_*() operations on this file, it will assume it // owns the _entire_ rest of the file after the start point. Use the next // function, stb_vorbis_open_file_section(), to limit it. extern stb_vorbis * stb_vorbis_open_file_section(FILE *f, int close_handle_on_close, int *error, const stb_vorbis_alloc *alloc_buffer, unsigned int len); // create an ogg vorbis decoder from an open FILE *, looking for a stream at // the _current_ seek point (ftell); the stream will be of length 'len' bytes. // on failure, returns NULL and sets *error. note that stb_vorbis must "own" // this stream; if you seek it in between calls to stb_vorbis, it will become // confused. #endif extern int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number); extern int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number); // these functions seek in the Vorbis file to (approximately) 'sample_number'. // after calling seek_frame(), the next call to get_frame_*() will include // the specified sample. after calling stb_vorbis_seek(), the next call to // stb_vorbis_get_samples_* will start with the specified sample. If you // do not need to seek to EXACTLY the target sample when using get_samples_*, // you can also use seek_frame(). extern void stb_vorbis_seek_start(stb_vorbis *f); // this function is equivalent to stb_vorbis_seek(f,0) extern unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f); extern float stb_vorbis_stream_length_in_seconds(stb_vorbis *f); // these functions return the total length of the vorbis stream extern int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output); // decode the next frame and return the number of samples. the number of // channels returned are stored in *channels (which can be NULL--it is always // the same as the number of channels reported by get_info). *output will // contain an array of float* buffers, one per channel. These outputs will // be overwritten on the next call to stb_vorbis_get_frame_*. // // You generally should not intermix calls to stb_vorbis_get_frame_*() // and stb_vorbis_get_samples_*(), since the latter calls the former. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts); extern int stb_vorbis_get_frame_short (stb_vorbis *f, int num_c, short **buffer, int num_samples); #endif // decode the next frame and return the number of *samples* per channel. // Note that for interleaved data, you pass in the number of shorts (the // size of your array), but the return value is the number of samples per // channel, not the total number of samples. // // The data is coerced to the number of channels you request according to the // channel coercion rules (see below). You must pass in the size of your // buffer(s) so that stb_vorbis will not overwrite the end of the buffer. // The maximum buffer size needed can be gotten from get_info(); however, // the Vorbis I specification implies an absolute maximum of 4096 samples // per channel. // Channel coercion rules: // Let M be the number of channels requested, and N the number of channels present, // and Cn be the nth channel; let stereo L be the sum of all L and center channels, // and stereo R be the sum of all R and center channels (channel assignment from the // vorbis spec). // M N output // 1 k sum(Ck) for all k // 2 * stereo L, stereo R // k l k > l, the first l channels, then 0s // k l k <= l, the first k channels // Note that this is not _good_ surround etc. mixing at all! It's just so // you get something useful. extern int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats); extern int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples); // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. DOES NOT APPLY THE COERCION RULES. // Returns the number of samples stored per channel; it may be less than requested // at the end of the file. If there are no more samples in the file, returns 0. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION extern int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts); extern int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int num_samples); #endif // gets num_samples samples, not necessarily on a frame boundary--this requires // buffering so you have to supply the buffers. Applies the coercion rules above // to produce 'channels' channels. Returns the number of samples stored per channel; // it may be less than requested at the end of the file. If there are no more // samples in the file, returns 0. #endif //////// ERROR CODES enum STBVorbisError { VORBIS__no_error, VORBIS_need_more_data=1, // not a real error VORBIS_invalid_api_mixing, // can't mix API modes VORBIS_outofmem, // not enough memory VORBIS_feature_not_supported, // uses floor 0 VORBIS_too_many_channels, // STB_VORBIS_MAX_CHANNELS is too small VORBIS_file_open_failure, // fopen() failed VORBIS_seek_without_length, // can't seek in unknown-length file VORBIS_unexpected_eof=10, // file is truncated? VORBIS_seek_invalid, // seek past EOF // decoding errors (corrupt/invalid stream) -- you probably // don't care about the exact details of these // vorbis errors: VORBIS_invalid_setup=20, VORBIS_invalid_stream, // ogg errors: VORBIS_missing_capture_pattern=30, VORBIS_invalid_stream_structure_version, VORBIS_continued_packet_flag_invalid, VORBIS_incorrect_stream_serial_number, VORBIS_invalid_first_page, VORBIS_bad_packet_type, VORBIS_cant_find_last_page, VORBIS_seek_failed }; #ifdef __cplusplus } #endif #endif // STB_VORBIS_INCLUDE_STB_VORBIS_H // // HEADER ENDS HERE // ////////////////////////////////////////////////////////////////////////////// #ifndef STB_VORBIS_HEADER_ONLY // global configuration settings (e.g. set these in the project/makefile), // or just set them in this file at the top (although ideally the first few // should be visible when the header file is compiled too, although it's not // crucial) // STB_VORBIS_NO_PUSHDATA_API // does not compile the code for the various stb_vorbis_*_pushdata() // functions // #define STB_VORBIS_NO_PUSHDATA_API // STB_VORBIS_NO_PULLDATA_API // does not compile the code for the non-pushdata APIs // #define STB_VORBIS_NO_PULLDATA_API // STB_VORBIS_NO_STDIO // does not compile the code for the APIs that use FILE *s internally // or externally (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_STDIO // STB_VORBIS_NO_INTEGER_CONVERSION // does not compile the code for converting audio sample data from // float to integer (implied by STB_VORBIS_NO_PULLDATA_API) // #define STB_VORBIS_NO_INTEGER_CONVERSION // STB_VORBIS_NO_FAST_SCALED_FLOAT // does not use a fast float-to-int trick to accelerate float-to-int on // most platforms which requires endianness be defined correctly. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT // STB_VORBIS_MAX_CHANNELS [number] // globally define this to the maximum number of channels you need. // The spec does not put a restriction on channels except that // the count is stored in a byte, so 255 is the hard limit. // Reducing this saves about 16 bytes per value, so using 16 saves // (255-16)*16 or around 4KB. Plus anything other memory usage // I forgot to account for. Can probably go as low as 8 (7.1 audio), // 6 (5.1 audio), or 2 (stereo only). #ifndef STB_VORBIS_MAX_CHANNELS #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone? #endif // STB_VORBIS_PUSHDATA_CRC_COUNT [number] // after a flush_pushdata(), stb_vorbis begins scanning for the // next valid page, without backtracking. when it finds something // that looks like a page, it streams through it and verifies its // CRC32. Should that validation fail, it keeps scanning. But it's // possible that _while_ streaming through to check the CRC32 of // one candidate page, it sees another candidate page. This #define // determines how many "overlapping" candidate pages it can search // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas // garbage pages could be as big as 64KB, but probably average ~16KB. // So don't hose ourselves by scanning an apparent 64KB page and // missing a ton of real ones in the interim; so minimum of 2 #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT #define STB_VORBIS_PUSHDATA_CRC_COUNT 4 #endif // STB_VORBIS_FAST_HUFFMAN_LENGTH [number] // sets the log size of the huffman-acceleration table. Maximum // supported value is 24. with larger numbers, more decodings are O(1), // but the table size is larger so worse cache missing, so you'll have // to probe (and try multiple ogg vorbis files) to find the sweet spot. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10 #endif // STB_VORBIS_FAST_BINARY_LENGTH [number] // sets the log size of the binary-search acceleration table. this // is used in similar fashion to the fast-huffman size to set initial // parameters for the binary search // STB_VORBIS_FAST_HUFFMAN_INT // The fast huffman tables are much more efficient if they can be // stored as 16-bit results instead of 32-bit results. This restricts // the codebooks to having only 65535 possible outcomes, though. // (At least, accelerated by the huffman table.) #ifndef STB_VORBIS_FAST_HUFFMAN_INT #define STB_VORBIS_FAST_HUFFMAN_SHORT #endif // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls // back on binary searching for the correct one. This requires storing // extra tables with the huffman codes in sorted order. Defining this // symbol trades off space for speed by forcing a linear search in the // non-fast case, except for "sparse" codebooks. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH // STB_VORBIS_DIVIDES_IN_RESIDUE // stb_vorbis precomputes the result of the scalar residue decoding // that would otherwise require a divide per chunk. you can trade off // space for time by defining this symbol. // #define STB_VORBIS_DIVIDES_IN_RESIDUE // STB_VORBIS_DIVIDES_IN_CODEBOOK // vorbis VQ codebooks can be encoded two ways: with every case explicitly // stored, or with all elements being chosen from a small range of values, // and all values possible in all elements. By default, stb_vorbis expands // this latter kind out to look like the former kind for ease of decoding, // because otherwise an integer divide-per-vector-element is required to // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can // trade off storage for speed. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK #ifdef STB_VORBIS_CODEBOOK_SHORTS #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats" #endif // STB_VORBIS_DIVIDE_TABLE // this replaces small integer divides in the floor decode loop with // table lookups. made less than 1% difference, so disabled by default. // STB_VORBIS_NO_INLINE_DECODE // disables the inlining of the scalar codebook fast-huffman decode. // might save a little codespace; useful for debugging // #define STB_VORBIS_NO_INLINE_DECODE // STB_VORBIS_NO_DEFER_FLOOR // Normally we only decode the floor without synthesizing the actual // full curve. We can instead synthesize the curve immediately. This // requires more memory and is very likely slower, so I don't think // you'd ever want to do it except for debugging. // #define STB_VORBIS_NO_DEFER_FLOOR ////////////////////////////////////////////////////////////////////////////// #ifdef STB_VORBIS_NO_PULLDATA_API #define STB_VORBIS_NO_INTEGER_CONVERSION #define STB_VORBIS_NO_STDIO #endif #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO) #define STB_VORBIS_NO_STDIO 1 #endif #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT // only need endianness for fast-float-to-int, which we don't // use for pushdata #ifndef STB_VORBIS_BIG_ENDIAN #define STB_VORBIS_ENDIAN 0 #else #define STB_VORBIS_ENDIAN 1 #endif #endif #endif #ifndef STB_VORBIS_NO_STDIO #include <stdio.h> #endif #ifndef STB_VORBIS_NO_CRT #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> // find definition of alloca if it's not in stdlib.h: #ifdef _MSC_VER #include <malloc.h> #endif #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__) #include <alloca.h> #endif #else // STB_VORBIS_NO_CRT #define NULL 0 #define malloc(s) 0 #define free(s) ((void) 0) #define realloc(s) 0 #endif // STB_VORBIS_NO_CRT #include <limits.h> #ifdef __MINGW32__ // eff you mingw: // "fixed": // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/ // "no that broke the build, reverted, who cares about C": // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/ #ifdef __forceinline #undef __forceinline #endif #define __forceinline #elif !defined(_MSC_VER) #if __GNUC__ #define __forceinline inline #else #define __forceinline #endif #endif #if STB_VORBIS_MAX_CHANNELS > 256 #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range" #endif #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24 #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range" #endif #if 0 #include <crtdbg.h> #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1]) #else #define CHECK(f) ((void) 0) #endif #define MAX_BLOCKSIZE_LOG 13 // from specification #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG) typedef unsigned char uint8; typedef signed char int8; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; #ifndef TRUE #define TRUE 1 #define FALSE 0 #endif typedef float codetype; // @NOTE // // Some arrays below are tagged "//varies", which means it's actually // a variable-sized piece of data, but rather than malloc I assume it's // small enough it's better to just allocate it all together with the // main thing // // Most of the variables are specified with the smallest size I could pack // them into. It might give better performance to make them all full-sized // integers. It should be safe to freely rearrange the structures or change // the sizes larger--nothing relies on silently truncating etc., nor the // order of variables. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH) #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1) typedef struct { int dimensions, entries; uint8 *codeword_lengths; float minimum_value; float delta_value; uint8 value_bits; uint8 lookup_type; uint8 sequence_p; uint8 sparse; uint32 lookup_values; codetype *multiplicands; uint32 *codewords; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #else int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE]; #endif uint32 *sorted_codewords; int *sorted_values; int sorted_entries; } Codebook; typedef struct { uint8 order; uint16 rate; uint16 bark_map_size; uint8 amplitude_bits; uint8 amplitude_offset; uint8 number_of_books; uint8 book_list[16]; // varies } Floor0; typedef struct { uint8 partitions; uint8 partition_class_list[32]; // varies uint8 class_dimensions[16]; // varies uint8 class_subclasses[16]; // varies uint8 class_masterbooks[16]; // varies int16 subclass_books[16][8]; // varies uint16 Xlist[31*8+2]; // varies uint8 sorted_order[31*8+2]; uint8 neighbors[31*8+2][2]; uint8 floor1_multiplier; uint8 rangebits; int values; } Floor1; typedef union { Floor0 floor0; Floor1 floor1; } Floor; typedef struct { uint32 begin, end; uint32 part_size; uint8 classifications; uint8 classbook; uint8 **classdata; int16 (*residue_books)[8]; } Residue; typedef struct { uint8 magnitude; uint8 angle; uint8 mux; } MappingChannel; typedef struct { uint16 coupling_steps; MappingChannel *chan; uint8 submaps; uint8 submap_floor[15]; // varies uint8 submap_residue[15]; // varies } Mapping; typedef struct { uint8 blockflag; uint8 mapping; uint16 windowtype; uint16 transformtype; } Mode; typedef struct { uint32 goal_crc; // expected crc if match int bytes_left; // bytes left in packet uint32 crc_so_far; // running crc int bytes_done; // bytes processed in _current_ chunk uint32 sample_loc; // granule pos encoded in page } CRCscan; typedef struct { uint32 page_start, page_end; uint32 last_decoded_sample; } ProbedPage; struct stb_vorbis { // user-accessible info unsigned int sample_rate; int channels; unsigned int setup_memory_required; unsigned int temp_memory_required; unsigned int setup_temp_memory_required; // input config #ifndef STB_VORBIS_NO_STDIO FILE *f; uint32 f_start; int close_on_free; #endif uint8 *stream; uint8 *stream_start; uint8 *stream_end; uint32 stream_len; uint8 push_mode; uint32 first_audio_page_offset; ProbedPage p_first, p_last; // memory management stb_vorbis_alloc alloc; int setup_offset; int temp_offset; // run-time results int eof; enum STBVorbisError error; // user-useful data // header info int blocksize[2]; int blocksize_0, blocksize_1; int codebook_count; Codebook *codebooks; int floor_count; uint16 floor_types[64]; // varies Floor *floor_config; int residue_count; uint16 residue_types[64]; // varies Residue *residue_config; int mapping_count; Mapping *mapping; int mode_count; Mode mode_config[64]; // varies uint32 total_samples; // decode buffer float *channel_buffers[STB_VORBIS_MAX_CHANNELS]; float *outputs [STB_VORBIS_MAX_CHANNELS]; float *previous_window[STB_VORBIS_MAX_CHANNELS]; int previous_length; #ifndef STB_VORBIS_NO_DEFER_FLOOR int16 *finalY[STB_VORBIS_MAX_CHANNELS]; #else float *floor_buffers[STB_VORBIS_MAX_CHANNELS]; #endif uint32 current_loc; // sample location of next frame to decode int current_loc_valid; // per-blocksize precomputed data // twiddle factors float *A[2],*B[2],*C[2]; float *window[2]; uint16 *bit_reverse[2]; // current page/packet/segment streaming info uint32 serial; // stream serial number for verification int last_page; int segment_count; uint8 segments[255]; uint8 page_flag; uint8 bytes_in_seg; uint8 first_decode; int next_seg; int last_seg; // flag that we're on the last segment int last_seg_which; // what was the segment number of the last seg? uint32 acc; int valid_bits; int packet_bytes; int end_seg_with_known_loc; uint32 known_loc_for_packet; int discard_samples_deferred; uint32 samples_output; // push mode scanning int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching #ifndef STB_VORBIS_NO_PUSHDATA_API CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT]; #endif // sample-access int channel_buffer_start; int channel_buffer_end; }; #if defined(STB_VORBIS_NO_PUSHDATA_API) #define IS_PUSH_MODE(f) FALSE #elif defined(STB_VORBIS_NO_PULLDATA_API) #define IS_PUSH_MODE(f) TRUE #else #define IS_PUSH_MODE(f) ((f)->push_mode) #endif typedef struct stb_vorbis vorb; static int error(vorb *f, enum STBVorbisError e) { f->error = e; if (!f->eof && e != VORBIS_need_more_data) { f->error=e; // breakpoint for debugging } return 0; } // these functions are used for allocating temporary memory // while decoding. if you can afford the stack space, use // alloca(); otherwise, provide a temp buffer and it will // allocate out of those. #define array_size_required(count,size) (count*(sizeof(void *)+(size))) #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size)) #ifdef dealloca #define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size)) #else #define temp_free(f,p) 0 #endif #define temp_alloc_save(f) ((f)->temp_offset) #define temp_alloc_restore(f,p) ((f)->temp_offset = (p)) #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size) // given a sufficiently large block of memory, make an array of pointers to subblocks of it static void *make_block_array(void *mem, int count, int size) { int i; void ** p = (void **) mem; char *q = (char *) (p + count); for (i=0; i < count; ++i) { p[i] = q; q += size; } return p; } static void *setup_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; f->setup_memory_required += sz; if (f->alloc.alloc_buffer) { void *p = (char *) f->alloc.alloc_buffer + f->setup_offset; if (f->setup_offset + sz > f->temp_offset) return NULL; f->setup_offset += sz; return p; } return sz ? malloc(sz) : NULL; } static void setup_free(vorb *f, void *p) { if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack free(p); } static void *setup_temp_malloc(vorb *f, int sz) { sz = (sz+3) & ~3; if (f->alloc.alloc_buffer) { if (f->temp_offset - sz < f->setup_offset) return NULL; f->temp_offset -= sz; return (char *) f->alloc.alloc_buffer + f->temp_offset; } return malloc(sz); } static void setup_temp_free(vorb *f, void *p, int sz) { if (f->alloc.alloc_buffer) { f->temp_offset += (sz+3)&~3; return; } free(p); } #define CRC32_POLY 0x04c11db7 // from spec static uint32 crc_table[256]; static void crc32_init(void) { int i,j; uint32 s; for(i=0; i < 256; i++) { for (s=(uint32) i << 24, j=0; j < 8; ++j) s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0); crc_table[i] = s; } } static __forceinline uint32 crc32_update(uint32 crc, uint8 byte) { return (crc << 8) ^ crc_table[byte ^ (crc >> 24)]; } // used in setup, and for huffman that doesn't go fast path static unsigned int bit_reverse(unsigned int n) { n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); return (n >> 16) | (n << 16); } static float square(float x) { return x*x; } // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3 // as required by the specification. fast(?) implementation from stb.h // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup static int ilog(int32 n) { static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 }; // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29) if (n < (1 << 14)) if (n < (1 << 4)) return 0 + log2_4[n ]; else if (n < (1 << 9)) return 5 + log2_4[n >> 5]; else return 10 + log2_4[n >> 10]; else if (n < (1 << 24)) if (n < (1 << 19)) return 15 + log2_4[n >> 15]; else return 20 + log2_4[n >> 20]; else if (n < (1 << 29)) return 25 + log2_4[n >> 25]; else if (n < (1 << 31)) return 30 + log2_4[n >> 30]; else return 0; // signed n returns 0 } #ifndef M_PI #define M_PI 3.14159265358979323846264f // from CRC #endif // code length assigned to a value with no huffman encoding #define NO_CODE 255 /////////////////////// LEAF SETUP FUNCTIONS ////////////////////////// // // these functions are only called at setup, and only a few times // per file static float float32_unpack(uint32 x) { // from the specification uint32 mantissa = x & 0x1fffff; uint32 sign = x & 0x80000000; uint32 exp = (x & 0x7fe00000) >> 21; double res = sign ? -(double)mantissa : (double)mantissa; return (float) ldexp((float)res, exp-788); } // zlib & jpeg huffman tables assume that the output symbols // can either be arbitrarily arranged, or have monotonically // increasing frequencies--they rely on the lengths being sorted; // this makes for a very simple generation algorithm. // vorbis allows a huffman table with non-sorted lengths. This // requires a more sophisticated construction, since symbols in // order do not map to huffman codes "in order". static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values) { if (!c->sparse) { c->codewords [symbol] = huff_code; } else { c->codewords [count] = huff_code; c->codeword_lengths[count] = len; values [count] = symbol; } } static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values) { int i,k,m=0; uint32 available[32]; memset(available, 0, sizeof(available)); // find the first entry for (k=0; k < n; ++k) if (len[k] < NO_CODE) break; if (k == n) { assert(c->sorted_entries == 0); return TRUE; } // add to the list add_entry(c, 0, k, m++, len[k], values); // add all available leaves for (i=1; i <= len[k]; ++i) available[i] = 1U << (32-i); // note that the above code treats the first case specially, // but it's really the same as the following code, so they // could probably be combined (except the initial code is 0, // and I use 0 in available[] to mean 'empty') for (i=k+1; i < n; ++i) { uint32 res; int z = len[i], y; if (z == NO_CODE) continue; // find lowest available leaf (should always be earliest, // which is what the specification calls for) // note that this property, and the fact we can never have // more than one free leaf at a given level, isn't totally // trivial to prove, but it seems true and the assert never // fires, so! while (z > 0 && !available[z]) --z; if (z == 0) { return FALSE; } res = available[z]; assert(z >= 0 && z < 32); available[z] = 0; add_entry(c, bit_reverse(res), i, m++, len[i], values); // propogate availability up the tree if (z != len[i]) { assert(len[i] >= 0 && len[i] < 32); for (y=len[i]; y > z; --y) { assert(available[y] == 0); available[y] = res + (1 << (32-y)); } } } return TRUE; } // accelerated huffman table allows fast O(1) match of all symbols // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH static void compute_accelerated_huffman(Codebook *c) { int i, len; for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i) c->fast_huffman[i] = -1; len = c->sparse ? c->sorted_entries : c->entries; #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT if (len > 32767) len = 32767; // largest possible value we can encode! #endif for (i=0; i < len; ++i) { if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) { uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i]; // set table entries for all bit combinations in the higher bits while (z < FAST_HUFFMAN_TABLE_SIZE) { c->fast_huffman[z] = i; z += 1 << c->codeword_lengths[i]; } } } } #ifdef _MSC_VER #define STBV_CDECL __cdecl #else #define STBV_CDECL #endif static int STBV_CDECL uint32_compare(const void *p, const void *q) { uint32 x = * (uint32 *) p; uint32 y = * (uint32 *) q; return x < y ? -1 : x > y; } static int include_in_sort(Codebook *c, uint8 len) { if (c->sparse) { assert(len != NO_CODE); return TRUE; } if (len == NO_CODE) return FALSE; if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE; return FALSE; } // if the fast table above doesn't work, we want to binary // search them... need to reverse the bits static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values) { int i, len; // build a list of all the entries // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN. // this is kind of a frivolous optimization--I don't see any performance improvement, // but it's like 4 extra lines of code, so. if (!c->sparse) { int k = 0; for (i=0; i < c->entries; ++i) if (include_in_sort(c, lengths[i])) c->sorted_codewords[k++] = bit_reverse(c->codewords[i]); assert(k == c->sorted_entries); } else { for (i=0; i < c->sorted_entries; ++i) c->sorted_codewords[i] = bit_reverse(c->codewords[i]); } qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare); c->sorted_codewords[c->sorted_entries] = 0xffffffff; len = c->sparse ? c->sorted_entries : c->entries; // now we need to indicate how they correspond; we could either // #1: sort a different data structure that says who they correspond to // #2: for each sorted entry, search the original list to find who corresponds // #3: for each original entry, find the sorted entry // #1 requires extra storage, #2 is slow, #3 can use binary search! for (i=0; i < len; ++i) { int huff_len = c->sparse ? lengths[values[i]] : lengths[i]; if (include_in_sort(c,huff_len)) { uint32 code = bit_reverse(c->codewords[i]); int x=0, n=c->sorted_entries; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } assert(c->sorted_codewords[x] == code); if (c->sparse) { c->sorted_values[x] = values[i]; c->codeword_lengths[x] = huff_len; } else { c->sorted_values[x] = i; } } } } // only run while parsing the header (3 times) static int vorbis_validate(uint8 *data) { static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' }; return memcmp(data, vorbis, 6) == 0; } // called from setup only, once per code book // (formula implied by specification) static int lookup1_values(int entries, int dim) { int r = (int) floor(exp((float) log((float) entries) / dim)); if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning; ++r; // floor() to avoid _ftol() when non-CRT assert(pow((float) r+1, dim) > entries); assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above return r; } // called twice per file static void compute_twiddle_factors(int n, float *A, float *B, float *C) { int n4 = n >> 2, n8 = n >> 3; int k,k2; for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f; B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f; } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } } static void compute_window(int n, float *window) { int n2 = n >> 1, i; for (i=0; i < n2; ++i) window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI))); } static void compute_bitreverse(int n, uint16 *rev) { int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions int i, n8 = n >> 3; for (i=0; i < n8; ++i) rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2; } static int init_blocksize(vorb *f, int b, int n) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3; f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2); f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4); if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem); compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]); f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2); if (!f->window[b]) return error(f, VORBIS_outofmem); compute_window(n, f->window[b]); f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8); if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem); compute_bitreverse(n, f->bit_reverse[b]); return TRUE; } static void neighbors(uint16 *x, int n, int *plow, int *phigh) { int low = -1; int high = 65536; int i; for (i=0; i < n; ++i) { if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; } if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; } } } // this has been repurposed so y is now the original index instead of y typedef struct { uint16 x,y; } Point; static int STBV_CDECL point_compare(const void *p, const void *q) { Point *a = (Point *) p; Point *b = (Point *) q; return a->x < b->x ? -1 : a->x > b->x; } // /////////////////////// END LEAF SETUP FUNCTIONS ////////////////////////// #if defined(STB_VORBIS_NO_STDIO) #define USE_MEMORY(z) TRUE #else #define USE_MEMORY(z) ((z)->stream) #endif static uint8 get8(vorb *z) { if (USE_MEMORY(z)) { if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; } return *z->stream++; } #ifndef STB_VORBIS_NO_STDIO { int c = fgetc(z->f); if (c == EOF) { z->eof = TRUE; return 0; } return c; } #endif } static uint32 get32(vorb *f) { uint32 x; x = get8(f); x += get8(f) << 8; x += get8(f) << 16; x += (uint32) get8(f) << 24; return x; } static int getn(vorb *z, uint8 *data, int n) { if (USE_MEMORY(z)) { if (z->stream+n > z->stream_end) { z->eof = 1; return 0; } memcpy(data, z->stream, n); z->stream += n; return 1; } #ifndef STB_VORBIS_NO_STDIO if (fread(data, n, 1, z->f) == 1) return 1; else { z->eof = 1; return 0; } #endif } static void skip(vorb *z, int n) { if (USE_MEMORY(z)) { z->stream += n; if (z->stream >= z->stream_end) z->eof = 1; return; } #ifndef STB_VORBIS_NO_STDIO { long x = ftell(z->f); fseek(z->f, x+n, SEEK_SET); } #endif } static int set_file_offset(stb_vorbis *f, unsigned int loc) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif f->eof = 0; if (USE_MEMORY(f)) { if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) { f->stream = f->stream_end; f->eof = 1; return 0; } else { f->stream = f->stream_start + loc; return 1; } } #ifndef STB_VORBIS_NO_STDIO if (loc + f->f_start < loc || loc >= 0x80000000) { loc = 0x7fffffff; f->eof = 1; } else { loc += f->f_start; } if (!fseek(f->f, loc, SEEK_SET)) return 1; f->eof = 1; fseek(f->f, f->f_start, SEEK_END); return 0; #endif } static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 }; static int capture_pattern(vorb *f) { if (0x4f != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x67 != get8(f)) return FALSE; if (0x53 != get8(f)) return FALSE; return TRUE; } #define PAGEFLAG_continued_packet 1 #define PAGEFLAG_first_page 2 #define PAGEFLAG_last_page 4 static int start_page_no_capturepattern(vorb *f) { uint32 loc0,loc1,n; // stream structure version if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version); // header flag f->page_flag = get8(f); // absolute granule position loc0 = get32(f); loc1 = get32(f); // @TODO: validate loc0,loc1 as valid positions? // stream serial number -- vorbis doesn't interleave, so discard get32(f); //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number); // page sequence number n = get32(f); f->last_page = n; // CRC32 get32(f); // page_segments f->segment_count = get8(f); if (!getn(f, f->segments, f->segment_count)) return error(f, VORBIS_unexpected_eof); // assume we _don't_ know any the sample position of any segments f->end_seg_with_known_loc = -2; if (loc0 != ~0U || loc1 != ~0U) { int i; // determine which packet is the last one that will complete for (i=f->segment_count-1; i >= 0; --i) if (f->segments[i] < 255) break; // 'i' is now the index of the _last_ segment of a packet that ends if (i >= 0) { f->end_seg_with_known_loc = i; f->known_loc_for_packet = loc0; } } if (f->first_decode) { int i,len; ProbedPage p; len = 0; for (i=0; i < f->segment_count; ++i) len += f->segments[i]; len += 27 + f->segment_count; p.page_start = f->first_audio_page_offset; p.page_end = p.page_start + len; p.last_decoded_sample = loc0; f->p_first = p; } f->next_seg = 0; return TRUE; } static int start_page(vorb *f) { if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern); return start_page_no_capturepattern(f); } static int start_packet(vorb *f) { while (f->next_seg == -1) { if (!start_page(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_continued_packet_flag_invalid); } f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; // f->next_seg is now valid return TRUE; } static int maybe_start_packet(vorb *f) { if (f->next_seg == -1) { int x = get8(f); if (f->eof) return FALSE; // EOF at page boundary is not an error! if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern); if (!start_page_no_capturepattern(f)) return FALSE; if (f->page_flag & PAGEFLAG_continued_packet) { // set up enough state that we can read this packet if we want, // e.g. during recovery f->last_seg = FALSE; f->bytes_in_seg = 0; return error(f, VORBIS_continued_packet_flag_invalid); } } return start_packet(f); } static int next_segment(vorb *f) { int len; if (f->last_seg) return 0; if (f->next_seg == -1) { f->last_seg_which = f->segment_count-1; // in case start_page fails if (!start_page(f)) { f->last_seg = 1; return 0; } if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid); } len = f->segments[f->next_seg++]; if (len < 255) { f->last_seg = TRUE; f->last_seg_which = f->next_seg-1; } if (f->next_seg >= f->segment_count) f->next_seg = -1; assert(f->bytes_in_seg == 0); f->bytes_in_seg = len; return len; } #define EOP (-1) #define INVALID_BITS (-1) static int get8_packet_raw(vorb *f) { if (!f->bytes_in_seg) { // CLANG! if (f->last_seg) return EOP; else if (!next_segment(f)) return EOP; } assert(f->bytes_in_seg > 0); --f->bytes_in_seg; ++f->packet_bytes; return get8(f); } static int get8_packet(vorb *f) { int x = get8_packet_raw(f); f->valid_bits = 0; return x; } static void flush_packet(vorb *f) { while (get8_packet_raw(f) != EOP); } // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important // as the huffman decoder? static uint32 get_bits(vorb *f, int n) { uint32 z; if (f->valid_bits < 0) return 0; if (f->valid_bits < n) { if (n > 24) { // the accumulator technique below would not work correctly in this case z = get_bits(f, 24); z += get_bits(f, n-24) << 24; return z; } if (f->valid_bits == 0) f->acc = 0; while (f->valid_bits < n) { int z = get8_packet_raw(f); if (z == EOP) { f->valid_bits = INVALID_BITS; return 0; } f->acc += z << f->valid_bits; f->valid_bits += 8; } } if (f->valid_bits < 0) return 0; z = f->acc & ((1 << n)-1); f->acc >>= n; f->valid_bits -= n; return z; } // @OPTIMIZE: primary accumulator for huffman // expand the buffer to as many bits as possible without reading off end of packet // it might be nice to allow f->valid_bits and f->acc to be stored in registers, // e.g. cache them locally and decode locally static __forceinline void prep_huffman(vorb *f) { if (f->valid_bits <= 24) { if (f->valid_bits == 0) f->acc = 0; do { int z; if (f->last_seg && !f->bytes_in_seg) return; z = get8_packet_raw(f); if (z == EOP) return; f->acc += (unsigned) z << f->valid_bits; f->valid_bits += 8; } while (f->valid_bits <= 24); } } enum { VORBIS_packet_id = 1, VORBIS_packet_comment = 3, VORBIS_packet_setup = 5 }; static int codebook_decode_scalar_raw(vorb *f, Codebook *c) { int i; prep_huffman(f); if (c->codewords == NULL && c->sorted_codewords == NULL) return -1; // cases to use binary search: sorted_codewords && !c->codewords // sorted_codewords && c->entries > 8 if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) { // binary search uint32 code = bit_reverse(f->acc); int x=0, n=c->sorted_entries, len; while (n > 1) { // invariant: sc[x] <= code < sc[x+n] int m = x + (n >> 1); if (c->sorted_codewords[m] <= code) { x = m; n -= (n>>1); } else { n >>= 1; } } // x is now the sorted index if (!c->sparse) x = c->sorted_values[x]; // x is now sorted index if sparse, or symbol otherwise len = c->codeword_lengths[x]; if (f->valid_bits >= len) { f->acc >>= len; f->valid_bits -= len; return x; } f->valid_bits = 0; return -1; } // if small, linear search assert(!c->sparse); for (i=0; i < c->entries; ++i) { if (c->codeword_lengths[i] == NO_CODE) continue; if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) { if (f->valid_bits >= c->codeword_lengths[i]) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; return i; } f->valid_bits = 0; return -1; } } error(f, VORBIS_invalid_stream); f->valid_bits = 0; return -1; } #ifndef STB_VORBIS_NO_INLINE_DECODE #define DECODE_RAW(var, f,c) \ if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \ prep_huffman(f); \ var = f->acc & FAST_HUFFMAN_TABLE_MASK; \ var = c->fast_huffman[var]; \ if (var >= 0) { \ int n = c->codeword_lengths[var]; \ f->acc >>= n; \ f->valid_bits -= n; \ if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \ } else { \ var = codebook_decode_scalar_raw(f,c); \ } #else static int codebook_decode_scalar(vorb *f, Codebook *c) { int i; if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) prep_huffman(f); // fast huffman table lookup i = f->acc & FAST_HUFFMAN_TABLE_MASK; i = c->fast_huffman[i]; if (i >= 0) { f->acc >>= c->codeword_lengths[i]; f->valid_bits -= c->codeword_lengths[i]; if (f->valid_bits < 0) { f->valid_bits = 0; return -1; } return i; } return codebook_decode_scalar_raw(f,c); } #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c); #endif #define DECODE(var,f,c) \ DECODE_RAW(var,f,c) \ if (c->sparse) var = c->sorted_values[var]; #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c) #else #define DECODE_VQ(var,f,c) DECODE(var,f,c) #endif // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case // where we avoid one addition #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off]) #define CODEBOOK_ELEMENT_BASE(c) (0) static int codebook_decode_start(vorb *f, Codebook *c) { int z = -1; // type 0 is only legal in a scalar context if (c->lookup_type == 0) error(f, VORBIS_invalid_stream); else { DECODE_VQ(z,f,c); if (c->sparse) assert(z < c->sorted_entries); if (z < 0) { // check for EOP if (!f->bytes_in_seg) if (f->last_seg) return z; error(f, VORBIS_invalid_stream); } } return z; } static int codebook_decode(vorb *f, Codebook *c, float *output, int len) { int i,z = codebook_decode_start(f,c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { float last = CODEBOOK_ELEMENT_BASE(c); int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i] += val; if (c->sequence_p) last = val + c->minimum_value; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; if (c->sequence_p) { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i] += val; last = val + c->minimum_value; } } else { float last = CODEBOOK_ELEMENT_BASE(c); for (i=0; i < len; ++i) { output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last; } } return TRUE; } static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step) { int i,z = codebook_decode_start(f,c); float last = CODEBOOK_ELEMENT_BASE(c); if (z < 0) return FALSE; if (len > c->dimensions) len = c->dimensions; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < len; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; output[i*step] += val; if (c->sequence_p) last = val; div *= c->lookup_values; } return TRUE; } #endif z *= c->dimensions; for (i=0; i < len; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; output[i*step] += val; if (c->sequence_p) last = val; } return TRUE; } static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode) { int c_inter = *c_inter_p; int p_inter = *p_inter_p; int i,z, effective = c->dimensions; // type 0 is only legal in a scalar context if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream); while (total_decode > 0) { float last = CODEBOOK_ELEMENT_BASE(c); DECODE_VQ(z,f,c); #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK assert(!c->sparse || z < c->sorted_entries); #endif if (z < 0) { if (!f->bytes_in_seg) if (f->last_seg) return FALSE; return error(f, VORBIS_invalid_stream); } // if this will take us off the end of the buffers, stop short! // we check by computing the length of the virtual interleaved // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter), // and the length we'll be using (effective) if (c_inter + p_inter*ch + effective > len * ch) { effective = len*ch - (p_inter*ch - c_inter); } #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int div = 1; for (i=0; i < effective; ++i) { int off = (z / div) % c->lookup_values; float val = CODEBOOK_ELEMENT_FAST(c,off) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } if (c->sequence_p) last = val; div *= c->lookup_values; } } else #endif { z *= c->dimensions; if (c->sequence_p) { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } last = val; } } else { for (i=0; i < effective; ++i) { float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last; if (outputs[c_inter]) outputs[c_inter][p_inter] += val; if (++c_inter == ch) { c_inter = 0; ++p_inter; } } } } total_decode -= effective; } *c_inter_p = c_inter; *p_inter_p = p_inter; return TRUE; } static int predict_point(int x, int x0, int x1, int y0, int y1) { int dy = y1 - y0; int adx = x1 - x0; // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86? int err = abs(dy) * (x - x0); int off = err / adx; return dy < 0 ? y0 - off : y0 + off; } // the following table is block-copied from the specification static float inverse_db_table[256] = { 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f }; // @OPTIMIZE: if you want to replace this bresenham line-drawing routine, // note that you must produce bit-identical output to decode correctly; // this specific sequence of operations is specified in the spec (it's // drawing integer-quantized frequency-space lines that the encoder // expects to be exactly the same) // ... also, isn't the whole point of Bresenham's algorithm to NOT // have to divide in the setup? sigh. #ifndef STB_VORBIS_NO_DEFER_FLOOR #define LINE_OP(a,b) a *= b #else #define LINE_OP(a,b) a = b #endif #ifdef STB_VORBIS_DIVIDE_TABLE #define DIVTAB_NUMER 32 #define DIVTAB_DENOM 64 int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB #endif static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n) { int dy = y1 - y0; int adx = x1 - x0; int ady = abs(dy); int base; int x=x0,y=y0; int err = 0; int sy; #ifdef STB_VORBIS_DIVIDE_TABLE if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) { if (dy < 0) { base = -integer_divide_table[ady][adx]; sy = base-1; } else { base = integer_divide_table[ady][adx]; sy = base+1; } } else { base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; } #else base = dy / adx; if (dy < 0) sy = base - 1; else sy = base+1; #endif ady -= abs(base) * adx; if (x1 > n) x1 = n; if (x < x1) { LINE_OP(output[x], inverse_db_table[y]); for (++x; x < x1; ++x) { err += ady; if (err >= adx) { err -= adx; y += sy; } else y += base; LINE_OP(output[x], inverse_db_table[y]); } } } static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype) { int k; if (rtype == 0) { int step = n / book->dimensions; for (k=0; k < step; ++k) if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step)) return FALSE; } else { for (k=0; k < n; ) { if (!codebook_decode(f, book, target+offset, n-k)) return FALSE; k += book->dimensions; offset += book->dimensions; } } return TRUE; } static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode) { int i,j,pass; Residue *r = f->residue_config + rn; int rtype = f->residue_types[rn]; int c = r->classbook; int classwords = f->codebooks[c].dimensions; int n_read = r->end - r->begin; int part_read = n_read / r->part_size; int temp_alloc_point = temp_alloc_save(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata)); #else int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications)); #endif CHECK(f); for (i=0; i < ch; ++i) if (!do_not_decode[i]) memset(residue_buffers[i], 0, sizeof(float) * n); if (rtype == 2 && ch != 1) { for (j=0; j < ch; ++j) if (!do_not_decode[j]) break; if (j == ch) goto done; for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set = 0; if (ch == 2) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = (z & 1), p_inter = z>>1; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #else // saves 1% if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; #endif } else { z += r->part_size; c_inter = z & 1; p_inter = z >> 1; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else if (ch == 1) { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = 0, p_inter = z; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = 0; p_inter = z; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } else { while (pcount < part_read) { int z = r->begin + pcount*r->part_size; int c_inter = z % ch, p_inter = z/ch; if (pass == 0) { Codebook *c = f->codebooks+r->classbook; int q; DECODE(q,f,c); if (q == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[0][class_set] = r->classdata[q]; #else for (i=classwords-1; i >= 0; --i) { classifications[0][i+pcount] = q % r->classifications; q /= r->classifications; } #endif } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { int z = r->begin + pcount*r->part_size; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[0][class_set][i]; #else int c = classifications[0][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { Codebook *book = f->codebooks + b; if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size)) goto done; } else { z += r->part_size; c_inter = z % ch; p_inter = z / ch; } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } } goto done; } CHECK(f); for (pass=0; pass < 8; ++pass) { int pcount = 0, class_set=0; while (pcount < part_read) { if (pass == 0) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { Codebook *c = f->codebooks+r->classbook; int temp; DECODE(temp,f,c); if (temp == EOP) goto done; #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE part_classdata[j][class_set] = r->classdata[temp]; #else for (i=classwords-1; i >= 0; --i) { classifications[j][i+pcount] = temp % r->classifications; temp /= r->classifications; } #endif } } } for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) { for (j=0; j < ch; ++j) { if (!do_not_decode[j]) { #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE int c = part_classdata[j][class_set][i]; #else int c = classifications[j][pcount]; #endif int b = r->residue_books[c][pass]; if (b >= 0) { float *target = residue_buffers[j]; int offset = r->begin + pcount * r->part_size; int n = r->part_size; Codebook *book = f->codebooks + b; if (!residue_decode(f, book, target, offset, n, rtype)) goto done; } } } } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE ++class_set; #endif } } done: CHECK(f); #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE temp_free(f,part_classdata); #else temp_free(f,classifications); #endif temp_alloc_restore(f,temp_alloc_point); } #if 0 // slow way for debugging void inverse_mdct_slow(float *buffer, int n) { int i,j; int n2 = n >> 1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) // formula from paper: //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); // formula from wikipedia //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); // these are equivalent, except the formula from the paper inverts the multiplier! // however, what actually works is NO MULTIPLIER!?! //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5)); acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1)); buffer[i] = acc; } free(x); } #elif 0 // same as above, but just barely able to run in real time on modern machines void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { float mcos[16384]; int i,j; int n2 = n >> 1, nmask = (n << 2) -1; float *x = (float *) malloc(sizeof(*x) * n2); memcpy(x, buffer, sizeof(*x) * n2); for (i=0; i < 4*n; ++i) mcos[i] = (float) cos(M_PI / 2 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n2; ++j) acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask]; buffer[i] = acc; } free(x); } #elif 0 // transform to use a slow dct-iv; this is STILL basically trivial, // but only requires half as many ops void dct_iv_slow(float *buffer, int n) { float mcos[16384]; float x[2048]; int i,j; int n2 = n >> 1, nmask = (n << 3) - 1; memcpy(x, buffer, sizeof(*x) * n); for (i=0; i < 8*n; ++i) mcos[i] = (float) cos(M_PI / 4 * i / n); for (i=0; i < n; ++i) { float acc = 0; for (j=0; j < n; ++j) acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask]; buffer[i] = acc; } } void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype) { int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4; float temp[4096]; memcpy(temp, buffer, n2 * sizeof(float)); dct_iv_slow(temp, n2); // returns -c'-d, a-b' for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b' for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d' for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d } #endif #ifndef LIBVORBIS_MDCT #define LIBVORBIS_MDCT 0 #endif #if LIBVORBIS_MDCT // directly call the vorbis MDCT using an interface documented // by Jeff Roberts... useful for performance comparison typedef struct { int n; int log2n; float *trig; int *bitrev; float scale; } mdct_lookup; extern void mdct_init(mdct_lookup *lookup, int n); extern void mdct_clear(mdct_lookup *l); extern void mdct_backward(mdct_lookup *init, float *in, float *out); mdct_lookup M1,M2; void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { mdct_lookup *M; if (M1.n == n) M = &M1; else if (M2.n == n) M = &M2; else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; } else { if (M2.n) __asm int 3; mdct_init(&M2, n); M = &M2; } mdct_backward(M, buffer, buffer); } #endif // the following were split out into separate functions while optimizing; // they could be pushed back up but eh. __forceinline showed no change; // they're probably already being inlined. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A) { float *ee0 = e + i_off; float *ee2 = ee0 + k_off; int i; assert((n & 3) == 0); for (i=(n>>2); i > 0; --i) { float k00_20, k01_21; k00_20 = ee0[ 0] - ee2[ 0]; k01_21 = ee0[-1] - ee2[-1]; ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = k00_20 * A[0] - k01_21 * A[1]; ee2[-1] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-2] - ee2[-2]; k01_21 = ee0[-3] - ee2[-3]; ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = k00_20 * A[0] - k01_21 * A[1]; ee2[-3] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-4] - ee2[-4]; k01_21 = ee0[-5] - ee2[-5]; ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = k00_20 * A[0] - k01_21 * A[1]; ee2[-5] = k01_21 * A[0] + k00_20 * A[1]; A += 8; k00_20 = ee0[-6] - ee2[-6]; k01_21 = ee0[-7] - ee2[-7]; ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = k00_20 * A[0] - k01_21 * A[1]; ee2[-7] = k01_21 * A[0] + k00_20 * A[1]; A += 8; ee0 -= 8; ee2 -= 8; } } static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1) { int i; float k00_20, k01_21; float *e0 = e + d0; float *e2 = e0 + k_off; for (i=lim >> 2; i > 0; --i) { k00_20 = e0[-0] - e2[-0]; k01_21 = e0[-1] - e2[-1]; e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0]; e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1]; e2[-0] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-1] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-2] - e2[-2]; k01_21 = e0[-3] - e2[-3]; e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2]; e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3]; e2[-2] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-3] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-4] - e2[-4]; k01_21 = e0[-5] - e2[-5]; e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4]; e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5]; e2[-4] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-5] = (k01_21)*A[0] + (k00_20) * A[1]; A += k1; k00_20 = e0[-6] - e2[-6]; k01_21 = e0[-7] - e2[-7]; e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6]; e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7]; e2[-6] = (k00_20)*A[0] - (k01_21) * A[1]; e2[-7] = (k01_21)*A[0] + (k00_20) * A[1]; e0 -= 8; e2 -= 8; A += k1; } } static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0) { int i; float A0 = A[0]; float A1 = A[0+1]; float A2 = A[0+a_off]; float A3 = A[0+a_off+1]; float A4 = A[0+a_off*2+0]; float A5 = A[0+a_off*2+1]; float A6 = A[0+a_off*3+0]; float A7 = A[0+a_off*3+1]; float k00,k11; float *ee0 = e +i_off; float *ee2 = ee0+k_off; for (i=n; i > 0; --i) { k00 = ee0[ 0] - ee2[ 0]; k11 = ee0[-1] - ee2[-1]; ee0[ 0] = ee0[ 0] + ee2[ 0]; ee0[-1] = ee0[-1] + ee2[-1]; ee2[ 0] = (k00) * A0 - (k11) * A1; ee2[-1] = (k11) * A0 + (k00) * A1; k00 = ee0[-2] - ee2[-2]; k11 = ee0[-3] - ee2[-3]; ee0[-2] = ee0[-2] + ee2[-2]; ee0[-3] = ee0[-3] + ee2[-3]; ee2[-2] = (k00) * A2 - (k11) * A3; ee2[-3] = (k11) * A2 + (k00) * A3; k00 = ee0[-4] - ee2[-4]; k11 = ee0[-5] - ee2[-5]; ee0[-4] = ee0[-4] + ee2[-4]; ee0[-5] = ee0[-5] + ee2[-5]; ee2[-4] = (k00) * A4 - (k11) * A5; ee2[-5] = (k11) * A4 + (k00) * A5; k00 = ee0[-6] - ee2[-6]; k11 = ee0[-7] - ee2[-7]; ee0[-6] = ee0[-6] + ee2[-6]; ee0[-7] = ee0[-7] + ee2[-7]; ee2[-6] = (k00) * A6 - (k11) * A7; ee2[-7] = (k11) * A6 + (k00) * A7; ee0 -= k0; ee2 -= k0; } } static __forceinline void iter_54(float *z) { float k00,k11,k22,k33; float y0,y1,y2,y3; k00 = z[ 0] - z[-4]; y0 = z[ 0] + z[-4]; y2 = z[-2] + z[-6]; k22 = z[-2] - z[-6]; z[-0] = y0 + y2; // z0 + z4 + z2 + z6 z[-2] = y0 - y2; // z0 + z4 - z2 - z6 // done with y0,y2 k33 = z[-3] - z[-7]; z[-4] = k00 + k33; // z0 - z4 + z3 - z7 z[-6] = k00 - k33; // z0 - z4 - z3 + z7 // done with k33 k11 = z[-1] - z[-5]; y1 = z[-1] + z[-5]; y3 = z[-3] + z[-7]; z[-1] = y1 + y3; // z1 + z5 + z3 + z7 z[-3] = y1 - y3; // z1 + z5 - z3 - z7 z[-5] = k11 - k22; // z1 - z5 + z2 - z6 z[-7] = k11 + k22; // z1 - z5 - z2 + z6 } static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n) { int a_off = base_n >> 3; float A2 = A[0+a_off]; float *z = e + i_off; float *base = z - 16 * n; while (z > base) { float k00,k11; k00 = z[-0] - z[-8]; k11 = z[-1] - z[-9]; z[-0] = z[-0] + z[-8]; z[-1] = z[-1] + z[-9]; z[-8] = k00; z[-9] = k11 ; k00 = z[ -2] - z[-10]; k11 = z[ -3] - z[-11]; z[ -2] = z[ -2] + z[-10]; z[ -3] = z[ -3] + z[-11]; z[-10] = (k00+k11) * A2; z[-11] = (k11-k00) * A2; k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation k11 = z[ -5] - z[-13]; z[ -4] = z[ -4] + z[-12]; z[ -5] = z[ -5] + z[-13]; z[-12] = k11; z[-13] = k00; k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation k11 = z[ -7] - z[-15]; z[ -6] = z[ -6] + z[-14]; z[ -7] = z[ -7] + z[-15]; z[-14] = (k00+k11) * A2; z[-15] = (k00-k11) * A2; iter_54(z); iter_54(z-8); z -= 16; } } static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype) { int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int ld; // @OPTIMIZE: reduce register pressure by using fewer variables? int save_point = temp_alloc_save(f); float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); float *u=NULL,*v=NULL; // twiddle factors float *A = f->A[blocktype]; // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function. // kernel from paper // merged: // copy and reflect spectral data // step 0 // note that it turns out that the items added together during // this step are, in fact, being added to themselves (as reflected // by step 0). inexplicable inefficiency! this became obvious // once I combined the passes. // so there's a missing 'times 2' here (for adding X to itself). // this propogates through linearly to the end, where the numbers // are 1/2 too small, and need to be compensated for. { float *d,*e, *AA, *e_stop; d = &buf2[n2-2]; AA = A; e = &buffer[0]; e_stop = &buffer[n2]; while (e != e_stop) { d[1] = (e[0] * AA[0] - e[2]*AA[1]); d[0] = (e[0] * AA[1] + e[2]*AA[0]); d -= 2; AA += 2; e += 4; } e = &buffer[n2-3]; while (d >= buf2) { d[1] = (-e[2] * AA[0] - -e[0]*AA[1]); d[0] = (-e[2] * AA[1] + -e[0]*AA[0]); d -= 2; AA += 2; e -= 4; } } // now we use symbolic names for these, so that we can // possibly swap their meaning as we change which operations // are in place u = buffer; v = buf2; // step 2 (paper output is w, now u) // this could be in place, but the data ends up in the wrong // place... _somebody_'s got to swap it, so this is nominated { float *AA = &A[n2-8]; float *d0,*d1, *e0, *e1; e0 = &v[n4]; e1 = &v[0]; d0 = &u[n4]; d1 = &u[0]; while (AA >= A) { float v40_20, v41_21; v41_21 = e0[1] - e1[1]; v40_20 = e0[0] - e1[0]; d0[1] = e0[1] + e1[1]; d0[0] = e0[0] + e1[0]; d1[1] = v41_21*AA[4] - v40_20*AA[5]; d1[0] = v40_20*AA[4] + v41_21*AA[5]; v41_21 = e0[3] - e1[3]; v40_20 = e0[2] - e1[2]; d0[3] = e0[3] + e1[3]; d0[2] = e0[2] + e1[2]; d1[3] = v41_21*AA[0] - v40_20*AA[1]; d1[2] = v40_20*AA[0] + v41_21*AA[1]; AA -= 8; d0 += 4; d1 += 4; e0 += 4; e1 += 4; } } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions // optimized step 3: // the original step3 loop can be nested r inside s or s inside r; // it's written originally as s inside r, but this is dumb when r // iterates many times, and s few. So I have two copies of it and // switch between them halfway. // this is iteration 0 of step 3 imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A); imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A); // this is iteration 1 of step 3 imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16); imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16); l=2; for (; l < (ld-3)>>1; ++l) { int k0 = n >> (l+2), k0_2 = k0>>1; int lim = 1 << (l+1); int i; for (i=0; i < lim; ++i) imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3)); } for (; l < ld-6; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1; int rlim = n >> (l+6), r; int lim = 1 << (l+1); int i_off; float *A0 = A; i_off = n2-1; for (r=rlim; r > 0; --r) { imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0); A0 += k1*4; i_off -= 8; } } // iterations with count: // ld-6,-5,-4 all interleaved together // the big win comes from getting rid of needless flops // due to the constants on pass 5 & 4 being all 1 and 0; // combining them to be simultaneous to improve cache made little difference imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); // output is u // step 4, 5, and 6 // cannot be in-place because of step 5 { uint16 *bitrev = f->bit_reverse[blocktype]; // weirdly, I'd have thought reading sequentially and writing // erratically would have been better than vice-versa, but in // fact that's not what my testing showed. (That is, with // j = bitreverse(i), do you read i and write j, or read j and write i.) float *d0 = &v[n4-4]; float *d1 = &v[n2-4]; while (d0 >= v) { int k4; k4 = bitrev[0]; d1[3] = u[k4+0]; d1[2] = u[k4+1]; d0[3] = u[k4+2]; d0[2] = u[k4+3]; k4 = bitrev[1]; d1[1] = u[k4+0]; d1[0] = u[k4+1]; d0[1] = u[k4+2]; d0[0] = u[k4+3]; d0 -= 4; d1 -= 4; bitrev += 2; } } // (paper output is u, now v) // data must be in buf2 assert(v == buf2); // step 7 (paper output is v, now v) // this is now in place { float *C = f->C[blocktype]; float *d, *e; d = v; e = v + n2 - 4; while (d < e) { float a02,a11,b0,b1,b2,b3; a02 = d[0] - e[2]; a11 = d[1] + e[3]; b0 = C[1]*a02 + C[0]*a11; b1 = C[1]*a11 - C[0]*a02; b2 = d[0] + e[ 2]; b3 = d[1] - e[ 3]; d[0] = b2 + b0; d[1] = b3 + b1; e[2] = b2 - b0; e[3] = b1 - b3; a02 = d[2] - e[0]; a11 = d[3] + e[1]; b0 = C[3]*a02 + C[2]*a11; b1 = C[3]*a11 - C[2]*a02; b2 = d[2] + e[ 0]; b3 = d[3] - e[ 1]; d[2] = b2 + b0; d[3] = b3 + b1; e[0] = b2 - b0; e[1] = b1 - b3; C += 4; d += 4; e -= 4; } } // data must be in buf2 // step 8+decode (paper output is X, now buffer) // this generates pairs of data a la 8 and pushes them directly through // the decode kernel (pushing rather than pulling) to avoid having // to make another pass later // this cannot POSSIBLY be in place, so we refer to the buffers directly { float *d0,*d1,*d2,*d3; float *B = f->B[blocktype] + n2 - 8; float *e = buf2 + n2 - 8; d0 = &buffer[0]; d1 = &buffer[n2-4]; d2 = &buffer[n2]; d3 = &buffer[n-4]; while (e >= v) { float p0,p1,p2,p3; p3 = e[6]*B[7] - e[7]*B[6]; p2 = -e[6]*B[6] - e[7]*B[7]; d0[0] = p3; d1[3] = - p3; d2[0] = p2; d3[3] = p2; p1 = e[4]*B[5] - e[5]*B[4]; p0 = -e[4]*B[4] - e[5]*B[5]; d0[1] = p1; d1[2] = - p1; d2[1] = p0; d3[2] = p0; p3 = e[2]*B[3] - e[3]*B[2]; p2 = -e[2]*B[2] - e[3]*B[3]; d0[2] = p3; d1[1] = - p3; d2[2] = p2; d3[1] = p2; p1 = e[0]*B[1] - e[1]*B[0]; p0 = -e[0]*B[0] - e[1]*B[1]; d0[3] = p1; d1[0] = - p1; d2[3] = p0; d3[0] = p0; B -= 8; e -= 8; d0 += 4; d2 += 4; d1 -= 4; d3 -= 4; } } temp_free(f,buf2); temp_alloc_restore(f,save_point); } #if 0 // this is the original version of the above code, if you want to optimize it from scratch void inverse_mdct_naive(float *buffer, int n) { float s; float A[1 << 12], B[1 << 12], C[1 << 11]; int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l; int n3_4 = n - n4, ld; // how can they claim this only uses N words?! // oh, because they're only used sparsely, whoops float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13]; // set up twiddle factors for (k=k2=0; k < n4; ++k,k2+=2) { A[k2 ] = (float) cos(4*k*M_PI/n); A[k2+1] = (float) -sin(4*k*M_PI/n); B[k2 ] = (float) cos((k2+1)*M_PI/n/2); B[k2+1] = (float) sin((k2+1)*M_PI/n/2); } for (k=k2=0; k < n8; ++k,k2+=2) { C[k2 ] = (float) cos(2*(k2+1)*M_PI/n); C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n); } // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio" // Note there are bugs in that pseudocode, presumably due to them attempting // to rename the arrays nicely rather than representing the way their actual // implementation bounces buffers back and forth. As a result, even in the // "some formulars corrected" version, a direct implementation fails. These // are noted below as "paper bug". // copy and reflect spectral data for (k=0; k < n2; ++k) u[k] = buffer[k]; for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1]; // kernel from paper // step 1 for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) { v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1]; v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2]; } // step 2 for (k=k4=0; k < n8; k+=1, k4+=4) { w[n2+3+k4] = v[n2+3+k4] + v[k4+3]; w[n2+1+k4] = v[n2+1+k4] + v[k4+1]; w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4]; w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4]; } // step 3 ld = ilog(n) - 1; // ilog is off-by-one from normal definitions for (l=0; l < ld-3; ++l) { int k0 = n >> (l+2), k1 = 1 << (l+3); int rlim = n >> (l+4), r4, r; int s2lim = 1 << (l+2), s2; for (r=r4=0; r < rlim; r4+=4,++r) { for (s2=0; s2 < s2lim; s2+=2) { u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4]; u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4]; u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1] - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1]; u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1] + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1]; } } if (l+1 < ld-3) { // paper bug: ping-ponging of u&w here is omitted memcpy(w, u, sizeof(u)); } } // step 4 for (i=0; i < n8; ++i) { int j = bit_reverse(i) >> (32-ld+3); assert(j < n8); if (i == j) { // paper bug: original code probably swapped in place; if copying, // need to directly copy in this case int i8 = i << 3; v[i8+1] = u[i8+1]; v[i8+3] = u[i8+3]; v[i8+5] = u[i8+5]; v[i8+7] = u[i8+7]; } else if (i < j) { int i8 = i << 3, j8 = j << 3; v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1]; v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3]; v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5]; v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7]; } } // step 5 for (k=0; k < n2; ++k) { w[k] = v[k*2+1]; } // step 6 for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) { u[n-1-k2] = w[k4]; u[n-2-k2] = w[k4+1]; u[n3_4 - 1 - k2] = w[k4+2]; u[n3_4 - 2 - k2] = w[k4+3]; } // step 7 for (k=k2=0; k < n8; ++k, k2 += 2) { v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2; v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2; } // step 8 for (k=k2=0; k < n4; ++k,k2 += 2) { X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1]; X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ]; } // decode kernel to output // determined the following value experimentally // (by first figuring out what made inverse_mdct_slow work); then matching that here // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?) s = 0.5; // theoretically would be n4 // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code, // so it needs to use the "old" B values to behave correctly, or else // set s to 1.0 ]]] for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4]; for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1]; for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4]; } #endif static float *get_window(vorb *f, int len) { len <<= 1; if (len == f->blocksize_0) return f->window[0]; if (len == f->blocksize_1) return f->window[1]; assert(0); return NULL; } #ifndef STB_VORBIS_NO_DEFER_FLOOR typedef int16 YTYPE; #else typedef int YTYPE; #endif static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag) { int n2 = n >> 1; int s = map->chan[i].mux, floor; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; int j,q; int lx = 0, ly = finalY[0] * g->floor1_multiplier; for (q=1; q < g->values; ++q) { j = g->sorted_order[q]; #ifndef STB_VORBIS_NO_DEFER_FLOOR if (finalY[j] >= 0) #else if (step2_flag[j]) #endif { int hy = finalY[j] * g->floor1_multiplier; int hx = g->Xlist[j]; if (lx != hx) draw_line(target, lx,ly, hx,hy, n2); CHECK(f); lx = hx, ly = hy; } } if (lx < n2) { // optimization of: draw_line(target, lx,ly, n,ly, n2); for (j=lx; j < n2; ++j) LINE_OP(target[j], inverse_db_table[ly]); CHECK(f); } } return TRUE; } // The meaning of "left" and "right" // // For a given frame: // we compute samples from 0..n // window_center is n/2 // we'll window and mix the samples from left_start to left_end with data from the previous frame // all of the samples from left_end to right_start can be output without mixing; however, // this interval is 0-length except when transitioning between short and long frames // all of the samples from right_start to right_end need to be mixed with the next frame, // which we don't have, so those get saved in a buffer // frame N's right_end-right_start, the number of samples to mix with the next frame, // has to be the same as frame N+1's left_end-left_start (which they are by // construction) static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { Mode *m; int i, n, prev, next, window_center; f->channel_buffer_start = f->channel_buffer_end = 0; retry: if (f->eof) return FALSE; if (!maybe_start_packet(f)) return FALSE; // check packet type if (get_bits(f,1) != 0) { if (IS_PUSH_MODE(f)) return error(f,VORBIS_bad_packet_type); while (EOP != get8_packet(f)); goto retry; } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); i = get_bits(f, ilog(f->mode_count-1)); if (i == EOP) return FALSE; if (i >= f->mode_count) return FALSE; *mode = i; m = f->mode_config + i; if (m->blockflag) { n = f->blocksize_1; prev = get_bits(f,1); next = get_bits(f,1); } else { prev = next = 0; n = f->blocksize_0; } // WINDOWING window_center = n >> 1; if (m->blockflag && !prev) { *p_left_start = (n - f->blocksize_0) >> 2; *p_left_end = (n + f->blocksize_0) >> 2; } else { *p_left_start = 0; *p_left_end = window_center; } if (m->blockflag && !next) { *p_right_start = (n*3 - f->blocksize_0) >> 2; *p_right_end = (n*3 + f->blocksize_0) >> 2; } else { *p_right_start = window_center; *p_right_end = n; } return TRUE; } static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left) { Mapping *map; int i,j,k,n,n2; int zero_channel[256]; int really_zero_channel[256]; // WINDOWING n = f->blocksize[m->blockflag]; map = &f->mapping[m->mapping]; // FLOORS n2 = n >> 1; CHECK(f); for (i=0; i < f->channels; ++i) { int s = map->chan[i].mux, floor; zero_channel[i] = FALSE; floor = map->submap_floor[s]; if (f->floor_types[floor] == 0) { return error(f, VORBIS_invalid_stream); } else { Floor1 *g = &f->floor_config[floor].floor1; if (get_bits(f, 1)) { short *finalY; uint8 step2_flag[256]; static int range_list[4] = { 256, 128, 86, 64 }; int range = range_list[g->floor1_multiplier-1]; int offset = 2; finalY = f->finalY[i]; finalY[0] = get_bits(f, ilog(range)-1); finalY[1] = get_bits(f, ilog(range)-1); for (j=0; j < g->partitions; ++j) { int pclass = g->partition_class_list[j]; int cdim = g->class_dimensions[pclass]; int cbits = g->class_subclasses[pclass]; int csub = (1 << cbits)-1; int cval = 0; if (cbits) { Codebook *c = f->codebooks + g->class_masterbooks[pclass]; DECODE(cval,f,c); } for (k=0; k < cdim; ++k) { int book = g->subclass_books[pclass][cval & csub]; cval = cval >> cbits; if (book >= 0) { int temp; Codebook *c = f->codebooks + book; DECODE(temp,f,c); finalY[offset++] = temp; } else finalY[offset++] = 0; } } if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec step2_flag[0] = step2_flag[1] = 1; for (j=2; j < g->values; ++j) { int low, high, pred, highroom, lowroom, room, val; low = g->neighbors[j][0]; high = g->neighbors[j][1]; //neighbors(g->Xlist, j, &low, &high); pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]); val = finalY[j]; highroom = range - pred; lowroom = pred; if (highroom < lowroom) room = highroom * 2; else room = lowroom * 2; if (val) { step2_flag[low] = step2_flag[high] = 1; step2_flag[j] = 1; if (val >= room) if (highroom > lowroom) finalY[j] = val - lowroom + pred; else finalY[j] = pred - val + highroom - 1; else if (val & 1) finalY[j] = pred - ((val+1)>>1); else finalY[j] = pred + (val>>1); } else { step2_flag[j] = 0; finalY[j] = pred; } } #ifdef STB_VORBIS_NO_DEFER_FLOOR do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag); #else // defer final floor computation until _after_ residue for (j=0; j < g->values; ++j) { if (!step2_flag[j]) finalY[j] = -1; } #endif } else { error: zero_channel[i] = TRUE; } // So we just defer everything else to later // at this point we've decoded the floor into buffer } } CHECK(f); // at this point we've decoded all floors if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); // re-enable coupled channels if necessary memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels); for (i=0; i < map->coupling_steps; ++i) if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) { zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE; } CHECK(f); // RESIDUE DECODE for (i=0; i < map->submaps; ++i) { float *residue_buffers[STB_VORBIS_MAX_CHANNELS]; int r; uint8 do_not_decode[256]; int ch = 0; for (j=0; j < f->channels; ++j) { if (map->chan[j].mux == i) { if (zero_channel[j]) { do_not_decode[ch] = TRUE; residue_buffers[ch] = NULL; } else { do_not_decode[ch] = FALSE; residue_buffers[ch] = f->channel_buffers[j]; } ++ch; } } r = map->submap_residue[i]; decode_residue(f, residue_buffers, ch, n2, r, do_not_decode); } if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); CHECK(f); // INVERSE COUPLING for (i = map->coupling_steps-1; i >= 0; --i) { int n2 = n >> 1; float *m = f->channel_buffers[map->chan[i].magnitude]; float *a = f->channel_buffers[map->chan[i].angle ]; for (j=0; j < n2; ++j) { float a2,m2; if (m[j] > 0) if (a[j] > 0) m2 = m[j], a2 = m[j] - a[j]; else a2 = m[j], m2 = m[j] + a[j]; else if (a[j] > 0) m2 = m[j], a2 = m[j] + a[j]; else a2 = m[j], m2 = m[j] - a[j]; m[j] = m2; a[j] = a2; } } CHECK(f); // finish decoding the floors #ifndef STB_VORBIS_NO_DEFER_FLOOR for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL); } } #else for (i=0; i < f->channels; ++i) { if (really_zero_channel[i]) { memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2); } else { for (j=0; j < n2; ++j) f->channel_buffers[i][j] *= f->floor_buffers[i][j]; } } #endif // INVERSE MDCT CHECK(f); for (i=0; i < f->channels; ++i) inverse_mdct(f->channel_buffers[i], n, f, m->blockflag); CHECK(f); // this shouldn't be necessary, unless we exited on an error // and want to flush to get to the next packet flush_packet(f); if (f->first_decode) { // assume we start so first non-discarded sample is sample 0 // this isn't to spec, but spec would require us to read ahead // and decode the size of all current frames--could be done, // but presumably it's not a commonly used feature f->current_loc = -n2; // start of first frame is positioned for discard // we might have to discard samples "from" the next frame too, // if we're lapping a large block then a small at the start? f->discard_samples_deferred = n - right_end; f->current_loc_valid = TRUE; f->first_decode = FALSE; } else if (f->discard_samples_deferred) { if (f->discard_samples_deferred >= right_start - left_start) { f->discard_samples_deferred -= (right_start - left_start); left_start = right_start; *p_left = left_start; } else { left_start += f->discard_samples_deferred; *p_left = left_start; f->discard_samples_deferred = 0; } } else if (f->previous_length == 0 && f->current_loc_valid) { // we're recovering from a seek... that means we're going to discard // the samples from this packet even though we know our position from // the last page header, so we need to update the position based on // the discarded samples here // but wait, the code below is going to add this in itself even // on a discard, so we don't need to do it here... } // check if we have ogg information about the sample # for this packet if (f->last_seg_which == f->end_seg_with_known_loc) { // if we have a valid current loc, and this is final: if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) { uint32 current_end = f->known_loc_for_packet - (n-right_end); // then let's infer the size of the (probably) short final frame if (current_end < f->current_loc + (right_end-left_start)) { if (current_end < f->current_loc) { // negative truncation, that's impossible! *len = 0; } else { *len = current_end - f->current_loc; } *len += left_start; if (*len > right_end) *len = right_end; // this should never happen f->current_loc += *len; return TRUE; } } // otherwise, just set our sample loc // guess that the ogg granule pos refers to the _middle_ of the // last frame? // set f->current_loc to the position of left_start f->current_loc = f->known_loc_for_packet - (n2-left_start); f->current_loc_valid = TRUE; } if (f->current_loc_valid) f->current_loc += (right_start - left_start); if (f->alloc.alloc_buffer) assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset); *len = right_end; // ignore samples after the window goes to 0 CHECK(f); return TRUE; } static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right) { int mode, left_end, right_end; if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0; return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left); } static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right) { int prev,i,j; // we use right&left (the start of the right- and left-window sin()-regions) // to determine how much to return, rather than inferring from the rules // (same result, clearer code); 'left' indicates where our sin() window // starts, therefore where the previous window's right edge starts, and // therefore where to start mixing from the previous buffer. 'right' // indicates where our sin() ending-window starts, therefore that's where // we start saving, and where our returned-data ends. // mixin from previous window if (f->previous_length) { int i,j, n = f->previous_length; float *w = get_window(f, n); for (i=0; i < f->channels; ++i) { for (j=0; j < n; ++j) f->channel_buffers[i][left+j] = f->channel_buffers[i][left+j]*w[ j] + f->previous_window[i][ j]*w[n-1-j]; } } prev = f->previous_length; // last half of this data becomes previous window f->previous_length = len - right; // @OPTIMIZE: could avoid this copy by double-buffering the // output (flipping previous_window with channel_buffers), but // then previous_window would have to be 2x as large, and // channel_buffers couldn't be temp mem (although they're NOT // currently temp mem, they could be (unless we want to level // performance by spreading out the computation)) for (i=0; i < f->channels; ++i) for (j=0; right+j < len; ++j) f->previous_window[i][j] = f->channel_buffers[i][right+j]; if (!prev) // there was no previous packet, so this data isn't valid... // this isn't entirely true, only the would-have-overlapped data // isn't valid, but this seems to be what the spec requires return 0; // truncate a short frame if (len < right) right = len; f->samples_output += right-left; return right - left; } static void vorbis_pump_first_frame(stb_vorbis *f) { int len, right, left; if (vorbis_decode_packet(f, &len, &left, &right)) vorbis_finish_frame(f, len, left, right); } #ifndef STB_VORBIS_NO_PUSHDATA_API static int is_whole_packet_present(stb_vorbis *f, int end_page) { // make sure that we have the packet available before continuing... // this requires a full ogg parse, but we know we can fetch from f->stream // instead of coding this out explicitly, we could save the current read state, // read the next packet with get8() until end-of-packet, check f->eof, then // reset the state? but that would be slower, esp. since we'd have over 256 bytes // of state to restore (primarily the page segment table) int s = f->next_seg, first = TRUE; uint8 *p = f->stream; if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag for (; s < f->segment_count; ++s) { p += f->segments[s]; if (f->segments[s] < 255) // stop at first short segment break; } // either this continues, or it ends it... if (end_page) if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream); if (s == f->segment_count) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } for (; s == -1;) { uint8 *q; int n; // check that we have the page header ready if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data); // validate the page if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream); if (p[4] != 0) return error(f, VORBIS_invalid_stream); if (first) { // the first segment must NOT have 'continued_packet', later ones MUST if (f->previous_length) if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); // if no previous length, we're resynching, so we can come in on a continued-packet, // which we'll just drop } else { if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream); } n = p[26]; // segment counts q = p+27; // q points to segment table p = q + n; // advance past header // make sure we've read the segment table if (p > f->stream_end) return error(f, VORBIS_need_more_data); for (s=0; s < n; ++s) { p += q[s]; if (q[s] < 255) break; } if (end_page) if (s < n-1) return error(f, VORBIS_invalid_stream); if (s == n) s = -1; // set 'crosses page' flag if (p > f->stream_end) return error(f, VORBIS_need_more_data); first = FALSE; } return TRUE; } #endif // !STB_VORBIS_NO_PUSHDATA_API static int start_decoder(vorb *f) { uint8 header[6], x,y; int len,i,j,k, max_submaps = 0; int longest_floorlist=0; // first page, first packet if (!start_page(f)) return FALSE; // validate page flag if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page); if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page); // check for expected packet length if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page); if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page); // read packet // check packet header if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page); if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page); // vorbis_version if (get32(f) != 0) return error(f, VORBIS_invalid_first_page); f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page); if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels); f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page); get32(f); // bitrate_maximum get32(f); // bitrate_nominal get32(f); // bitrate_minimum x = get8(f); { int log0,log1; log0 = x & 15; log1 = x >> 4; f->blocksize_0 = 1 << log0; f->blocksize_1 = 1 << log1; if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup); if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup); if (log0 > log1) return error(f, VORBIS_invalid_setup); } // framing_flag x = get8(f); if (!(x & 1)) return error(f, VORBIS_invalid_first_page); // second packet! if (!start_page(f)) return FALSE; if (!start_packet(f)) return FALSE; do { len = next_segment(f); skip(f, len); f->bytes_in_seg = 0; } while (len); // third packet! if (!start_packet(f)) return FALSE; #ifndef STB_VORBIS_NO_PUSHDATA_API if (IS_PUSH_MODE(f)) { if (!is_whole_packet_present(f, TRUE)) { // convert error in ogg header to write type if (f->error == VORBIS_invalid_stream) f->error = VORBIS_invalid_setup; return FALSE; } } #endif crc32_init(); // always init it, to avoid multithread race conditions if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup); for (i=0; i < 6; ++i) header[i] = get8_packet(f); if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup); // codebooks f->codebook_count = get_bits(f,8) + 1; f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count); if (f->codebooks == NULL) return error(f, VORBIS_outofmem); memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count); for (i=0; i < f->codebook_count; ++i) { uint32 *values; int ordered, sorted_count; int total=0; uint8 *lengths; Codebook *c = f->codebooks+i; CHECK(f); x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup); x = get_bits(f, 8); c->dimensions = (get_bits(f, 8)<<8) + x; x = get_bits(f, 8); y = get_bits(f, 8); c->entries = (get_bits(f, 8)<<16) + (y<<8) + x; ordered = get_bits(f,1); c->sparse = ordered ? 0 : get_bits(f,1); if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup); if (c->sparse) lengths = (uint8 *) setup_temp_malloc(f, c->entries); else lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (!lengths) return error(f, VORBIS_outofmem); if (ordered) { int current_entry = 0; int current_length = get_bits(f,5) + 1; while (current_entry < c->entries) { int limit = c->entries - current_entry; int n = get_bits(f, ilog(limit)); if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); } memset(lengths + current_entry, current_length, n); current_entry += n; ++current_length; } } else { for (j=0; j < c->entries; ++j) { int present = c->sparse ? get_bits(f,1) : 1; if (present) { lengths[j] = get_bits(f, 5) + 1; ++total; if (lengths[j] == 32) return error(f, VORBIS_invalid_setup); } else { lengths[j] = NO_CODE; } } } if (c->sparse && total >= c->entries >> 2) { // convert sparse items to non-sparse! if (c->entries > (int) f->setup_temp_memory_required) f->setup_temp_memory_required = c->entries; c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries); if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem); memcpy(c->codeword_lengths, lengths, c->entries); setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs! lengths = c->codeword_lengths; c->sparse = 0; } // compute the size of the sorted tables if (c->sparse) { sorted_count = total; } else { sorted_count = 0; #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH for (j=0; j < c->entries; ++j) if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE) ++sorted_count; #endif } c->sorted_entries = sorted_count; values = NULL; CHECK(f); if (!c->sparse) { c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries); if (!c->codewords) return error(f, VORBIS_outofmem); } else { unsigned int size; if (c->sorted_entries) { c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries); if (!c->codeword_lengths) return error(f, VORBIS_outofmem); c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries); if (!c->codewords) return error(f, VORBIS_outofmem); values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries); if (!values) return error(f, VORBIS_outofmem); } size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries; if (size > f->setup_temp_memory_required) f->setup_temp_memory_required = size; } if (!compute_codewords(c, lengths, c->entries, values)) { if (c->sparse) setup_temp_free(f, values, 0); return error(f, VORBIS_invalid_setup); } if (c->sorted_entries) { // allocate an extra slot for sentinels c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1)); if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem); // allocate an extra slot at the front so that c->sorted_values[-1] is defined // so that we can catch that case without an extra if c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1)); if (c->sorted_values == NULL) return error(f, VORBIS_outofmem); ++c->sorted_values; c->sorted_values[-1] = -1; compute_sorted_huffman(c, lengths, values); } if (c->sparse) { setup_temp_free(f, values, sizeof(*values)*c->sorted_entries); setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries); setup_temp_free(f, lengths, c->entries); c->codewords = NULL; } compute_accelerated_huffman(c); CHECK(f); c->lookup_type = get_bits(f, 4); if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup); if (c->lookup_type > 0) { uint16 *mults; c->minimum_value = float32_unpack(get_bits(f, 32)); c->delta_value = float32_unpack(get_bits(f, 32)); c->value_bits = get_bits(f, 4)+1; c->sequence_p = get_bits(f,1); if (c->lookup_type == 1) { c->lookup_values = lookup1_values(c->entries, c->dimensions); } else { c->lookup_values = c->entries * c->dimensions; } if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup); mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values); if (mults == NULL) return error(f, VORBIS_outofmem); for (j=0; j < (int) c->lookup_values; ++j) { int q = get_bits(f, c->value_bits); if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } mults[j] = q; } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK if (c->lookup_type == 1) { int len, sparse = c->sparse; float last=0; // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop if (sparse) { if (c->sorted_entries == 0) goto skip; c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions); } else c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions); if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } len = sparse ? c->sorted_entries : c->entries; for (j=0; j < len; ++j) { unsigned int z = sparse ? c->sorted_values[j] : j; unsigned int div=1; for (k=0; k < c->dimensions; ++k) { int off = (z / div) % c->lookup_values; float val = mults[off]; val = mults[off]*c->delta_value + c->minimum_value + last; c->multiplicands[j*c->dimensions + k] = val; if (c->sequence_p) last = val; if (k+1 < c->dimensions) { if (div > UINT_MAX / (unsigned int) c->lookup_values) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); } div *= c->lookup_values; } } } c->lookup_type = 2; } else #endif { float last=0; CHECK(f); c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values); if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); } for (j=0; j < (int) c->lookup_values; ++j) { float val = mults[j] * c->delta_value + c->minimum_value + last; c->multiplicands[j] = val; if (c->sequence_p) last = val; } } #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK skip:; #endif setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values); CHECK(f); } CHECK(f); } // time domain transfers (notused) x = get_bits(f, 6) + 1; for (i=0; i < x; ++i) { uint32 z = get_bits(f, 16); if (z != 0) return error(f, VORBIS_invalid_setup); } // Floors f->floor_count = get_bits(f, 6)+1; f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config)); if (f->floor_config == NULL) return error(f, VORBIS_outofmem); for (i=0; i < f->floor_count; ++i) { f->floor_types[i] = get_bits(f, 16); if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup); if (f->floor_types[i] == 0) { Floor0 *g = &f->floor_config[i].floor0; g->order = get_bits(f,8); g->rate = get_bits(f,16); g->bark_map_size = get_bits(f,16); g->amplitude_bits = get_bits(f,6); g->amplitude_offset = get_bits(f,8); g->number_of_books = get_bits(f,4) + 1; for (j=0; j < g->number_of_books; ++j) g->book_list[j] = get_bits(f,8); return error(f, VORBIS_feature_not_supported); } else { Point p[31*8+2]; Floor1 *g = &f->floor_config[i].floor1; int max_class = -1; g->partitions = get_bits(f, 5); for (j=0; j < g->partitions; ++j) { g->partition_class_list[j] = get_bits(f, 4); if (g->partition_class_list[j] > max_class) max_class = g->partition_class_list[j]; } for (j=0; j <= max_class; ++j) { g->class_dimensions[j] = get_bits(f, 3)+1; g->class_subclasses[j] = get_bits(f, 2); if (g->class_subclasses[j]) { g->class_masterbooks[j] = get_bits(f, 8); if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } for (k=0; k < 1 << g->class_subclasses[j]; ++k) { g->subclass_books[j][k] = get_bits(f,8)-1; if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } } g->floor1_multiplier = get_bits(f,2)+1; g->rangebits = get_bits(f,4); g->Xlist[0] = 0; g->Xlist[1] = 1 << g->rangebits; g->values = 2; for (j=0; j < g->partitions; ++j) { int c = g->partition_class_list[j]; for (k=0; k < g->class_dimensions[c]; ++k) { g->Xlist[g->values] = get_bits(f, g->rangebits); ++g->values; } } // precompute the sorting for (j=0; j < g->values; ++j) { p[j].x = g->Xlist[j]; p[j].y = j; } qsort(p, g->values, sizeof(p[0]), point_compare); for (j=0; j < g->values; ++j) g->sorted_order[j] = (uint8) p[j].y; // precompute the neighbors for (j=2; j < g->values; ++j) { int low,hi; neighbors(g->Xlist, j, &low,&hi); g->neighbors[j][0] = low; g->neighbors[j][1] = hi; } if (g->values > longest_floorlist) longest_floorlist = g->values; } } // Residue f->residue_count = get_bits(f, 6)+1; f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0])); if (f->residue_config == NULL) return error(f, VORBIS_outofmem); memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0])); for (i=0; i < f->residue_count; ++i) { uint8 residue_cascade[64]; Residue *r = f->residue_config+i; f->residue_types[i] = get_bits(f, 16); if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup); r->begin = get_bits(f, 24); r->end = get_bits(f, 24); if (r->end < r->begin) return error(f, VORBIS_invalid_setup); r->part_size = get_bits(f,24)+1; r->classifications = get_bits(f,6)+1; r->classbook = get_bits(f,8); if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup); for (j=0; j < r->classifications; ++j) { uint8 high_bits=0; uint8 low_bits=get_bits(f,3); if (get_bits(f,1)) high_bits = get_bits(f,5); residue_cascade[j] = high_bits*8 + low_bits; } r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications); if (r->residue_books == NULL) return error(f, VORBIS_outofmem); for (j=0; j < r->classifications; ++j) { for (k=0; k < 8; ++k) { if (residue_cascade[j] & (1 << k)) { r->residue_books[j][k] = get_bits(f, 8); if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup); } else { r->residue_books[j][k] = -1; } } } // precompute the classifications[] array to avoid inner-loop mod/divide // call it 'classdata' since we already have r->classifications r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); if (!r->classdata) return error(f, VORBIS_outofmem); memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries); for (j=0; j < f->codebooks[r->classbook].entries; ++j) { int classwords = f->codebooks[r->classbook].dimensions; int temp = j; r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords); if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem); for (k=classwords-1; k >= 0; --k) { r->classdata[j][k] = temp % r->classifications; temp /= r->classifications; } } } f->mapping_count = get_bits(f,6)+1; f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping)); if (f->mapping == NULL) return error(f, VORBIS_outofmem); memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping)); for (i=0; i < f->mapping_count; ++i) { Mapping *m = f->mapping + i; int mapping_type = get_bits(f,16); if (mapping_type != 0) return error(f, VORBIS_invalid_setup); m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan)); if (m->chan == NULL) return error(f, VORBIS_outofmem); if (get_bits(f,1)) m->submaps = get_bits(f,4)+1; else m->submaps = 1; if (m->submaps > max_submaps) max_submaps = m->submaps; if (get_bits(f,1)) { m->coupling_steps = get_bits(f,8)+1; for (k=0; k < m->coupling_steps; ++k) { m->chan[k].magnitude = get_bits(f, ilog(f->channels-1)); m->chan[k].angle = get_bits(f, ilog(f->channels-1)); if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup); if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup); } } else m->coupling_steps = 0; // reserved field if (get_bits(f,2)) return error(f, VORBIS_invalid_setup); if (m->submaps > 1) { for (j=0; j < f->channels; ++j) { m->chan[j].mux = get_bits(f, 4); if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup); } } else // @SPECIFICATION: this case is missing from the spec for (j=0; j < f->channels; ++j) m->chan[j].mux = 0; for (j=0; j < m->submaps; ++j) { get_bits(f,8); // discard m->submap_floor[j] = get_bits(f,8); m->submap_residue[j] = get_bits(f,8); if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup); if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup); } } // Modes f->mode_count = get_bits(f, 6)+1; for (i=0; i < f->mode_count; ++i) { Mode *m = f->mode_config+i; m->blockflag = get_bits(f,1); m->windowtype = get_bits(f,16); m->transformtype = get_bits(f,16); m->mapping = get_bits(f,8); if (m->windowtype != 0) return error(f, VORBIS_invalid_setup); if (m->transformtype != 0) return error(f, VORBIS_invalid_setup); if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup); } flush_packet(f); f->previous_length = 0; for (i=0; i < f->channels; ++i) { f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1); f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist); if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem); #ifdef STB_VORBIS_NO_DEFER_FLOOR f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2); if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem); #endif } if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE; if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE; f->blocksize[0] = f->blocksize_0; f->blocksize[1] = f->blocksize_1; #ifdef STB_VORBIS_DIVIDE_TABLE if (integer_divide_table[1][1]==0) for (i=0; i < DIVTAB_NUMER; ++i) for (j=1; j < DIVTAB_DENOM; ++j) integer_divide_table[i][j] = i / j; #endif // compute how much temporary memory is needed // 1. { uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1); uint32 classify_mem; int i,max_part_read=0; for (i=0; i < f->residue_count; ++i) { Residue *r = f->residue_config + i; int n_read = r->end - r->begin; int part_read = n_read / r->part_size; if (part_read > max_part_read) max_part_read = part_read; } #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *)); #else classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *)); #endif f->temp_memory_required = classify_mem; if (imdct_mem > f->temp_memory_required) f->temp_memory_required = imdct_mem; } f->first_decode = TRUE; if (f->alloc.alloc_buffer) { assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes); // check if there's enough temp memory so we don't error later if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset) return error(f, VORBIS_outofmem); } f->first_audio_page_offset = stb_vorbis_get_file_offset(f); return TRUE; } static void vorbis_deinit(stb_vorbis *p) { int i,j; if (p->residue_config) { for (i=0; i < p->residue_count; ++i) { Residue *r = p->residue_config+i; if (r->classdata) { for (j=0; j < p->codebooks[r->classbook].entries; ++j) setup_free(p, r->classdata[j]); setup_free(p, r->classdata); } setup_free(p, r->residue_books); } } if (p->codebooks) { CHECK(p); for (i=0; i < p->codebook_count; ++i) { Codebook *c = p->codebooks + i; setup_free(p, c->codeword_lengths); setup_free(p, c->multiplicands); setup_free(p, c->codewords); setup_free(p, c->sorted_codewords); // c->sorted_values[-1] is the first entry in the array setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL); } setup_free(p, p->codebooks); } setup_free(p, p->floor_config); setup_free(p, p->residue_config); if (p->mapping) { for (i=0; i < p->mapping_count; ++i) setup_free(p, p->mapping[i].chan); setup_free(p, p->mapping); } CHECK(p); for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) { setup_free(p, p->channel_buffers[i]); setup_free(p, p->previous_window[i]); #ifdef STB_VORBIS_NO_DEFER_FLOOR setup_free(p, p->floor_buffers[i]); #endif setup_free(p, p->finalY[i]); } for (i=0; i < 2; ++i) { setup_free(p, p->A[i]); setup_free(p, p->B[i]); setup_free(p, p->C[i]); setup_free(p, p->window[i]); setup_free(p, p->bit_reverse[i]); } #ifndef STB_VORBIS_NO_STDIO if (p->close_on_free) fclose(p->f); #endif } void stb_vorbis_close(stb_vorbis *p) { if (p == NULL) return; vorbis_deinit(p); setup_free(p,p); } static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z) { memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start if (z) { p->alloc = *z; p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3; p->temp_offset = p->alloc.alloc_buffer_length_in_bytes; } p->eof = 0; p->error = VORBIS__no_error; p->stream = NULL; p->codebooks = NULL; p->page_crc_tests = -1; #ifndef STB_VORBIS_NO_STDIO p->close_on_free = FALSE; p->f = NULL; #endif } int stb_vorbis_get_sample_offset(stb_vorbis *f) { if (f->current_loc_valid) return f->current_loc; else return -1; } stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f) { stb_vorbis_info d; d.channels = f->channels; d.sample_rate = f->sample_rate; d.setup_memory_required = f->setup_memory_required; d.setup_temp_memory_required = f->setup_temp_memory_required; d.temp_memory_required = f->temp_memory_required; d.max_frame_size = f->blocksize_1 >> 1; return d; } int stb_vorbis_get_error(stb_vorbis *f) { int e = f->error; f->error = VORBIS__no_error; return e; } static stb_vorbis * vorbis_alloc(stb_vorbis *f) { stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p)); return p; } #ifndef STB_VORBIS_NO_PUSHDATA_API void stb_vorbis_flush_pushdata(stb_vorbis *f) { f->previous_length = 0; f->page_crc_tests = 0; f->discard_samples_deferred = 0; f->current_loc_valid = FALSE; f->first_decode = FALSE; f->samples_output = 0; f->channel_buffer_start = 0; f->channel_buffer_end = 0; } static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len) { int i,n; for (i=0; i < f->page_crc_tests; ++i) f->scan[i].bytes_done = 0; // if we have room for more scans, search for them first, because // they may cause us to stop early if their header is incomplete if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) { if (data_len < 4) return 0; data_len -= 3; // need to look for 4-byte sequence, so don't miss // one that straddles a boundary for (i=0; i < data_len; ++i) { if (data[i] == 0x4f) { if (0==memcmp(data+i, ogg_page_header, 4)) { int j,len; uint32 crc; // make sure we have the whole page header if (i+26 >= data_len || i+27+data[i+26] >= data_len) { // only read up to this page start, so hopefully we'll // have the whole page header start next time data_len = i; break; } // ok, we have it all; compute the length of the page len = 27 + data[i+26]; for (j=0; j < data[i+26]; ++j) len += data[i+27+j]; // scan everything up to the embedded crc (which we must 0) crc = 0; for (j=0; j < 22; ++j) crc = crc32_update(crc, data[i+j]); // now process 4 0-bytes for ( ; j < 26; ++j) crc = crc32_update(crc, 0); // len is the total number of bytes we need to scan n = f->page_crc_tests++; f->scan[n].bytes_left = len-j; f->scan[n].crc_so_far = crc; f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24); // if the last frame on a page is continued to the next, then // we can't recover the sample_loc immediately if (data[i+27+data[i+26]-1] == 255) f->scan[n].sample_loc = ~0; else f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24); f->scan[n].bytes_done = i+j; if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT) break; // keep going if we still have room for more } } } } for (i=0; i < f->page_crc_tests;) { uint32 crc; int j; int n = f->scan[i].bytes_done; int m = f->scan[i].bytes_left; if (m > data_len - n) m = data_len - n; // m is the bytes to scan in the current chunk crc = f->scan[i].crc_so_far; for (j=0; j < m; ++j) crc = crc32_update(crc, data[n+j]); f->scan[i].bytes_left -= m; f->scan[i].crc_so_far = crc; if (f->scan[i].bytes_left == 0) { // does it match? if (f->scan[i].crc_so_far == f->scan[i].goal_crc) { // Houston, we have page data_len = n+m; // consumption amount is wherever that scan ended f->page_crc_tests = -1; // drop out of page scan mode f->previous_length = 0; // decode-but-don't-output one frame f->next_seg = -1; // start a new page f->current_loc = f->scan[i].sample_loc; // set the current sample location // to the amount we'd have decoded had we decoded this page f->current_loc_valid = f->current_loc != ~0U; return data_len; } // delete entry f->scan[i] = f->scan[--f->page_crc_tests]; } else { ++i; } } return data_len; } // return value: number of bytes we used int stb_vorbis_decode_frame_pushdata( stb_vorbis *f, // the file we're decoding const uint8 *data, int data_len, // the memory available for decoding int *channels, // place to write number of float * buffers float ***output, // place to write float ** array of float * buffers int *samples // place to write number of output samples ) { int i; int len,right,left; if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (f->page_crc_tests >= 0) { *samples = 0; return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len); } f->stream = (uint8 *) data; f->stream_end = (uint8 *) data + data_len; f->error = VORBIS__no_error; // check that we have the entire packet in memory if (!is_whole_packet_present(f, FALSE)) { *samples = 0; return 0; } if (!vorbis_decode_packet(f, &len, &left, &right)) { // save the actual error we encountered enum STBVorbisError error = f->error; if (error == VORBIS_bad_packet_type) { // flush and resynch f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } if (error == VORBIS_continued_packet_flag_invalid) { if (f->previous_length == 0) { // we may be resynching, in which case it's ok to hit one // of these; just discard the packet f->error = VORBIS__no_error; while (get8_packet(f) != EOP) if (f->eof) break; *samples = 0; return (int) (f->stream - data); } } // if we get an error while parsing, what to do? // well, it DEFINITELY won't work to continue from where we are! stb_vorbis_flush_pushdata(f); // restore the error that actually made us bail f->error = error; *samples = 0; return 1; } // success! len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; if (channels) *channels = f->channels; *samples = len; *output = f->outputs; return (int) (f->stream - data); } stb_vorbis *stb_vorbis_open_pushdata( const unsigned char *data, int data_len, // the memory available for decoding int *data_used, // only defined if result is not NULL int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + data_len; p.push_mode = TRUE; if (!start_decoder(&p)) { if (p.eof) *error = VORBIS_need_more_data; else *error = p.error; return NULL; } f = vorbis_alloc(&p); if (f) { *f = p; *data_used = (int) (f->stream - data); *error = 0; return f; } else { vorbis_deinit(&p); return NULL; } } #endif // STB_VORBIS_NO_PUSHDATA_API unsigned int stb_vorbis_get_file_offset(stb_vorbis *f) { #ifndef STB_VORBIS_NO_PUSHDATA_API if (f->push_mode) return 0; #endif if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start); #ifndef STB_VORBIS_NO_STDIO return (unsigned int) (ftell(f->f) - f->f_start); #endif } #ifndef STB_VORBIS_NO_PULLDATA_API // // DATA-PULLING API // static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last) { for(;;) { int n; if (f->eof) return 0; n = get8(f); if (n == 0x4f) { // page header candidate unsigned int retry_loc = stb_vorbis_get_file_offset(f); int i; // check if we're off the end of a file_section stream if (retry_loc - 25 > f->stream_len) return 0; // check the rest of the header for (i=1; i < 4; ++i) if (get8(f) != ogg_page_header[i]) break; if (f->eof) return 0; if (i == 4) { uint8 header[27]; uint32 i, crc, goal, len; for (i=0; i < 4; ++i) header[i] = ogg_page_header[i]; for (; i < 27; ++i) header[i] = get8(f); if (f->eof) return 0; if (header[4] != 0) goto invalid; goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24); for (i=22; i < 26; ++i) header[i] = 0; crc = 0; for (i=0; i < 27; ++i) crc = crc32_update(crc, header[i]); len = 0; for (i=0; i < header[26]; ++i) { int s = get8(f); crc = crc32_update(crc, s); len += s; } if (len && f->eof) return 0; for (i=0; i < len; ++i) crc = crc32_update(crc, get8(f)); // finished parsing probable page if (crc == goal) { // we could now check that it's either got the last // page flag set, OR it's followed by the capture // pattern, but I guess TECHNICALLY you could have // a file with garbage between each ogg page and recover // from it automatically? So even though that paranoia // might decrease the chance of an invalid decode by // another 2^32, not worth it since it would hose those // invalid-but-useful files? if (end) *end = stb_vorbis_get_file_offset(f); if (last) { if (header[5] & 0x04) *last = 1; else *last = 0; } set_file_offset(f, retry_loc-1); return 1; } } invalid: // not a valid page, so rewind and look for next one set_file_offset(f, retry_loc); } } } #define SAMPLE_unknown 0xffffffff // seeking is implemented with a binary search, which narrows down the range to // 64K, before using a linear search (because finding the synchronization // pattern can be expensive, and the chance we'd find the end page again is // relatively high for small ranges) // // two initial interpolation-style probes are used at the start of the search // to try to bound either side of the binary search sensibly, while still // working in O(log n) time if they fail. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z) { uint8 header[27], lacing[255]; int i,len; // record where the page starts z->page_start = stb_vorbis_get_file_offset(f); // parse the header getn(f, header, 27); if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S') return 0; getn(f, lacing, header[26]); // determine the length of the payload len = 0; for (i=0; i < header[26]; ++i) len += lacing[i]; // this implies where the page ends z->page_end = z->page_start + 27 + header[26] + len; // read the last-decoded sample out of the data z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24); // restore file state to where we were set_file_offset(f, z->page_start); return 1; } // rarely used function to seek back to the preceeding page while finding the // start of a packet static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset) { unsigned int previous_safe, end; // now we want to seek back 64K from the limit if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset) previous_safe = limit_offset - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); while (vorbis_find_page(f, &end, NULL)) { if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset) return 1; set_file_offset(f, end); } return 0; } // implements the search logic for finding a page and starting decoding. if // the function succeeds, current_loc_valid will be true and current_loc will // be less than or equal to the provided sample number (the closer the // better). static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number) { ProbedPage left, right, mid; int i, start_seg_with_known_loc, end_pos, page_start; uint32 delta, stream_length, padding; double offset, bytes_per_sample; int probe = 0; // find the last page and validate the target sample stream_length = stb_vorbis_stream_length_in_samples(f); if (stream_length == 0) return error(f, VORBIS_seek_without_length); if (sample_number > stream_length) return error(f, VORBIS_seek_invalid); // this is the maximum difference between the window-center (which is the // actual granule position value), and the right-start (which the spec // indicates should be the granule position (give or take one)). padding = ((f->blocksize_1 - f->blocksize_0) >> 2); if (sample_number < padding) sample_number = 0; else sample_number -= padding; left = f->p_first; while (left.last_decoded_sample == ~0U) { // (untested) the first page does not have a 'last_decoded_sample' set_file_offset(f, left.page_end); if (!get_seek_page_info(f, &left)) goto error; } right = f->p_last; assert(right.last_decoded_sample != ~0U); // starting from the start is handled differently if (sample_number <= left.last_decoded_sample) { stb_vorbis_seek_start(f); return 1; } while (left.page_end != right.page_start) { assert(left.page_end < right.page_start); // search range in bytes delta = right.page_start - left.page_end; if (delta <= 65536) { // there's only 64K left to search - handle it linearly set_file_offset(f, left.page_end); } else { if (probe < 2) { if (probe == 0) { // first probe (interpolate) double data_bytes = right.page_end - left.page_start; bytes_per_sample = data_bytes / right.last_decoded_sample; offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample); } else { // second probe (try to bound the other side) double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample; if (error >= 0 && error < 8000) error = 8000; if (error < 0 && error > -8000) error = -8000; offset += error * 2; } // ensure the offset is valid if (offset < left.page_end) offset = left.page_end; if (offset > right.page_start - 65536) offset = right.page_start - 65536; set_file_offset(f, (unsigned int) offset); } else { // binary search for large ranges (offset by 32K to ensure // we don't hit the right page) set_file_offset(f, left.page_end + (delta / 2) - 32768); } if (!vorbis_find_page(f, NULL, NULL)) goto error; } for (;;) { if (!get_seek_page_info(f, &mid)) goto error; if (mid.last_decoded_sample != ~0U) break; // (untested) no frames end on this page set_file_offset(f, mid.page_end); assert(mid.page_start < right.page_start); } // if we've just found the last page again then we're in a tricky file, // and we're close enough. if (mid.page_start == right.page_start) break; if (sample_number < mid.last_decoded_sample) right = mid; else left = mid; ++probe; } // seek back to start of the last packet page_start = left.page_start; set_file_offset(f, page_start); if (!start_page(f)) return error(f, VORBIS_seek_failed); end_pos = f->end_seg_with_known_loc; assert(end_pos >= 0); for (;;) { for (i = end_pos; i > 0; --i) if (f->segments[i-1] != 255) break; start_seg_with_known_loc = i; if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet)) break; // (untested) the final packet begins on an earlier page if (!go_to_page_before(f, page_start)) goto error; page_start = stb_vorbis_get_file_offset(f); if (!start_page(f)) goto error; end_pos = f->segment_count - 1; } // prepare to start decoding f->current_loc_valid = FALSE; f->last_seg = FALSE; f->valid_bits = 0; f->packet_bytes = 0; f->bytes_in_seg = 0; f->previous_length = 0; f->next_seg = start_seg_with_known_loc; for (i = 0; i < start_seg_with_known_loc; i++) skip(f, f->segments[i]); // start decoding (optimizable - this frame is generally discarded) vorbis_pump_first_frame(f); return 1; error: // try to restore the file to a valid state stb_vorbis_seek_start(f); return error(f, VORBIS_seek_failed); } // the same as vorbis_decode_initial, but without advancing static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode) { int bits_read, bytes_read; if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode)) return 0; // either 1 or 2 bytes were read, figure out which so we can rewind bits_read = 1 + ilog(f->mode_count-1); if (f->mode_config[*mode].blockflag) bits_read += 2; bytes_read = (bits_read + 7) / 8; f->bytes_in_seg += bytes_read; f->packet_bytes -= bytes_read; skip(f, -bytes_read); if (f->next_seg == -1) f->next_seg = f->segment_count - 1; else f->next_seg--; f->valid_bits = 0; return 1; } int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number) { uint32 max_frame_samples; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); // fast page-level search if (!seek_to_sample_coarse(f, sample_number)) return 0; assert(f->current_loc_valid); assert(f->current_loc <= sample_number); // linear search for the relevant packet max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2; while (f->current_loc < sample_number) { int left_start, left_end, right_start, right_end, mode, frame_samples; if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode)) return error(f, VORBIS_seek_failed); // calculate the number of samples returned by the next frame frame_samples = right_start - left_start; if (f->current_loc + frame_samples > sample_number) { return 1; // the next frame will contain the sample } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) { // there's a chance the frame after this could contain the sample vorbis_pump_first_frame(f); } else { // this frame is too early to be relevant f->current_loc += frame_samples; f->previous_length = 0; maybe_start_packet(f); flush_packet(f); } } // the next frame will start with the sample assert(f->current_loc == sample_number); return 1; } int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number) { if (!stb_vorbis_seek_frame(f, sample_number)) return 0; if (sample_number != f->current_loc) { int n; uint32 frame_start = f->current_loc; stb_vorbis_get_frame_float(f, &n, NULL); assert(sample_number > frame_start); assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end); f->channel_buffer_start += (sample_number - frame_start); } return 1; } void stb_vorbis_seek_start(stb_vorbis *f) { if (IS_PUSH_MODE(f)) { error(f, VORBIS_invalid_api_mixing); return; } set_file_offset(f, f->first_audio_page_offset); f->previous_length = 0; f->first_decode = TRUE; f->next_seg = -1; vorbis_pump_first_frame(f); } unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f) { unsigned int restore_offset, previous_safe; unsigned int end, last_page_loc; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!f->total_samples) { unsigned int last; uint32 lo,hi; char header[6]; // first, store the current decode position so we can restore it restore_offset = stb_vorbis_get_file_offset(f); // now we want to seek back 64K from the end (the last page must // be at most a little less than 64K, but let's allow a little slop) if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset) previous_safe = f->stream_len - 65536; else previous_safe = f->first_audio_page_offset; set_file_offset(f, previous_safe); // previous_safe is now our candidate 'earliest known place that seeking // to will lead to the final page' if (!vorbis_find_page(f, &end, &last)) { // if we can't find a page, we're hosed! f->error = VORBIS_cant_find_last_page; f->total_samples = 0xffffffff; goto done; } // check if there are more pages last_page_loc = stb_vorbis_get_file_offset(f); // stop when the last_page flag is set, not when we reach eof; // this allows us to stop short of a 'file_section' end without // explicitly checking the length of the section while (!last) { set_file_offset(f, end); if (!vorbis_find_page(f, &end, &last)) { // the last page we found didn't have the 'last page' flag // set. whoops! break; } previous_safe = last_page_loc+1; last_page_loc = stb_vorbis_get_file_offset(f); } set_file_offset(f, last_page_loc); // parse the header getn(f, (unsigned char *)header, 6); // extract the absolute granule position lo = get32(f); hi = get32(f); if (lo == 0xffffffff && hi == 0xffffffff) { f->error = VORBIS_cant_find_last_page; f->total_samples = SAMPLE_unknown; goto done; } if (hi) lo = 0xfffffffe; // saturate f->total_samples = lo; f->p_last.page_start = last_page_loc; f->p_last.page_end = end; f->p_last.last_decoded_sample = lo; done: set_file_offset(f, restore_offset); } return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples; } float stb_vorbis_stream_length_in_seconds(stb_vorbis *f) { return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate; } int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output) { int len, right,left,i; if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing); if (!vorbis_decode_packet(f, &len, &left, &right)) { f->channel_buffer_start = f->channel_buffer_end = 0; return 0; } len = vorbis_finish_frame(f, len, left, right); for (i=0; i < f->channels; ++i) f->outputs[i] = f->channel_buffers[i] + left; f->channel_buffer_start = left; f->channel_buffer_end = left+len; if (channels) *channels = f->channels; if (output) *output = f->outputs; return len; } #ifndef STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length) { stb_vorbis *f, p; vorbis_init(&p, alloc); p.f = file; p.f_start = (uint32) ftell(file); p.stream_len = length; p.close_on_free = close_on_free; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc) { unsigned int len, start; start = (unsigned int) ftell(file); fseek(file, 0, SEEK_END); len = (unsigned int) (ftell(file) - start); fseek(file, start, SEEK_SET); return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len); } stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc) { FILE *f = fopen(filename, "rb"); if (f) return stb_vorbis_open_file(f, TRUE, error, alloc); if (error) *error = VORBIS_file_open_failure; return NULL; } #endif // STB_VORBIS_NO_STDIO stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc) { stb_vorbis *f, p; if (data == NULL) return NULL; vorbis_init(&p, alloc); p.stream = (uint8 *) data; p.stream_end = (uint8 *) data + len; p.stream_start = (uint8 *) p.stream; p.stream_len = len; p.push_mode = FALSE; if (start_decoder(&p)) { f = vorbis_alloc(&p); if (f) { *f = p; vorbis_pump_first_frame(f); return f; } } if (error) *error = p.error; vorbis_deinit(&p); return NULL; } #ifndef STB_VORBIS_NO_INTEGER_CONVERSION #define PLAYBACK_MONO 1 #define PLAYBACK_LEFT 2 #define PLAYBACK_RIGHT 4 #define L (PLAYBACK_LEFT | PLAYBACK_MONO) #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO) #define R (PLAYBACK_RIGHT | PLAYBACK_MONO) static int8 channel_position[7][6] = { { 0 }, { C }, { L, R }, { L, C, R }, { L, R, L, R }, { L, C, R, L, R }, { L, C, R, L, R, C }, }; #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT typedef union { float f; int i; } float_conv; typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4]; #define FASTDEF(x) float_conv x // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT)) #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22)) #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s)) #define check_endianness() #else #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s)))) #define check_endianness() #define FASTDEF(x) #endif static void copy_samples(short *dest, float *src, int len) { int i; check_endianness(); for (i=0; i < len; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; dest[i] = v; } } static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE; check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE) { memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { if (channel_position[num_c][j] & mask) { for (i=0; i < n; ++i) buffer[i] += data[j][d_offset+o+i]; } } for (i=0; i < n; ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o+i] = v; } } } static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len) { #define BUFFER_SIZE 32 float buffer[BUFFER_SIZE]; int i,j,o,n = BUFFER_SIZE >> 1; // o is the offset in the source data check_endianness(); for (o = 0; o < len; o += BUFFER_SIZE >> 1) { // o2 is the offset in the output data int o2 = o << 1; memset(buffer, 0, sizeof(buffer)); if (o + n > len) n = len - o; for (j=0; j < num_c; ++j) { int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT); if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; buffer[i*2+1] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_LEFT) { for (i=0; i < n; ++i) { buffer[i*2+0] += data[j][d_offset+o+i]; } } else if (m == PLAYBACK_RIGHT) { for (i=0; i < n; ++i) { buffer[i*2+1] += data[j][d_offset+o+i]; } } } for (i=0; i < (n<<1); ++i) { FASTDEF(temp); int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; output[o2+i] = v; } } } static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples) { int i; if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} }; for (i=0; i < buf_c; ++i) compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples); } else { int limit = buf_c < data_c ? buf_c : data_c; for (i=0; i < limit; ++i) copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples); for ( ; i < buf_c; ++i) memset(buffer[i]+b_offset, 0, sizeof(short) * samples); } } int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples) { float **output; int len = stb_vorbis_get_frame_float(f, NULL, &output); if (len > num_samples) len = num_samples; if (len) convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len); return len; } static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len) { int i; check_endianness(); if (buf_c != data_c && buf_c <= 2 && data_c <= 6) { assert(buf_c == 2); for (i=0; i < buf_c; ++i) compute_stereo_samples(buffer, data_c, data, d_offset, len); } else { int limit = buf_c < data_c ? buf_c : data_c; int j; for (j=0; j < len; ++j) { for (i=0; i < limit; ++i) { FASTDEF(temp); float f = data[i][d_offset+j]; int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15); if ((unsigned int) (v + 32768) > 65535) v = v < 0 ? -32768 : 32767; *buffer++ = v; } for ( ; i < buf_c; ++i) *buffer++ = 0; } } } int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts) { float **output; int len; if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts); len = stb_vorbis_get_frame_float(f, NULL, &output); if (len) { if (len*num_c > num_shorts) len = num_shorts / num_c; convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len); } return len; } int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts) { float **outputs; int len = num_shorts / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k); buffer += k*channels; n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; if (k) convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k); n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #ifndef STB_VORBIS_NO_STDIO int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // NO_STDIO int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output) { int data_len, offset, total, limit, error; short *data; stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL); if (v == NULL) return -1; limit = v->channels * 4096; *channels = v->channels; if (sample_rate) *sample_rate = v->sample_rate; offset = data_len = 0; total = limit; data = (short *) malloc(total * sizeof(*data)); if (data == NULL) { stb_vorbis_close(v); return -2; } for (;;) { int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset); if (n == 0) break; data_len += n; offset += n * v->channels; if (offset + limit > total) { short *data2; total *= 2; data2 = (short *) realloc(data, total * sizeof(*data)); if (data2 == NULL) { free(data); stb_vorbis_close(v); return -2; } data = data2; } } *output = data; stb_vorbis_close(v); return data_len; } #endif // STB_VORBIS_NO_INTEGER_CONVERSION int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats) { float **outputs; int len = num_floats / channels; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < len) { int i,j; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= len) k = len - n; for (j=0; j < k; ++j) { for (i=0; i < z; ++i) *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j]; for ( ; i < channels; ++i) *buffer++ = 0; } n += k; f->channel_buffer_start += k; if (n == len) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples) { float **outputs; int n=0; int z = f->channels; if (z > channels) z = channels; while (n < num_samples) { int i; int k = f->channel_buffer_end - f->channel_buffer_start; if (n+k >= num_samples) k = num_samples - n; if (k) { for (i=0; i < z; ++i) memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k); for ( ; i < channels; ++i) memset(buffer[i]+n, 0, sizeof(float) * k); } n += k; f->channel_buffer_start += k; if (n == num_samples) break; if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break; } return n; } #endif // STB_VORBIS_NO_PULLDATA_API /* Version history 1.09 - 2016/04/04 - back out 'avoid discarding last frame' fix from previous version 1.08 - 2016/04/02 - fixed multiple warnings; fix setup memory leaks; avoid discarding last frame of audio data 1.07 - 2015/01/16 - fixed some warnings, fix mingw, const-correct API some more crash fixes when out of memory or with corrupt files 1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson) some crash fixes when out of memory or with corrupt files 1.05 - 2015/04/19 - don't define __forceinline if it's redundant 1.04 - 2014/08/27 - fix missing const-correct case in API 1.03 - 2014/08/07 - Warning fixes 1.02 - 2014/07/09 - Declare qsort compare function _cdecl on windows 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in multichannel (API change) report sample rate for decode-full-file funcs 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence 0.99993 - remove assert that fired on legal files with empty tables 0.99992 - rewind-to-start 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++ 0.9998 - add a full-decode function with a memory source 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition 0.9996 - query length of vorbis stream in samples/seconds 0.9995 - bugfix to another optimization that only happened in certain files 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation 0.9992 - performance improvement of IMDCT; now performs close to reference implementation 0.9991 - performance improvement of IMDCT 0.999 - (should have been 0.9990) performance improvement of IMDCT 0.998 - no-CRT support from Casey Muratori 0.997 - bugfixes for bugs found by Terje Mathisen 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen 0.992 - fixes for MinGW warning 0.991 - turn fast-float-conversion on by default 0.990 - fix push-mode seek recovery if you seek into the headers 0.98b - fix to bad release of 0.98 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode 0.97 - builds under c++ (typecasting, don't use 'class' keyword) 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code 0.95 - clamping code for 16-bit functions 0.94 - not publically released 0.93 - fixed all-zero-floor case (was decoding garbage) 0.92 - fixed a memory leak 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION 0.90 - first public release */ #endif // STB_VORBIS_HEADER_ONLY
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
drivers/gles3/rasterizer_scene_gles3.cpp
5,014
#include "rasterizer_scene_gles3.h" #include "globals.h" #include "os/os.h" #include "rasterizer_canvas_gles3.h" #ifdef IPHONE_ENABLED // for some reason glClearDepth seems to have been removed in iOS ES3.h #define glClearDepth glClearDepthf #endif static const GLenum _cube_side_enum[6]={ GL_TEXTURE_CUBE_MAP_NEGATIVE_X, GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, }; static _FORCE_INLINE_ void store_transform2d(const Transform2D& p_mtx, float* p_array) { p_array[ 0]=p_mtx.elements[0][0]; p_array[ 1]=p_mtx.elements[0][1]; p_array[ 2]=0; p_array[ 3]=0; p_array[ 4]=p_mtx.elements[1][0]; p_array[ 5]=p_mtx.elements[1][1]; p_array[ 6]=0; p_array[ 7]=0; p_array[ 8]=0; p_array[ 9]=0; p_array[10]=1; p_array[11]=0; p_array[12]=p_mtx.elements[2][0]; p_array[13]=p_mtx.elements[2][1]; p_array[14]=0; p_array[15]=1; } static _FORCE_INLINE_ void store_transform(const Transform& p_mtx, float* p_array) { p_array[ 0]=p_mtx.basis.elements[0][0]; p_array[ 1]=p_mtx.basis.elements[1][0]; p_array[ 2]=p_mtx.basis.elements[2][0]; p_array[ 3]=0; p_array[ 4]=p_mtx.basis.elements[0][1]; p_array[ 5]=p_mtx.basis.elements[1][1]; p_array[ 6]=p_mtx.basis.elements[2][1]; p_array[ 7]=0; p_array[ 8]=p_mtx.basis.elements[0][2]; p_array[ 9]=p_mtx.basis.elements[1][2]; p_array[10]=p_mtx.basis.elements[2][2]; p_array[11]=0; p_array[12]=p_mtx.origin.x; p_array[13]=p_mtx.origin.y; p_array[14]=p_mtx.origin.z; p_array[15]=1; } static _FORCE_INLINE_ void store_camera(const CameraMatrix& p_mtx, float* p_array) { for (int i=0;i<4;i++) { for (int j=0;j<4;j++) { p_array[i*4+j]=p_mtx.matrix[i][j]; } } } /* SHADOW ATLAS API */ RID RasterizerSceneGLES3::shadow_atlas_create() { ShadowAtlas *shadow_atlas = memnew( ShadowAtlas ); shadow_atlas->fbo=0; shadow_atlas->depth=0; shadow_atlas->size=0; shadow_atlas->smallest_subdiv=0; for(int i=0;i<4;i++) { shadow_atlas->size_order[i]=i; } return shadow_atlas_owner.make_rid(shadow_atlas); } void RasterizerSceneGLES3::shadow_atlas_set_size(RID p_atlas,int p_size){ ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); ERR_FAIL_COND(!shadow_atlas); ERR_FAIL_COND(p_size<0); p_size = nearest_power_of_2(p_size); if (p_size==shadow_atlas->size) return; if (shadow_atlas->fbo) { glDeleteTextures(1,&shadow_atlas->depth); glDeleteFramebuffers(1,&shadow_atlas->fbo); shadow_atlas->depth=0; shadow_atlas->fbo=0; print_line("erasing atlas"); } for(int i=0;i<4;i++) { //clear subdivisions shadow_atlas->quadrants[i].shadows.resize(0); shadow_atlas->quadrants[i].shadows.resize( 1<<shadow_atlas->quadrants[i].subdivision ); } //erase shadow atlas reference from lights for (Map<RID,uint32_t>::Element *E=shadow_atlas->shadow_owners.front();E;E=E->next()) { LightInstance *li = light_instance_owner.getornull(E->key()); ERR_CONTINUE(!li); li->shadow_atlases.erase(p_atlas); } //clear owners shadow_atlas->shadow_owners.clear(); shadow_atlas->size=p_size; if (shadow_atlas->size) { glGenFramebuffers(1, &shadow_atlas->fbo); glBindFramebuffer(GL_FRAMEBUFFER, shadow_atlas->fbo); // Create a texture for storing the depth glActiveTexture(GL_TEXTURE0); glGenTextures(1, &shadow_atlas->depth); glBindTexture(GL_TEXTURE_2D, shadow_atlas->depth); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadow_atlas->size, shadow_atlas->size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_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); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadow_atlas->depth, 0); glViewport(0,0,shadow_atlas->size,shadow_atlas->size); glClearDepth(0.0f); glClear(GL_DEPTH_BUFFER_BIT); } } void RasterizerSceneGLES3::shadow_atlas_set_quadrant_subdivision(RID p_atlas,int p_quadrant,int p_subdivision){ ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); ERR_FAIL_COND(!shadow_atlas); ERR_FAIL_INDEX(p_quadrant,4); ERR_FAIL_INDEX(p_subdivision,16384); uint32_t subdiv = nearest_power_of_2(p_subdivision); if (subdiv&0xaaaaaaaa) { //sqrt(subdiv) must be integer subdiv<<=1; } subdiv=int(Math::sqrt((float)subdiv)); //obtain the number that will be x*x if (shadow_atlas->quadrants[p_quadrant].subdivision==subdiv) return; //erase all data from quadrant for(int i=0;i<shadow_atlas->quadrants[p_quadrant].shadows.size();i++) { if (shadow_atlas->quadrants[p_quadrant].shadows[i].owner.is_valid()) { shadow_atlas->shadow_owners.erase(shadow_atlas->quadrants[p_quadrant].shadows[i].owner); LightInstance *li = light_instance_owner.getornull(shadow_atlas->quadrants[p_quadrant].shadows[i].owner); ERR_CONTINUE(!li); li->shadow_atlases.erase(p_atlas); } } shadow_atlas->quadrants[p_quadrant].shadows.resize(0); shadow_atlas->quadrants[p_quadrant].shadows.resize(subdiv*subdiv); shadow_atlas->quadrants[p_quadrant].subdivision=subdiv; //cache the smallest subdiv (for faster allocation in light update) shadow_atlas->smallest_subdiv=1<<30; for(int i=0;i<4;i++) { if (shadow_atlas->quadrants[i].subdivision) { shadow_atlas->smallest_subdiv=MIN(shadow_atlas->smallest_subdiv,shadow_atlas->quadrants[i].subdivision); } } if (shadow_atlas->smallest_subdiv==1<<30) { shadow_atlas->smallest_subdiv=0; } //resort the size orders, simple bublesort for 4 elements.. int swaps=0; do { swaps=0; for(int i=0;i<3;i++) { if (shadow_atlas->quadrants[shadow_atlas->size_order[i]].subdivision < shadow_atlas->quadrants[shadow_atlas->size_order[i+1]].subdivision) { SWAP(shadow_atlas->size_order[i],shadow_atlas->size_order[i+1]); swaps++; } } } while(swaps>0); } bool RasterizerSceneGLES3::_shadow_atlas_find_shadow(ShadowAtlas *shadow_atlas,int *p_in_quadrants,int p_quadrant_count,int p_current_subdiv,uint64_t p_tick,int &r_quadrant,int &r_shadow) { for(int i=p_quadrant_count-1;i>=0;i--) { int qidx = p_in_quadrants[i]; if (shadow_atlas->quadrants[qidx].subdivision==p_current_subdiv) { return false; } //look for an empty space int sc = shadow_atlas->quadrants[qidx].shadows.size(); ShadowAtlas::Quadrant::Shadow *sarr = shadow_atlas->quadrants[qidx].shadows.ptr(); int found_free_idx=-1; //found a free one int found_used_idx=-1; //found existing one, must steal it uint64_t min_pass; // pass of the existing one, try to use the least recently used one (LRU fashion) for(int j=0;j<sc;j++) { if (!sarr[j].owner.is_valid()) { found_free_idx=j; break; } LightInstance *sli = light_instance_owner.getornull(sarr[j].owner); ERR_CONTINUE(!sli); if (sli->last_scene_pass!=scene_pass) { //was just allocated, don't kill it so soon, wait a bit.. if (p_tick-sarr[j].alloc_tick < shadow_atlas_realloc_tolerance_msec) continue; if (found_used_idx==-1 || sli->last_scene_pass<min_pass) { found_used_idx=j; min_pass=sli->last_scene_pass; } } } if (found_free_idx==-1 && found_used_idx==-1) continue; //nothing found if (found_free_idx==-1 && found_used_idx!=-1) { found_free_idx=found_used_idx; } r_quadrant=qidx; r_shadow=found_free_idx; return true; } return false; } bool RasterizerSceneGLES3::shadow_atlas_update_light(RID p_atlas, RID p_light_intance, float p_coverage, uint64_t p_light_version){ ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_atlas); ERR_FAIL_COND_V(!shadow_atlas,false); LightInstance *li = light_instance_owner.getornull(p_light_intance); ERR_FAIL_COND_V(!li,false); if (shadow_atlas->size==0 || shadow_atlas->smallest_subdiv==0) { return false; } uint32_t quad_size = shadow_atlas->size>>1; int desired_fit = MIN(quad_size/shadow_atlas->smallest_subdiv,nearest_power_of_2(quad_size*p_coverage)); int valid_quadrants[4]; int valid_quadrant_count=0; int best_size=-1; //best size found int best_subdiv=-1; //subdiv for the best size //find the quadrants this fits into, and the best possible size it can fit into for(int i=0;i<4;i++) { int q = shadow_atlas->size_order[i]; int sd = shadow_atlas->quadrants[q].subdivision; if (sd==0) continue; //unused int max_fit = quad_size / sd; if (best_size!=-1 && max_fit>best_size) break; //too large valid_quadrants[valid_quadrant_count++]=q; best_subdiv=sd; if (max_fit>=desired_fit) { best_size=max_fit; } } ERR_FAIL_COND_V(valid_quadrant_count==0,false); uint64_t tick = OS::get_singleton()->get_ticks_msec(); //see if it already exists if (shadow_atlas->shadow_owners.has(p_light_intance)) { //it does! uint32_t key = shadow_atlas->shadow_owners[p_light_intance]; uint32_t q = (key>>ShadowAtlas::QUADRANT_SHIFT)&0x3; uint32_t s = key&ShadowAtlas::SHADOW_INDEX_MASK; bool should_realloc=shadow_atlas->quadrants[q].subdivision!=best_subdiv && (shadow_atlas->quadrants[q].shadows[s].alloc_tick-tick > shadow_atlas_realloc_tolerance_msec); bool should_redraw=shadow_atlas->quadrants[q].shadows[s].version!=p_light_version; if (!should_realloc) { shadow_atlas->quadrants[q].shadows[s].version=p_light_version; //already existing, see if it should redraw or it's just OK return should_redraw; } int new_quadrant,new_shadow; //find a better place if (_shadow_atlas_find_shadow(shadow_atlas,valid_quadrants,valid_quadrant_count,shadow_atlas->quadrants[q].subdivision,tick,new_quadrant,new_shadow)) { //found a better place! ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows[new_shadow]; if (sh->owner.is_valid()) { //is taken, but is invalid, erasing it shadow_atlas->shadow_owners.erase(sh->owner); LightInstance *sli = light_instance_owner.get(sh->owner); sli->shadow_atlases.erase(p_atlas); } //erase previous shadow_atlas->quadrants[q].shadows[s].version=0; shadow_atlas->quadrants[q].shadows[s].owner=RID(); sh->owner=p_light_intance; sh->alloc_tick=tick; sh->version=p_light_version; //make new key key=new_quadrant<<ShadowAtlas::QUADRANT_SHIFT; key|=new_shadow; //update it in map shadow_atlas->shadow_owners[p_light_intance]=key; //make it dirty, as it should redraw anyway return true; } //no better place for this shadow found, keep current //already existing, see if it should redraw or it's just OK shadow_atlas->quadrants[q].shadows[s].version=p_light_version; return should_redraw; } int new_quadrant,new_shadow; //find a better place if (_shadow_atlas_find_shadow(shadow_atlas,valid_quadrants,valid_quadrant_count,-1,tick,new_quadrant,new_shadow)) { //found a better place! ShadowAtlas::Quadrant::Shadow *sh = &shadow_atlas->quadrants[new_quadrant].shadows[new_shadow]; if (sh->owner.is_valid()) { //is taken, but is invalid, erasing it shadow_atlas->shadow_owners.erase(sh->owner); LightInstance *sli = light_instance_owner.get(sh->owner); sli->shadow_atlases.erase(p_atlas); } sh->owner=p_light_intance; sh->alloc_tick=tick; sh->version=p_light_version; //make new key uint32_t key=new_quadrant<<ShadowAtlas::QUADRANT_SHIFT; key|=new_shadow; //update it in map shadow_atlas->shadow_owners[p_light_intance]=key; //make it dirty, as it should redraw anyway return true; } //no place to allocate this light, apologies return false; } void RasterizerSceneGLES3::set_directional_shadow_count(int p_count) { directional_shadow.light_count=p_count; directional_shadow.current_light=0; } int RasterizerSceneGLES3::get_directional_light_shadow_size(RID p_light_intance) { ERR_FAIL_COND_V(directional_shadow.light_count==0,0); int shadow_size; if (directional_shadow.light_count==1) { shadow_size = directional_shadow.size; } else { shadow_size = directional_shadow.size/2; //more than 4 not supported anyway } LightInstance *light_instance = light_instance_owner.getornull(p_light_intance); ERR_FAIL_COND_V(!light_instance,0); switch(light_instance->light_ptr->directional_shadow_mode) { case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: break; //none case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: shadow_size/=2; break; } return shadow_size; } ////////////////////////////////////////////////////// RID RasterizerSceneGLES3::reflection_atlas_create() { ReflectionAtlas *reflection_atlas = memnew( ReflectionAtlas ); reflection_atlas->subdiv=0; reflection_atlas->color=0; reflection_atlas->size=0; for(int i=0;i<6;i++) { reflection_atlas->fbo[i]=0; } return reflection_atlas_owner.make_rid(reflection_atlas); } void RasterizerSceneGLES3::reflection_atlas_set_size(RID p_ref_atlas,int p_size) { ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_ref_atlas); ERR_FAIL_COND(!reflection_atlas); int size = nearest_power_of_2(p_size); if (size==reflection_atlas->size) return; if (reflection_atlas->size) { for(int i=0;i<6;i++) { glDeleteFramebuffers(1,&reflection_atlas->fbo[i]); reflection_atlas->fbo[i]=0; } glDeleteTextures(1,&reflection_atlas->color); reflection_atlas->color=0; } reflection_atlas->size=size; for(int i=0;i<reflection_atlas->reflections.size();i++) { //erase probes reference to this if (reflection_atlas->reflections[i].owner.is_valid()) { ReflectionProbeInstance *reflection_probe_instance = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[i].owner); reflection_atlas->reflections[i].owner=RID(); ERR_CONTINUE(!reflection_probe_instance); reflection_probe_instance->reflection_atlas_index=-1; reflection_probe_instance->atlas=RID(); reflection_probe_instance->render_step=-1; } } if (reflection_atlas->size) { bool use_float=true; GLenum internal_format = use_float?GL_RGBA16F:GL_RGB10_A2; GLenum format = GL_RGBA; GLenum type = use_float?GL_HALF_FLOAT:GL_UNSIGNED_INT_2_10_10_10_REV; // Create a texture for storing the color glActiveTexture(GL_TEXTURE0); glGenTextures(1, &reflection_atlas->color); glBindTexture(GL_TEXTURE_2D, reflection_atlas->color); int mmsize=reflection_atlas->size; for(int i=0;i<6;i++) { glTexImage2D(GL_TEXTURE_2D, i, internal_format, mmsize, mmsize, 0, format, type, NULL); mmsize>>=1; } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_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); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 5); mmsize=reflection_atlas->size; for(int i=0;i<6;i++) { glGenFramebuffers(1, &reflection_atlas->fbo[i]); glBindFramebuffer(GL_FRAMEBUFFER, reflection_atlas->fbo[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, reflection_atlas->color, i); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE); glDisable(GL_SCISSOR_TEST); glViewport(0,0,mmsize,mmsize); glClearColor(0,0,0,0); glClear(GL_COLOR_BUFFER_BIT); //it needs to be cleared, to avoid generating garbage mmsize>>=1; } } } void RasterizerSceneGLES3::reflection_atlas_set_subdivision(RID p_ref_atlas,int p_subdiv) { ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_ref_atlas); ERR_FAIL_COND(!reflection_atlas); uint32_t subdiv = nearest_power_of_2(p_subdiv); if (subdiv&0xaaaaaaaa) { //sqrt(subdiv) must be integer subdiv<<=1; } subdiv=int(Math::sqrt((float)subdiv)); if (reflection_atlas->subdiv==subdiv) return; if (subdiv) { for(int i=0;i<reflection_atlas->reflections.size();i++) { //erase probes reference to this if (reflection_atlas->reflections[i].owner.is_valid()) { ReflectionProbeInstance *reflection_probe_instance = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[i].owner); reflection_atlas->reflections[i].owner=RID(); ERR_CONTINUE(!reflection_probe_instance); reflection_probe_instance->reflection_atlas_index=-1; reflection_probe_instance->atlas=RID(); reflection_probe_instance->render_step=-1; } } } reflection_atlas->subdiv=subdiv; reflection_atlas->reflections.resize(subdiv*subdiv); } //////////////////////////////////////////////////// RID RasterizerSceneGLES3::reflection_probe_instance_create(RID p_probe) { RasterizerStorageGLES3::ReflectionProbe *probe = storage->reflection_probe_owner.getornull(p_probe); ERR_FAIL_COND_V(!probe,RID()); ReflectionProbeInstance *rpi = memnew( ReflectionProbeInstance ); rpi->probe_ptr=probe; rpi->self=reflection_probe_instance_owner.make_rid(rpi); rpi->probe=p_probe; rpi->reflection_atlas_index=-1; rpi->render_step=-1; rpi->last_pass=0; return rpi->self; } void RasterizerSceneGLES3::reflection_probe_instance_set_transform(RID p_instance,const Transform& p_transform) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND(!rpi); rpi->transform=p_transform; } void RasterizerSceneGLES3::reflection_probe_release_atlas_index(RID p_instance) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND(!rpi); if (rpi->reflection_atlas_index==-1) return; ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(rpi->atlas); ERR_FAIL_COND(!reflection_atlas); ERR_FAIL_INDEX(rpi->reflection_atlas_index,reflection_atlas->reflections.size()); ERR_FAIL_COND(reflection_atlas->reflections[rpi->reflection_atlas_index].owner!=rpi->self); reflection_atlas->reflections[rpi->reflection_atlas_index].owner=RID(); rpi->reflection_atlas_index=-1; rpi->atlas=RID(); rpi->render_step=-1; } bool RasterizerSceneGLES3::reflection_probe_instance_needs_redraw(RID p_instance) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND_V(!rpi,false); return rpi->reflection_atlas_index==-1 || rpi->probe_ptr->update_mode==VS::REFLECTION_PROBE_UPDATE_ALWAYS; } bool RasterizerSceneGLES3::reflection_probe_instance_has_reflection(RID p_instance){ ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND_V(!rpi,false); return rpi->reflection_atlas_index!=-1; } bool RasterizerSceneGLES3::reflection_probe_instance_begin_render(RID p_instance,RID p_reflection_atlas) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND_V(!rpi,false); rpi->render_step=0; if (rpi->reflection_atlas_index!=-1) { return true; //got one already } ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas); ERR_FAIL_COND_V(!reflection_atlas,false); if (reflection_atlas->size==0 || reflection_atlas->subdiv==0) { return false; } int best_free=-1; int best_used=-1; uint64_t best_used_frame; for(int i=0;i<reflection_atlas->reflections.size();i++) { if (reflection_atlas->reflections[i].owner==RID()) { best_free=i; break; } if (rpi->render_step<0 && reflection_atlas->reflections[i].last_frame<storage->frame.count && (best_used==-1 || reflection_atlas->reflections[i].last_frame<best_used_frame)) { best_used=i; best_used_frame=reflection_atlas->reflections[i].last_frame; } } if (best_free==-1 && best_used==-1) { return false ;// sorry, can not do. Try again next frame. } if (best_free==-1) { //find best from what is used best_free=best_used; ReflectionProbeInstance *victim_rpi = reflection_probe_instance_owner.getornull(reflection_atlas->reflections[best_free].owner); ERR_FAIL_COND_V(!victim_rpi,false); victim_rpi->atlas=RID(); victim_rpi->reflection_atlas_index=-1; } reflection_atlas->reflections[best_free].owner=p_instance; reflection_atlas->reflections[best_free].last_frame=storage->frame.count; rpi->reflection_atlas_index=best_free; rpi->atlas=p_reflection_atlas; rpi->render_step=0; return true; } bool RasterizerSceneGLES3::reflection_probe_instance_postprocess_step(RID p_instance) { ReflectionProbeInstance *rpi = reflection_probe_instance_owner.getornull(p_instance); ERR_FAIL_COND_V(!rpi,true); ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(rpi->atlas); ERR_FAIL_COND_V(!reflection_atlas,false); ERR_FAIL_COND_V(rpi->render_step>=6,true); glBindFramebuffer(GL_FRAMEBUFFER,reflection_atlas->fbo[rpi->render_step]); state.cube_to_dp_shader.bind(); int target_size=reflection_atlas->size/reflection_atlas->subdiv; int cubemap_index=reflection_cubemaps.size()-1; for(int i=reflection_cubemaps.size()-1;i>=0;i--) { //find appropriate cubemap to render to if (reflection_cubemaps[i].size>target_size*2) break; cubemap_index=i; } glDisable(GL_BLEND); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP,reflection_cubemaps[cubemap_index].cubemap); glDisable(GL_CULL_FACE); storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DUAL_PARABOLOID,true); storage->shaders.cubemap_filter.bind(); int cell_size = reflection_atlas->size / reflection_atlas->subdiv; for(int i=0;i<rpi->render_step;i++) { cell_size>>=1; //mipmaps! } int x = (rpi->reflection_atlas_index % reflection_atlas->subdiv) * cell_size; int y = (rpi->reflection_atlas_index / reflection_atlas->subdiv) * cell_size; int width=cell_size; int height=cell_size; storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE,rpi->render_step==0); storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY,rpi->probe_ptr->update_mode==VS::REFLECTION_PROBE_UPDATE_ALWAYS); for(int i=0;i<2;i++) { storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::Z_FLIP,i>0); storage->shaders.cubemap_filter.set_uniform(CubemapFilterShaderGLES3::ROUGHNESS,rpi->render_step/5.0); uint32_t local_width=width,local_height=height; uint32_t local_x=x,local_y=y; local_height/=2; local_y+=i*local_height; glViewport(local_x,local_y,local_width,local_height); _copy_screen(); } storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::USE_DIRECT_WRITE,false); storage->shaders.cubemap_filter.set_conditional(CubemapFilterShaderGLES3::LOW_QUALITY,false); rpi->render_step++; return rpi->render_step==6; } /* ENVIRONMENT API */ RID RasterizerSceneGLES3::environment_create(){ Environment *env = memnew( Environment ); return environment_owner.make_rid(env); } void RasterizerSceneGLES3::environment_set_background(RID p_env,VS::EnvironmentBG p_bg){ Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->bg_mode=p_bg; } void RasterizerSceneGLES3::environment_set_skybox(RID p_env, RID p_skybox){ Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->skybox=p_skybox; } void RasterizerSceneGLES3::environment_set_skybox_scale(RID p_env,float p_scale) { Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->skybox_scale=p_scale; } void RasterizerSceneGLES3::environment_set_bg_color(RID p_env,const Color& p_color){ Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->bg_color=p_color; } void RasterizerSceneGLES3::environment_set_bg_energy(RID p_env,float p_energy) { Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->bg_energy=p_energy; } void RasterizerSceneGLES3::environment_set_canvas_max_layer(RID p_env,int p_max_layer){ Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->canvas_max_layer=p_max_layer; } void RasterizerSceneGLES3::environment_set_ambient_light(RID p_env, const Color& p_color, float p_energy, float p_skybox_contribution){ Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->ambient_color=p_color; env->ambient_energy=p_energy; env->ambient_skybox_contribution=p_skybox_contribution; } void RasterizerSceneGLES3::environment_set_dof_blur_far(RID p_env,bool p_enable,float p_distance,float p_transition,float p_amount,VS::EnvironmentDOFBlurQuality p_quality){ Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->dof_blur_far_enabled=p_enable; env->dof_blur_far_distance=p_distance; env->dof_blur_far_transition=p_transition; env->dof_blur_far_amount=p_amount; env->dof_blur_far_quality=p_quality; } void RasterizerSceneGLES3::environment_set_dof_blur_near(RID p_env,bool p_enable,float p_distance,float p_transition,float p_amount,VS::EnvironmentDOFBlurQuality p_quality){ Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->dof_blur_near_enabled=p_enable; env->dof_blur_near_distance=p_distance; env->dof_blur_near_transition=p_transition; env->dof_blur_near_amount=p_amount; env->dof_blur_near_quality=p_quality; } void RasterizerSceneGLES3::environment_set_glow(RID p_env, bool p_enable, int p_level_flags, float p_intensity, float p_strength, float p_bloom_treshold, VS::EnvironmentGlowBlendMode p_blend_mode, float p_hdr_bleed_treshold, float p_hdr_bleed_scale, bool p_bicubic_upscale) { Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->glow_enabled=p_enable; env->glow_levels=p_level_flags; env->glow_intensity=p_intensity; env->glow_strength=p_strength; env->glow_bloom=p_bloom_treshold; env->glow_blend_mode=p_blend_mode; env->glow_hdr_bleed_treshold=p_hdr_bleed_treshold; env->glow_hdr_bleed_scale=p_hdr_bleed_scale; env->glow_bicubic_upscale=p_bicubic_upscale; } void RasterizerSceneGLES3::environment_set_fog(RID p_env,bool p_enable,float p_begin,float p_end,RID p_gradient_texture){ } void RasterizerSceneGLES3::environment_set_ssr(RID p_env,bool p_enable, int p_max_steps,float p_accel,float p_fade,float p_depth_tolerance,bool p_smooth,bool p_roughness) { Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->ssr_enabled=p_enable; env->ssr_max_steps=p_max_steps; env->ssr_accel=p_accel; env->ssr_fade=p_fade; env->ssr_depth_tolerance=p_depth_tolerance; env->ssr_smooth=p_smooth; env->ssr_roughness=p_roughness; } void RasterizerSceneGLES3::environment_set_ssao(RID p_env,bool p_enable, float p_radius, float p_intensity, float p_radius2, float p_intensity2, float p_bias, float p_light_affect,const Color &p_color,bool p_blur) { Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->ssao_enabled=p_enable; env->ssao_radius=p_radius; env->ssao_intensity=p_intensity; env->ssao_radius2=p_radius2; env->ssao_intensity2=p_intensity2; env->ssao_bias=p_bias; env->ssao_light_affect=p_light_affect; env->ssao_color=p_color; env->ssao_filter=p_blur; } void RasterizerSceneGLES3::environment_set_tonemap(RID p_env,VS::EnvironmentToneMapper p_tone_mapper,float p_exposure,float p_white,bool p_auto_exposure,float p_min_luminance,float p_max_luminance,float p_auto_exp_speed,float p_auto_exp_scale) { Environment *env=environment_owner.getornull(p_env); ERR_FAIL_COND(!env); env->tone_mapper=p_tone_mapper; env->tone_mapper_exposure=p_exposure; env->tone_mapper_exposure_white=p_white; env->auto_exposure=p_auto_exposure; env->auto_exposure_speed=p_auto_exp_speed; env->auto_exposure_min=p_min_luminance; env->auto_exposure_max=p_max_luminance; env->auto_exposure_grey=p_auto_exp_scale; } void RasterizerSceneGLES3::environment_set_adjustment(RID p_env,bool p_enable,float p_brightness,float p_contrast,float p_saturation,RID p_ramp) { } RID RasterizerSceneGLES3::light_instance_create(RID p_light) { LightInstance *light_instance = memnew( LightInstance ); light_instance->last_pass=0; light_instance->last_scene_pass=0; light_instance->last_scene_shadow_pass=0; light_instance->light=p_light; light_instance->light_ptr=storage->light_owner.getornull(p_light); ERR_FAIL_COND_V(!light_instance->light_ptr,RID()); light_instance->self=light_instance_owner.make_rid(light_instance); return light_instance->self; } void RasterizerSceneGLES3::light_instance_set_transform(RID p_light_instance,const Transform& p_transform){ LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); ERR_FAIL_COND(!light_instance); light_instance->transform=p_transform; } void RasterizerSceneGLES3::light_instance_set_shadow_transform(RID p_light_instance,const CameraMatrix& p_projection,const Transform& p_transform,float p_far,float p_split,int p_pass) { LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); ERR_FAIL_COND(!light_instance); if (light_instance->light_ptr->type!=VS::LIGHT_DIRECTIONAL) { p_pass=0; } ERR_FAIL_INDEX(p_pass,4); light_instance->shadow_transform[p_pass].camera=p_projection; light_instance->shadow_transform[p_pass].transform=p_transform; light_instance->shadow_transform[p_pass].farplane=p_far; light_instance->shadow_transform[p_pass].split=p_split; } void RasterizerSceneGLES3::light_instance_mark_visible(RID p_light_instance) { LightInstance *light_instance = light_instance_owner.getornull(p_light_instance); ERR_FAIL_COND(!light_instance); light_instance->last_scene_pass=scene_pass; } ////////////////////// RID RasterizerSceneGLES3::gi_probe_instance_create() { GIProbeInstance *gipi = memnew(GIProbeInstance); return gi_probe_instance_owner.make_rid(gipi); } void RasterizerSceneGLES3::gi_probe_instance_set_light_data(RID p_probe, RID p_base, RID p_data) { GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe); ERR_FAIL_COND(!gipi); gipi->data=p_data; gipi->probe=storage->gi_probe_owner.getornull(p_base); if (p_data.is_valid()) { RasterizerStorageGLES3::GIProbeData *gipd = storage->gi_probe_data_owner.getornull(p_data); ERR_FAIL_COND(!gipd); if (gipd) { gipi->tex_cache=gipd->tex_id; gipi->cell_size_cache.x=1.0/gipd->width; gipi->cell_size_cache.y=1.0/gipd->height; gipi->cell_size_cache.z=1.0/gipd->depth; } } } void RasterizerSceneGLES3::gi_probe_instance_set_transform_to_data(RID p_probe,const Transform& p_xform) { GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe); ERR_FAIL_COND(!gipi); gipi->transform_to_data=p_xform; } void RasterizerSceneGLES3::gi_probe_instance_set_bounds(RID p_probe,const Vector3& p_bounds) { GIProbeInstance *gipi = gi_probe_instance_owner.getornull(p_probe); ERR_FAIL_COND(!gipi); gipi->bounds=p_bounds; } //////////////////////////// //////////////////////////// //////////////////////////// bool RasterizerSceneGLES3::_setup_material(RasterizerStorageGLES3::Material* p_material,bool p_alpha_pass) { if (p_material->shader->spatial.cull_mode==RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_DISABLED) { glDisable(GL_CULL_FACE); } else { glEnable(GL_CULL_FACE); } if (state.current_line_width!=p_material->line_width) { //glLineWidth(MAX(p_material->line_width,1.0)); state.current_line_width=p_material->line_width; } if (state.current_depth_draw!=p_material->shader->spatial.depth_draw_mode) { switch(p_material->shader->spatial.depth_draw_mode) { case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS: case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_OPAQUE: { glDepthMask(!p_alpha_pass); } break; case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALWAYS: { glDepthMask(GL_TRUE); } break; case RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_NEVER: { glDepthMask(GL_FALSE); } break; } state.current_depth_draw=p_material->shader->spatial.depth_draw_mode; } //glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); /* if (p_material->flags[VS::MATERIAL_FLAG_WIREFRAME]) glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); if (p_material->line_width) glLineWidth(p_material->line_width); */ #if 0 //blend mode if (state.current_blend_mode!=p_material->shader->spatial.blend_mode) { switch(p_material->shader->spatial.blend_mode) { case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(p_alpha_pass?GL_SRC_ALPHA:GL_ONE,GL_ONE); } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_SUB: { glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); glBlendFunc(GL_SRC_ALPHA,GL_ONE); } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MUL: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } break; } state.current_blend_mode=p_material->shader->spatial.blend_mode; } #endif //material parameters state.scene_shader.set_custom_shader(p_material->shader->custom_code_id); bool rebind = state.scene_shader.bind(); if (p_material->ubo_id) { glBindBufferBase(GL_UNIFORM_BUFFER,1,p_material->ubo_id); } int tc = p_material->textures.size(); RID* textures = p_material->textures.ptr(); ShaderLanguage::ShaderNode::Uniform::Hint* texture_hints = p_material->shader->texture_hints.ptr(); state.current_main_tex=0; for(int i=0;i<tc;i++) { glActiveTexture(GL_TEXTURE0+i); GLenum target; GLuint tex; RasterizerStorageGLES3::Texture *t = storage->texture_owner.getornull( textures[i] ); if (!t) { //check hints target=GL_TEXTURE_2D; switch(texture_hints[i]) { case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: { tex=storage->resources.black_tex; } break; case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: { tex=storage->resources.aniso_tex; } break; case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: { tex=storage->resources.normal_tex; } break; default: { tex=storage->resources.white_tex; } break; } } else { if (storage->config.srgb_decode_supported) { //if SRGB decode extension is present, simply switch the texture to whathever is needed bool must_srgb=false; if (t->srgb && (texture_hints[i]==ShaderLanguage::ShaderNode::Uniform::HINT_ALBEDO || texture_hints[i]==ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO)) { must_srgb=true; } if (t->using_srgb!=must_srgb) { if (must_srgb) { glTexParameteri(t->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT); #ifdef TOOLS_ENABLED if (!(t->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) { t->flags|=VS::TEXTURE_FLAG_CONVERT_TO_LINEAR; //notify that texture must be set to linear beforehand, so it works in other platforms when exported } #endif } else { glTexParameteri(t->target,_TEXTURE_SRGB_DECODE_EXT,_SKIP_DECODE_EXT); } t->using_srgb=must_srgb; } } target=t->target; tex = t->tex_id; } glBindTexture(target,tex); if (i==0) { state.current_main_tex=tex; } } return rebind; } void RasterizerSceneGLES3::_setup_geometry(RenderList::Element *e) { switch(e->instance->base_type) { case VS::INSTANCE_MESH: { RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface*>(e->geometry); if (s->blend_shapes.size() && e->instance->blend_values.size()) { //blend shapes, use transform feedback storage->mesh_render_blend_shapes(s,e->instance->blend_values.ptr()); //rebind shader state.scene_shader.bind(); } else { glBindVertexArray(s->array_id); // everything is so easy nowadays } } break; case VS::INSTANCE_MULTIMESH: { RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh*>(e->owner); RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface*>(e->geometry); glBindVertexArray(s->instancing_array_id); // use the instancing array ID glBindBuffer(GL_ARRAY_BUFFER,multi_mesh->buffer); //modify the buffer int stride = (multi_mesh->xform_floats+multi_mesh->color_floats)*4; glEnableVertexAttribArray(8); glVertexAttribPointer(8,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+0); glVertexAttribDivisor(8,1); glEnableVertexAttribArray(9); glVertexAttribPointer(9,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+4*4); glVertexAttribDivisor(9,1); int color_ofs; if (multi_mesh->transform_format==VS::MULTIMESH_TRANSFORM_3D) { glEnableVertexAttribArray(10); glVertexAttribPointer(10,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+8*4); glVertexAttribDivisor(10,1); color_ofs=12*4; } else { glDisableVertexAttribArray(10); glVertexAttrib4f(10,0,0,1,0); color_ofs=8*4; } switch(multi_mesh->color_format) { case VS::MULTIMESH_COLOR_NONE: { glDisableVertexAttribArray(11); glVertexAttrib4f(11,1,1,1,1); } break; case VS::MULTIMESH_COLOR_8BIT: { glEnableVertexAttribArray(11); glVertexAttribPointer(11,4,GL_UNSIGNED_BYTE,GL_TRUE,stride,((uint8_t*)NULL)+color_ofs); glVertexAttribDivisor(11,1); } break; case VS::MULTIMESH_COLOR_FLOAT: { glEnableVertexAttribArray(11); glVertexAttribPointer(11,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+color_ofs); glVertexAttribDivisor(11,1); } break; } } break; } } static const GLenum gl_primitive[]={ GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_TRIANGLE_STRIP, GL_TRIANGLE_FAN }; void RasterizerSceneGLES3::_render_geometry(RenderList::Element *e) { switch(e->instance->base_type) { case VS::INSTANCE_MESH: { RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface*>(e->geometry); if (s->index_array_len>0) { glDrawElements(gl_primitive[s->primitive],s->index_array_len, (s->array_len>=(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT,0); storage->info.render_vertices_count+=s->index_array_len; } else { glDrawArrays(gl_primitive[s->primitive],0,s->array_len); storage->info.render_vertices_count+=s->array_len; } } break; case VS::INSTANCE_MULTIMESH: { RasterizerStorageGLES3::MultiMesh *multi_mesh = static_cast<RasterizerStorageGLES3::MultiMesh*>(e->owner); RasterizerStorageGLES3::Surface *s = static_cast<RasterizerStorageGLES3::Surface*>(e->geometry); int amount = MAX(multi_mesh->size,multi_mesh->visible_instances); if (s->index_array_len>0) { glDrawElementsInstanced(gl_primitive[s->primitive],s->index_array_len, (s->array_len>=(1<<16))?GL_UNSIGNED_INT:GL_UNSIGNED_SHORT,0,amount); storage->info.render_vertices_count+=s->index_array_len * amount; } else { glDrawArraysInstanced(gl_primitive[s->primitive],0,s->array_len,amount); storage->info.render_vertices_count+=s->array_len * amount; } } break; case VS::INSTANCE_IMMEDIATE: { bool restore_tex=false; const RasterizerStorageGLES3::Immediate *im = static_cast<const RasterizerStorageGLES3::Immediate*>( e->geometry ); if (im->building) { return; } glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer); glBindVertexArray(state.immediate_array); for(const List< RasterizerStorageGLES3::Immediate::Chunk>::Element *E=im->chunks.front();E;E=E->next()) { const RasterizerStorageGLES3::Immediate::Chunk &c=E->get(); if (c.vertices.empty()) { continue; } int vertices = c.vertices.size(); uint32_t buf_ofs=0; storage->info.render_vertices_count+=vertices; if (c.texture.is_valid() && storage->texture_owner.owns(c.texture)) { const RasterizerStorageGLES3::Texture *t = storage->texture_owner.get(c.texture); glActiveTexture(GL_TEXTURE0); glBindTexture(t->target,t->tex_id); restore_tex=true; } else if (restore_tex) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,state.current_main_tex); restore_tex=false; } if (!c.normals.empty()) { glEnableVertexAttribArray(VS::ARRAY_NORMAL); glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector3)*vertices,c.normals.ptr()); glVertexAttribPointer(VS::ARRAY_NORMAL, 3, GL_FLOAT, false,sizeof(Vector3)*vertices,((uint8_t*)NULL)+buf_ofs); buf_ofs+=sizeof(Vector3)*vertices; } else { glDisableVertexAttribArray(VS::ARRAY_NORMAL); } if (!c.tangents.empty()) { glEnableVertexAttribArray(VS::ARRAY_TANGENT); glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Plane)*vertices,c.tangents.ptr()); glVertexAttribPointer(VS::ARRAY_TANGENT, 4, GL_FLOAT, false,sizeof(Plane)*vertices,((uint8_t*)NULL)+buf_ofs); buf_ofs+=sizeof(Plane)*vertices; } else { glDisableVertexAttribArray(VS::ARRAY_TANGENT); } if (!c.colors.empty()) { glEnableVertexAttribArray(VS::ARRAY_COLOR); glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Color)*vertices,c.colors.ptr()); glVertexAttribPointer(VS::ARRAY_COLOR, 4, GL_FLOAT, false,sizeof(Color),((uint8_t*)NULL)+buf_ofs); buf_ofs+=sizeof(Color)*vertices; } else { glDisableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1); } if (!c.uvs.empty()) { glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector2)*vertices,c.uvs.ptr()); glVertexAttribPointer(VS::ARRAY_TEX_UV, 2, GL_FLOAT, false,sizeof(Vector2),((uint8_t*)NULL)+buf_ofs); buf_ofs+=sizeof(Vector2)*vertices; } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV); } if (!c.uvs2.empty()) { glEnableVertexAttribArray(VS::ARRAY_TEX_UV2); glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector2)*vertices,c.uvs2.ptr()); glVertexAttribPointer(VS::ARRAY_TEX_UV2, 2, GL_FLOAT, false,sizeof(Vector2),((uint8_t*)NULL)+buf_ofs); buf_ofs+=sizeof(Vector2)*vertices; } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV2); } glEnableVertexAttribArray(VS::ARRAY_VERTEX); glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector3)*vertices,c.vertices.ptr()); glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false,sizeof(Vector3),((uint8_t*)NULL)+buf_ofs); glDrawArrays(gl_primitive[c.primitive],0,c.vertices.size()); } if (restore_tex) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,state.current_main_tex); restore_tex=false; } } break; } } void RasterizerSceneGLES3::_setup_light(RenderList::Element *e,const Transform& p_view_transform) { int omni_indices[16]; int omni_count=0; int spot_indices[16]; int spot_count=0; int reflection_indices[16]; int reflection_count=0; int maxobj = MIN(16,state.max_forward_lights_per_object); int lc = e->instance->light_instances.size(); if (lc) { const RID* lights=e->instance->light_instances.ptr(); for(int i=0;i<lc;i++) { LightInstance *li=light_instance_owner.getptr(lights[i]); if (li->last_pass!=render_pass) //not visible continue; if (li->light_ptr->type==VS::LIGHT_OMNI) { if (omni_count<maxobj && e->instance->layer_mask&li->light_ptr->cull_mask) { omni_indices[omni_count++]=li->light_index; } } if (li->light_ptr->type==VS::LIGHT_SPOT) { if (spot_count<maxobj && e->instance->layer_mask&li->light_ptr->cull_mask) { spot_indices[spot_count++]=li->light_index; } } } } state.scene_shader.set_uniform(SceneShaderGLES3::OMNI_LIGHT_COUNT,omni_count); if (omni_count) { glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::OMNI_LIGHT_INDICES),omni_count,omni_indices); } state.scene_shader.set_uniform(SceneShaderGLES3::SPOT_LIGHT_COUNT,spot_count); if (spot_count) { glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::SPOT_LIGHT_INDICES),spot_count,spot_indices); } int rc = e->instance->reflection_probe_instances.size(); if (rc) { const RID* reflections=e->instance->reflection_probe_instances.ptr(); for(int i=0;i<rc;i++) { ReflectionProbeInstance *rpi=reflection_probe_instance_owner.getptr(reflections[i]); if (rpi->last_pass!=render_pass) //not visible continue; if (reflection_count<maxobj) { reflection_indices[reflection_count++]=rpi->reflection_index; } } } state.scene_shader.set_uniform(SceneShaderGLES3::REFLECTION_COUNT,reflection_count); if (reflection_count) { glUniform1iv(state.scene_shader.get_uniform(SceneShaderGLES3::REFLECTION_INDICES),reflection_count,reflection_indices); } int gi_probe_count = e->instance->gi_probe_instances.size(); if (gi_probe_count) { const RID * ridp = e->instance->gi_probe_instances.ptr(); GIProbeInstance *gipi = gi_probe_instance_owner.getptr(ridp[0]); glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-6); glBindTexture(GL_TEXTURE_3D,gipi->tex_cache); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_XFORM1, gipi->transform_to_data * p_view_transform); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BOUNDS1, gipi->bounds); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER1, gipi->probe?gipi->probe->dynamic_range*gipi->probe->energy:0.0); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT1, gipi->probe?!gipi->probe->interior:false); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_CELL_SIZE1, gipi->cell_size_cache); if (gi_probe_count>1) { GIProbeInstance *gipi2 = gi_probe_instance_owner.getptr(ridp[1]); glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-7); glBindTexture(GL_TEXTURE_3D,gipi2->tex_cache); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_XFORM2, gipi2->transform_to_data * p_view_transform); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BOUNDS2, gipi2->bounds); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_CELL_SIZE2, gipi2->cell_size_cache); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_MULTIPLIER2, gipi2->probe?gipi2->probe->dynamic_range*gipi2->probe->energy:0.0); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE_BLEND_AMBIENT2, gipi2->probe?!gipi2->probe->interior:false); state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, true ); } else { state.scene_shader.set_uniform(SceneShaderGLES3::GI_PROBE2_ENABLED, false ); } } } void RasterizerSceneGLES3::_setup_transform(InstanceBase *p_instance,const Transform& p_view_transform,const CameraMatrix& p_projection) { if (p_instance->billboard || p_instance->billboard_y || p_instance->depth_scale) { Transform xf=p_instance->transform; if (p_instance->depth_scale) { if (p_projection.matrix[3][3]) { //orthogonal matrix, try to do about the same //with viewport size //real_t w = Math::abs( 1.0/(2.0*(p_projection.matrix[0][0])) ); real_t h = Math::abs( 1.0/(2.0*p_projection.matrix[1][1]) ); float sc = (h*2.0); //consistent with Y-fov xf.basis.scale( Vector3(sc,sc,sc)); } else { //just scale by depth real_t sc = Plane(p_view_transform.origin,-p_view_transform.get_basis().get_axis(2)).distance_to(xf.origin); xf.basis.scale( Vector3(sc,sc,sc)); } } if (p_instance->billboard && storage->frame.current_rt) { Vector3 scale = xf.basis.get_scale(); if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) { xf.set_look_at(xf.origin, xf.origin + p_view_transform.get_basis().get_axis(2), -p_view_transform.get_basis().get_axis(1)); } else { xf.set_look_at(xf.origin, xf.origin + p_view_transform.get_basis().get_axis(2), p_view_transform.get_basis().get_axis(1)); } xf.basis.scale(scale); } if (p_instance->billboard_y && storage->frame.current_rt) { Vector3 scale = xf.basis.get_scale(); Vector3 look_at = p_view_transform.get_origin(); look_at.y = 0.0; Vector3 look_at_norm = look_at.normalized(); if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) { xf.set_look_at(xf.origin,xf.origin + look_at_norm, Vector3(0.0, -1.0, 0.0)); } else { xf.set_look_at(xf.origin,xf.origin + look_at_norm, Vector3(0.0, 1.0, 0.0)); } xf.basis.scale(scale); } state.scene_shader.set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, xf); } else { state.scene_shader.set_uniform(SceneShaderGLES3::WORLD_TRANSFORM, p_instance->transform); } } void RasterizerSceneGLES3::_set_cull(bool p_front,bool p_reverse_cull) { bool front = p_front; if (p_reverse_cull) front=!front; if (front!=state.cull_front) { glCullFace(front?GL_FRONT:GL_BACK); state.cull_front=front; } } void RasterizerSceneGLES3::_render_list(RenderList::Element **p_elements,int p_element_count,const Transform& p_view_transform,const CameraMatrix& p_projection,GLuint p_base_env,bool p_reverse_cull,bool p_alpha_pass,bool p_shadow,bool p_directional_add,bool p_directional_shadows) { if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) { //p_reverse_cull=!p_reverse_cull; glFrontFace(GL_CCW); } else { glFrontFace(GL_CW); } glBindBufferBase(GL_UNIFORM_BUFFER,0,state.scene_ubo); //bind globals ubo if (!p_shadow && !p_directional_add) { glBindBufferBase(GL_UNIFORM_BUFFER,2,state.env_radiance_ubo); //bind environment radiance info glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-1); glBindTexture(GL_TEXTURE_2D,state.brdf_texture); if (p_base_env) { glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-2); glBindTexture(GL_TEXTURE_2D,p_base_env); state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP,true); } else { state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP,false); } } else { state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP,false); } state.cull_front=false; glCullFace(GL_BACK); state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON,false); state.current_blend_mode=-1; state.current_line_width=-1; state.current_depth_draw=-1; RasterizerStorageGLES3::Material* prev_material=NULL; RasterizerStorageGLES3::Geometry* prev_geometry=NULL; VS::InstanceType prev_base_type = VS::INSTANCE_MAX; int current_blend_mode=-1; int prev_shading=-1; RID prev_skeleton; state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,true); //by default unshaded (easier to set) bool first=true; storage->info.render_object_count+=p_element_count; for (int i=0;i<p_element_count;i++) { RenderList::Element *e = p_elements[i]; RasterizerStorageGLES3::Material* material= e->material; RID skeleton = e->instance->skeleton; bool rebind=first; int shading = (e->sort_key>>RenderList::SORT_KEY_SHADING_SHIFT)&RenderList::SORT_KEY_SHADING_MASK; if (!p_shadow) { if (p_directional_add) { if (e->sort_key&RenderList::SORT_KEY_UNSHADED_FLAG || !(e->instance->layer_mask&directional_light->light_ptr->cull_mask)) { continue; } shading&=~1; //ignore the ignore directional for base pass } if (shading!=prev_shading) { if (e->sort_key&RenderList::SORT_KEY_UNSHADED_FLAG) { state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,true); state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5,false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES,false); //state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,true); } else { state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES,e->instance->gi_probe_instances.size()>0); state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING,!p_directional_add); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5,shadow_filter_mode==SHADOW_FILTER_PCF5); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13,shadow_filter_mode==SHADOW_FILTER_PCF13); if (p_directional_add || (directional_light && (e->sort_key&RenderList::SORT_KEY_NO_DIRECTIONAL_FLAG)==0)) { state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL,true); if (p_directional_shadows && directional_light->light_ptr->shadow) { state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW,true); switch(directional_light->light_ptr->directional_shadow_mode) { case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: break; //none case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2,true); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,directional_light->light_ptr->directional_blend_splits); break; case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4,true); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,directional_light->light_ptr->directional_blend_splits); break; } } } } rebind=true; } if (p_alpha_pass || p_directional_add) { int desired_blend_mode; if (p_directional_add) { desired_blend_mode=RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD; } else { desired_blend_mode=material->shader->spatial.blend_mode; } if (desired_blend_mode!=current_blend_mode) { switch(desired_blend_mode) { case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_ADD: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(p_alpha_pass?GL_SRC_ALPHA:GL_ONE,GL_ONE); } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_SUB: { glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); glBlendFunc(GL_SRC_ALPHA,GL_ONE); } break; case RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MUL: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } break; } current_blend_mode=desired_blend_mode; } } } if (prev_skeleton!=skeleton) { if (prev_skeleton.is_valid() != skeleton.is_valid()) { state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON,skeleton.is_valid()); rebind=true; } if (skeleton.is_valid()) { RasterizerStorageGLES3::Skeleton *sk = storage->skeleton_owner.getornull(skeleton); if (sk->size) { glBindBufferBase(GL_UNIFORM_BUFFER,7,sk->ubo); } } } if ((prev_base_type==VS::INSTANCE_MULTIMESH) != (e->instance->base_type==VS::INSTANCE_MULTIMESH)) { state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING,e->instance->base_type==VS::INSTANCE_MULTIMESH); rebind=true; } if (material!=prev_material || rebind) { storage->info.render_material_switch_count++; rebind = _setup_material(material,p_alpha_pass); if (rebind) { storage->info.render_shader_rebind_count++; } } if (!(e->sort_key&RenderList::SORT_KEY_UNSHADED_FLAG) && !p_directional_add && !p_shadow) { _setup_light(e,p_view_transform); } if (prev_base_type != e->instance->base_type || prev_geometry!=e->geometry) { _setup_geometry(e); storage->info.render_surface_switch_count++; } _set_cull(e->sort_key&RenderList::SORT_KEY_MIRROR_FLAG,p_reverse_cull); state.scene_shader.set_uniform(SceneShaderGLES3::NORMAL_MULT, e->instance->mirror?-1.0:1.0); _setup_transform(e->instance,p_view_transform,p_projection); _render_geometry(e); prev_material=material; prev_base_type=e->instance->base_type; prev_geometry=e->geometry; prev_shading=shading; prev_skeleton=skeleton; first=false; } glFrontFace(GL_CW); glBindVertexArray(0); state.scene_shader.set_conditional(SceneShaderGLES3::USE_INSTANCING,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_SKELETON,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_RADIANCE_MAP,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_FORWARD_LIGHTING,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_LIGHT_DIRECTIONAL,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_DIRECTIONAL_SHADOW,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM4,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM2,false); state.scene_shader.set_conditional(SceneShaderGLES3::LIGHT_USE_PSSM_BLEND,false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADELESS,false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_5,false); state.scene_shader.set_conditional(SceneShaderGLES3::SHADOW_MODE_PCF_13,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_GI_PROBES,false); } void RasterizerSceneGLES3::_add_geometry( RasterizerStorageGLES3::Geometry* p_geometry, InstanceBase *p_instance, RasterizerStorageGLES3::GeometryOwner *p_owner,int p_material,bool p_shadow) { RasterizerStorageGLES3::Material *m=NULL; RID m_src=p_instance->material_override.is_valid() ? p_instance->material_override :(p_material>=0?p_instance->materials[p_material]:p_geometry->material); /* #ifdef DEBUG_ENABLED if (current_debug==VS::SCENARIO_DEBUG_OVERDRAW) { m_src=overdraw_material; } #endif */ if (m_src.is_valid()) { m=storage->material_owner.getornull( m_src ); if (!m->shader) { m=NULL; } } if (!m) { m=storage->material_owner.getptr( default_material ); } ERR_FAIL_COND(!m); bool has_base_alpha=(m->shader->spatial.uses_alpha); bool has_blend_alpha=m->shader->spatial.blend_mode!=RasterizerStorageGLES3::Shader::Spatial::BLEND_MODE_MIX || m->shader->spatial.ontop; bool has_alpha = has_base_alpha || has_blend_alpha; bool shadow = false; bool mirror = p_instance->mirror; if (m->shader->spatial.cull_mode==RasterizerStorageGLES3::Shader::Spatial::CULL_MODE_FRONT) { mirror=!mirror; } if (m->shader->spatial.uses_sss) { state.used_sss=true; } if (p_shadow) { if (has_blend_alpha || (has_base_alpha && m->shader->spatial.depth_draw_mode!=RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS)) return; //bye if (!m->shader->spatial.uses_vertex && !m->shader->spatial.uses_discard && m->shader->spatial.depth_draw_mode!=RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) { //shader does not use discard and does not write a vertex position, use generic material if (p_instance->cast_shadows == VS::SHADOW_CASTING_SETTING_DOUBLE_SIDED) m = storage->material_owner.getptr(default_material_twosided); else m = storage->material_owner.getptr(default_material); } has_alpha=false; } RenderList::Element *e = has_alpha ? render_list.add_alpha_element() : render_list.add_element(); if (!e) return; e->geometry=p_geometry; e->material=m; e->instance=p_instance; e->owner=p_owner; e->sort_key=0; if (e->geometry->last_pass!=render_pass) { e->geometry->last_pass=render_pass; e->geometry->index=current_geometry_index++; } if (!p_shadow && directional_light && (directional_light->light_ptr->cull_mask&e->instance->layer_mask)==0) { e->sort_key|=RenderList::SORT_KEY_NO_DIRECTIONAL_FLAG; } e->sort_key|=uint64_t(e->geometry->index)<<RenderList::SORT_KEY_GEOMETRY_INDEX_SHIFT; e->sort_key|=uint64_t(e->instance->base_type)<<RenderList::SORT_KEY_GEOMETRY_TYPE_SHIFT; if (!p_shadow) { if (e->material->last_pass!=render_pass) { e->material->last_pass=render_pass; e->material->index=current_material_index++; } e->sort_key|=uint64_t(e->material->index)<<RenderList::SORT_KEY_MATERIAL_INDEX_SHIFT; e->sort_key|=uint64_t(e->instance->depth_layer)<<RenderList::SORT_KEY_DEPTH_LAYER_SHIFT; if (!has_blend_alpha && has_alpha && m->shader->spatial.depth_draw_mode==RasterizerStorageGLES3::Shader::Spatial::DEPTH_DRAW_ALPHA_PREPASS) { //if nothing exists, add this element as opaque too RenderList::Element *oe = render_list.add_element(); if (!oe) return; copymem(oe,e,sizeof(RenderList::Element)); } if (e->instance->gi_probe_instances.size()) { e->sort_key|=RenderList::SORT_KEY_GI_PROBES_FLAG; } } /* if (e->geometry->type==RasterizerStorageGLES3::Geometry::GEOMETRY_MULTISURFACE) e->sort_flags|=RenderList::SORT_FLAG_INSTANCING; */ if (mirror) { e->sort_key|=RenderList::SORT_KEY_MIRROR_FLAG; } //e->light_type=0xFF; // no lights! if (shadow || m->shader->spatial.unshaded /*|| current_debug==VS::SCENARIO_DEBUG_SHADELESS*/) { e->sort_key|=RenderList::SORT_KEY_UNSHADED_FLAG; } } void RasterizerSceneGLES3::_draw_skybox(RasterizerStorageGLES3::SkyBox *p_skybox,const CameraMatrix& p_projection,const Transform& p_transform,bool p_vflip,float p_scale) { if (!p_skybox) return; RasterizerStorageGLES3::Texture *tex = storage->texture_owner.getornull(p_skybox->cubemap); ERR_FAIL_COND(!tex); glActiveTexture(GL_TEXTURE0); glBindTexture(tex->target,tex->tex_id); if (storage->config.srgb_decode_supported && tex->srgb && !tex->using_srgb) { glTexParameteri(tex->target,_TEXTURE_SRGB_DECODE_EXT,_DECODE_EXT); tex->using_srgb=true; #ifdef TOOLS_ENABLED if (!(tex->flags&VS::TEXTURE_FLAG_CONVERT_TO_LINEAR)) { tex->flags|=VS::TEXTURE_FLAG_CONVERT_TO_LINEAR; //notify that texture must be set to linear beforehand, so it works in other platforms when exported } #endif } glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); glDepthFunc(GL_LEQUAL); glColorMask(1,1,1,1); float flip_sign = p_vflip?-1:1; Vector3 vertices[8]={ Vector3(-1,-1*flip_sign,1), Vector3( 0, 1, 0), Vector3( 1,-1*flip_sign,1), Vector3( 1, 1, 0), Vector3( 1, 1*flip_sign,1), Vector3( 1, 0, 0), Vector3(-1, 1*flip_sign,1), Vector3( 0, 0, 0) }; //skybox uv vectors float vw,vh,zn; p_projection.get_viewport_size(vw,vh); zn=p_projection.get_z_near(); float scale=p_scale; for(int i=0;i<4;i++) { Vector3 uv=vertices[i*2+1]; uv.x=(uv.x*2.0-1.0)*vw*scale; uv.y=-(uv.y*2.0-1.0)*vh*scale; uv.z=-zn; vertices[i*2+1] = p_transform.basis.xform(uv).normalized(); vertices[i*2+1].z = -vertices[i*2+1].z; } glBindBuffer(GL_ARRAY_BUFFER,state.skybox_verts); glBufferSubData(GL_ARRAY_BUFFER,0,sizeof(Vector3)*8,vertices); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind glBindVertexArray(state.skybox_array); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_CUBEMAP,true); storage->shaders.copy.bind(); glDrawArrays(GL_TRIANGLE_FAN,0,4); glBindVertexArray(0); glColorMask(1,1,1,1); storage->shaders.copy.set_conditional(CopyShaderGLES3::USE_CUBEMAP,false); } void RasterizerSceneGLES3::_setup_environment(Environment *env,const CameraMatrix& p_cam_projection,const Transform& p_cam_transform) { //store camera into ubo store_camera(p_cam_projection,state.ubo_data.projection_matrix); store_transform(p_cam_transform,state.ubo_data.camera_matrix); store_transform(p_cam_transform.affine_inverse(),state.ubo_data.camera_inverse_matrix); //time global variables for(int i=0;i<4;i++) { state.ubo_data.time[i]=storage->frame.time[i]; } //bg and ambient if (env) { state.ubo_data.bg_energy=env->bg_energy; state.ubo_data.ambient_energy=env->ambient_energy; Color linear_ambient_color = env->ambient_color.to_linear(); state.ubo_data.ambient_light_color[0]=linear_ambient_color.r; state.ubo_data.ambient_light_color[1]=linear_ambient_color.g; state.ubo_data.ambient_light_color[2]=linear_ambient_color.b; state.ubo_data.ambient_light_color[3]=linear_ambient_color.a; Color bg_color; switch(env->bg_mode) { case VS::ENV_BG_CLEAR_COLOR: { bg_color=storage->frame.clear_request_color.to_linear(); } break; case VS::ENV_BG_COLOR: { bg_color=env->bg_color.to_linear(); } break; default: { bg_color=Color(0,0,0,1); } break; } state.ubo_data.bg_color[0]=bg_color.r; state.ubo_data.bg_color[1]=bg_color.g; state.ubo_data.bg_color[2]=bg_color.b; state.ubo_data.bg_color[3]=bg_color.a; state.env_radiance_data.ambient_contribution=env->ambient_skybox_contribution; state.ubo_data.ambient_occlusion_affect_light=env->ssao_light_affect; } else { state.ubo_data.bg_energy=1.0; state.ubo_data.ambient_energy=1.0; //use from clear color instead, since there is no ambient Color linear_ambient_color = storage->frame.clear_request_color.to_linear(); state.ubo_data.ambient_light_color[0]=linear_ambient_color.r; state.ubo_data.ambient_light_color[1]=linear_ambient_color.g; state.ubo_data.ambient_light_color[2]=linear_ambient_color.b; state.ubo_data.ambient_light_color[3]=linear_ambient_color.a; state.ubo_data.bg_color[0]=linear_ambient_color.r; state.ubo_data.bg_color[1]=linear_ambient_color.g; state.ubo_data.bg_color[2]=linear_ambient_color.b; state.ubo_data.bg_color[3]=linear_ambient_color.a; state.env_radiance_data.ambient_contribution=0; state.ubo_data.ambient_occlusion_affect_light=0; } { //directional shadow state.ubo_data.shadow_directional_pixel_size[0]=1.0/directional_shadow.size; state.ubo_data.shadow_directional_pixel_size[1]=1.0/directional_shadow.size; glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-4); glBindTexture(GL_TEXTURE_2D,directional_shadow.depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS); } glBindBuffer(GL_UNIFORM_BUFFER, state.scene_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0,sizeof(State::SceneDataUBO), &state.ubo_data); glBindBuffer(GL_UNIFORM_BUFFER, 0); //fill up environment store_transform(p_cam_transform,state.env_radiance_data.transform); glBindBuffer(GL_UNIFORM_BUFFER, state.env_radiance_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0,sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_data); glBindBuffer(GL_UNIFORM_BUFFER, 0); } void RasterizerSceneGLES3::_setup_directional_light(int p_index,const Transform& p_camera_inverse_transform,bool p_use_shadows) { LightInstance *li = directional_lights[p_index]; LightDataUBO ubo_data; //used for filling float sign = li->light_ptr->negative?-1:1; Color linear_col = li->light_ptr->color.to_linear(); ubo_data.light_color_energy[0]=linear_col.r*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[1]=linear_col.g*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[2]=linear_col.b*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[3]=0; //omni, keep at 0 ubo_data.light_pos_inv_radius[0]=0.0; ubo_data.light_pos_inv_radius[1]=0.0; ubo_data.light_pos_inv_radius[2]=0.0; ubo_data.light_pos_inv_radius[3]=0.0; Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0,0,-1))).normalized(); ubo_data.light_direction_attenuation[0]=direction.x; ubo_data.light_direction_attenuation[1]=direction.y; ubo_data.light_direction_attenuation[2]=direction.z; ubo_data.light_direction_attenuation[3]=1.0; ubo_data.light_params[0]=0; ubo_data.light_params[1]=li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR]; ubo_data.light_params[2]=0; ubo_data.light_params[3]=0; Color shadow_color = li->light_ptr->shadow_color.to_linear(); ubo_data.light_shadow_color[0]=shadow_color.r; ubo_data.light_shadow_color[1]=shadow_color.g; ubo_data.light_shadow_color[2]=shadow_color.b; ubo_data.light_shadow_color[3]=1.0; if (p_use_shadows && li->light_ptr->shadow) { int shadow_count=0; switch(li->light_ptr->directional_shadow_mode) { case VS::LIGHT_DIRECTIONAL_SHADOW_ORTHOGONAL: { shadow_count=1; } break; case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS: { shadow_count=2; } break; case VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS: { shadow_count=4; } break; } for(int j=0;j<shadow_count;j++) { uint32_t x=li->directional_rect.pos.x; uint32_t y=li->directional_rect.pos.y; uint32_t width=li->directional_rect.size.x; uint32_t height=li->directional_rect.size.y; if (li->light_ptr->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) { width/=2; height/=2; if (j==0) { } else if (j==1) { x+=width; } else if (j==2) { y+=height; } else if (j==3) { x+=width; y+=height; } } else if (li->light_ptr->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) { height/=2; if (j==0) { } else { y+=height; } } ubo_data.shadow_split_offsets[j]=1.0/li->shadow_transform[j].split; Transform modelview = (p_camera_inverse_transform * li->shadow_transform[j].transform).inverse(); CameraMatrix bias; bias.set_light_bias(); CameraMatrix rectm; Rect2 atlas_rect = Rect2(float(x)/directional_shadow.size,float(y)/directional_shadow.size,float(width)/directional_shadow.size,float(height)/directional_shadow.size); rectm.set_light_atlas_rect(atlas_rect); CameraMatrix shadow_mtx = rectm * bias * li->shadow_transform[j].camera * modelview; store_camera(shadow_mtx,&ubo_data.shadow_matrix1[16*j]); ubo_data.light_clamp[0]=atlas_rect.pos.x; ubo_data.light_clamp[1]=atlas_rect.pos.y; ubo_data.light_clamp[2]=atlas_rect.size.x; ubo_data.light_clamp[3]=atlas_rect.size.y; } } glBindBuffer(GL_UNIFORM_BUFFER, state.directional_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(LightDataUBO), &ubo_data); glBindBuffer(GL_UNIFORM_BUFFER, 0); directional_light=li; glBindBufferBase(GL_UNIFORM_BUFFER,3,state.directional_ubo); } void RasterizerSceneGLES3::_setup_lights(RID *p_light_cull_result,int p_light_cull_count,const Transform& p_camera_inverse_transform,const CameraMatrix& p_camera_projection,RID p_shadow_atlas) { state.omni_light_count=0; state.spot_light_count=0; state.directional_light_count=0; directional_light=NULL; ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); for(int i=0;i<p_light_cull_count;i++) { ERR_BREAK( i>=RenderList::MAX_LIGHTS ); LightInstance *li = light_instance_owner.getptr(p_light_cull_result[i]); LightDataUBO ubo_data; //used for filling switch(li->light_ptr->type) { case VS::LIGHT_DIRECTIONAL: { if (state.directional_light_count<RenderList::MAX_DIRECTIONAL_LIGHTS) { directional_lights[state.directional_light_count++]=li; } } break; case VS::LIGHT_OMNI: { float sign = li->light_ptr->negative?-1:1; Color linear_col = li->light_ptr->color.to_linear(); ubo_data.light_color_energy[0]=linear_col.r*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[1]=linear_col.g*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[2]=linear_col.b*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[3]=0; Vector3 pos = p_camera_inverse_transform.xform(li->transform.origin); //directional, keep at 0 ubo_data.light_pos_inv_radius[0]=pos.x; ubo_data.light_pos_inv_radius[1]=pos.y; ubo_data.light_pos_inv_radius[2]=pos.z; ubo_data.light_pos_inv_radius[3]=1.0/MAX(0.001,li->light_ptr->param[VS::LIGHT_PARAM_RANGE]); ubo_data.light_direction_attenuation[0]=0; ubo_data.light_direction_attenuation[1]=0; ubo_data.light_direction_attenuation[2]=0; ubo_data.light_direction_attenuation[3]=li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION]; ubo_data.light_params[0]=0; ubo_data.light_params[1]=0; ubo_data.light_params[2]=li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR]; ubo_data.light_params[3]=0; Color shadow_color = li->light_ptr->shadow_color.to_linear(); ubo_data.light_shadow_color[0]=shadow_color.r; ubo_data.light_shadow_color[1]=shadow_color.g; ubo_data.light_shadow_color[2]=shadow_color.b; ubo_data.light_shadow_color[3]=1.0; if (li->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) { // fill in the shadow information uint32_t key = shadow_atlas->shadow_owners[li->self]; uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT)&0x3; uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; ERR_CONTINUE(shadow>=shadow_atlas->quadrants[quadrant].shadows.size()); uint32_t atlas_size = shadow_atlas->size; uint32_t quadrant_size = atlas_size>>1; uint32_t x=(quadrant&1)*quadrant_size; uint32_t y=(quadrant>>1)*quadrant_size; uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); x+=(shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; y+=(shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; uint32_t width=shadow_size; uint32_t height=shadow_size; if (li->light_ptr->omni_shadow_detail==VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { height/=2; } else { width/=2; } Transform proj = (p_camera_inverse_transform * li->transform).inverse(); store_transform(proj,ubo_data.shadow_matrix1); ubo_data.light_params[3]=1.0; //means it has shadow ubo_data.light_clamp[0]=float(x)/atlas_size; ubo_data.light_clamp[1]=float(y)/atlas_size; ubo_data.light_clamp[2]=float(width)/atlas_size; ubo_data.light_clamp[3]=float(height)/atlas_size; } li->light_index=state.omni_light_count; copymem(&state.omni_array_tmp[li->light_index*state.ubo_light_size],&ubo_data,state.ubo_light_size); state.omni_light_count++; #if 0 if (li->light_ptr->shadow_enabled) { li->shadow_projection[0] = Transform(camera_transform_inverse * li->transform).inverse(); lights_use_shadow=true; } #endif } break; case VS::LIGHT_SPOT: { float sign = li->light_ptr->negative?-1:1; Color linear_col = li->light_ptr->color.to_linear(); ubo_data.light_color_energy[0]=linear_col.r*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[1]=linear_col.g*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[2]=linear_col.b*sign*li->light_ptr->param[VS::LIGHT_PARAM_ENERGY]; ubo_data.light_color_energy[3]=0; Vector3 pos = p_camera_inverse_transform.xform(li->transform.origin); //directional, keep at 0 ubo_data.light_pos_inv_radius[0]=pos.x; ubo_data.light_pos_inv_radius[1]=pos.y; ubo_data.light_pos_inv_radius[2]=pos.z; ubo_data.light_pos_inv_radius[3]=1.0/MAX(0.001,li->light_ptr->param[VS::LIGHT_PARAM_RANGE]); Vector3 direction = p_camera_inverse_transform.basis.xform(li->transform.basis.xform(Vector3(0,0,-1))).normalized(); ubo_data.light_direction_attenuation[0]=direction.x; ubo_data.light_direction_attenuation[1]=direction.y; ubo_data.light_direction_attenuation[2]=direction.z; ubo_data.light_direction_attenuation[3]=li->light_ptr->param[VS::LIGHT_PARAM_ATTENUATION]; ubo_data.light_params[0]=li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ATTENUATION]; ubo_data.light_params[1]=Math::cos(Math::deg2rad(li->light_ptr->param[VS::LIGHT_PARAM_SPOT_ANGLE])); ubo_data.light_params[2]=li->light_ptr->param[VS::LIGHT_PARAM_SPECULAR]; ubo_data.light_params[3]=0; Color shadow_color = li->light_ptr->shadow_color.to_linear(); ubo_data.light_shadow_color[0]=shadow_color.r; ubo_data.light_shadow_color[1]=shadow_color.g; ubo_data.light_shadow_color[2]=shadow_color.b; ubo_data.light_shadow_color[3]=1.0; if (li->light_ptr->shadow && shadow_atlas && shadow_atlas->shadow_owners.has(li->self)) { // fill in the shadow information uint32_t key = shadow_atlas->shadow_owners[li->self]; uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT)&0x3; uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; ERR_CONTINUE(shadow>=shadow_atlas->quadrants[quadrant].shadows.size()); uint32_t atlas_size = shadow_atlas->size; uint32_t quadrant_size = atlas_size>>1; uint32_t x=(quadrant&1)*quadrant_size; uint32_t y=(quadrant>>1)*quadrant_size; uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); x+=(shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; y+=(shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; uint32_t width=shadow_size; uint32_t height=shadow_size; Rect2 rect(float(x)/atlas_size,float(y)/atlas_size,float(width)/atlas_size,float(height)/atlas_size); ubo_data.light_params[3]=1.0; //means it has shadow ubo_data.light_clamp[0]=rect.pos.x; ubo_data.light_clamp[1]=rect.pos.y; ubo_data.light_clamp[2]=rect.size.x; ubo_data.light_clamp[3]=rect.size.y; Transform modelview = (p_camera_inverse_transform * li->transform).inverse(); CameraMatrix bias; bias.set_light_bias(); CameraMatrix rectm; rectm.set_light_atlas_rect(rect); CameraMatrix shadow_mtx = rectm * bias * li->shadow_transform[0].camera * modelview; store_camera(shadow_mtx,ubo_data.shadow_matrix1); } li->light_index=state.spot_light_count; copymem(&state.spot_array_tmp[li->light_index*state.ubo_light_size],&ubo_data,state.ubo_light_size); state.spot_light_count++; #if 0 if (li->light_ptr->shadow_enabled) { CameraMatrix bias; bias.set_light_bias(); Transform modelview=Transform(camera_transform_inverse * li->transform).inverse(); li->shadow_projection[0] = bias * li->projection * modelview; lights_use_shadow=true; } #endif } break; } li->last_pass=render_pass; //update UBO for forward rendering, blit to texture for clustered } if (state.omni_light_count) { glBindBuffer(GL_UNIFORM_BUFFER, state.omni_array_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, state.omni_light_count*state.ubo_light_size, state.omni_array_tmp); glBindBuffer(GL_UNIFORM_BUFFER, 0); glBindBufferBase(GL_UNIFORM_BUFFER,4,state.omni_array_ubo); } if (state.spot_light_count) { glBindBuffer(GL_UNIFORM_BUFFER, state.spot_array_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, state.spot_light_count*state.ubo_light_size, state.spot_array_tmp); glBindBuffer(GL_UNIFORM_BUFFER, 0); glBindBufferBase(GL_UNIFORM_BUFFER,5,state.spot_array_ubo); } } void RasterizerSceneGLES3::_setup_reflections(RID *p_reflection_probe_cull_result,int p_reflection_probe_cull_count,const Transform& p_camera_inverse_transform,const CameraMatrix& p_camera_projection,RID p_reflection_atlas,Environment *p_env) { state.reflection_probe_count=0; for(int i=0;i<p_reflection_probe_cull_count;i++) { ReflectionProbeInstance *rpi=reflection_probe_instance_owner.getornull(p_reflection_probe_cull_result[i]); ERR_CONTINUE(!rpi); ReflectionAtlas *reflection_atlas=reflection_atlas_owner.getornull(p_reflection_atlas); ERR_CONTINUE(!reflection_atlas); ERR_CONTINUE(rpi->reflection_atlas_index<0); if (state.reflection_probe_count>=state.max_ubo_reflections) break; rpi->last_pass=render_pass; ReflectionProbeDataUBO reflection_ubo; reflection_ubo.box_extents[0]=rpi->probe_ptr->extents.x; reflection_ubo.box_extents[1]=rpi->probe_ptr->extents.y; reflection_ubo.box_extents[2]=rpi->probe_ptr->extents.z; reflection_ubo.box_extents[3]=0; reflection_ubo.box_ofs[0]=rpi->probe_ptr->origin_offset.x; reflection_ubo.box_ofs[1]=rpi->probe_ptr->origin_offset.y; reflection_ubo.box_ofs[2]=rpi->probe_ptr->origin_offset.z; reflection_ubo.box_ofs[3]=0; reflection_ubo.params[0]=rpi->probe_ptr->intensity; reflection_ubo.params[1]=0; reflection_ubo.params[2]=rpi->probe_ptr->interior?1.0:0.0; reflection_ubo.params[3]=rpi->probe_ptr->box_projection?1.0:0.0; if (rpi->probe_ptr->interior) { Color ambient_linear = rpi->probe_ptr->interior_ambient.to_linear(); reflection_ubo.ambient[0]=ambient_linear.r*rpi->probe_ptr->interior_ambient_energy; reflection_ubo.ambient[1]=ambient_linear.g*rpi->probe_ptr->interior_ambient_energy; reflection_ubo.ambient[2]=ambient_linear.b*rpi->probe_ptr->interior_ambient_energy; reflection_ubo.ambient[3]=rpi->probe_ptr->interior_ambient_probe_contrib; } else { Color ambient_linear; float contrib=0; if (p_env) { ambient_linear=p_env->ambient_color.to_linear(); ambient_linear.r*=p_env->ambient_energy; ambient_linear.g*=p_env->ambient_energy; ambient_linear.b*=p_env->ambient_energy; contrib=p_env->ambient_skybox_contribution; } reflection_ubo.ambient[0]=ambient_linear.r; reflection_ubo.ambient[1]=ambient_linear.g; reflection_ubo.ambient[2]=ambient_linear.b; reflection_ubo.ambient[3]=0; } int cell_size = reflection_atlas->size / reflection_atlas->subdiv; int x = (rpi->reflection_atlas_index % reflection_atlas->subdiv) * cell_size; int y = (rpi->reflection_atlas_index / reflection_atlas->subdiv) * cell_size; int width=cell_size; int height=cell_size; reflection_ubo.atlas_clamp[0]=float(x)/reflection_atlas->size; reflection_ubo.atlas_clamp[1]=float(y)/reflection_atlas->size; reflection_ubo.atlas_clamp[2]=float(width)/reflection_atlas->size; reflection_ubo.atlas_clamp[3]=float(height/2)/reflection_atlas->size; Transform proj = (p_camera_inverse_transform * rpi->transform).inverse(); store_transform(proj,reflection_ubo.local_matrix); rpi->reflection_index=state.reflection_probe_count; copymem(&state.reflection_array_tmp[rpi->reflection_index*sizeof(ReflectionProbeDataUBO)],&reflection_ubo,sizeof(ReflectionProbeDataUBO)); state.reflection_probe_count++; } if (state.reflection_probe_count) { glBindBuffer(GL_UNIFORM_BUFFER, state.reflection_array_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, state.reflection_probe_count*sizeof(ReflectionProbeDataUBO), state.reflection_array_tmp); glBindBuffer(GL_UNIFORM_BUFFER, 0); glBindBufferBase(GL_UNIFORM_BUFFER,6,state.reflection_array_ubo); } } void RasterizerSceneGLES3::_copy_screen() { glBindVertexArray( storage->resources.quadie_array); glDrawArrays(GL_TRIANGLE_FAN,0,4); glBindVertexArray(0); } void RasterizerSceneGLES3::_copy_to_front_buffer(Environment *env) { //copy to front buffer glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); glDepthFunc(GL_LEQUAL); glColorMask(1,1,1,1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.diffuse); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,true); if (!env) { //no environment, simply convert from linear to srgb storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,true); } else { storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,true); } storage->shaders.copy.bind(); _copy_screen(); //turn off everything used storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,false); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,false); } void RasterizerSceneGLES3::_copy_texture_to_front_buffer(GLuint p_texture) { //copy to front buffer glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); glDepthFunc(GL_LEQUAL); glColorMask(1,1,1,1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,p_texture); glViewport(0,0,storage->frame.current_rt->width*0.5,storage->frame.current_rt->height*0.5); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,true); storage->shaders.copy.bind(); _copy_screen(); //turn off everything used storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,false); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,false); } void RasterizerSceneGLES3::_fill_render_list(InstanceBase** p_cull_result,int p_cull_count,bool p_shadow){ current_geometry_index=0; current_material_index=0; state.used_sss=false; //fill list for(int i=0;i<p_cull_count;i++) { InstanceBase *inst = p_cull_result[i]; switch(inst->base_type) { case VS::INSTANCE_MESH: { RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.getptr(inst->base); ERR_CONTINUE(!mesh); int ssize = mesh->surfaces.size(); for (int i=0;i<ssize;i++) { int mat_idx = inst->materials[i].is_valid() ? i : -1; RasterizerStorageGLES3::Surface *s = mesh->surfaces[i]; _add_geometry(s,inst,NULL,mat_idx,p_shadow); } //mesh->last_pass=frame; } break; case VS::INSTANCE_MULTIMESH: { RasterizerStorageGLES3::MultiMesh *multi_mesh = storage->multimesh_owner.getptr(inst->base); ERR_CONTINUE(!multi_mesh); if (multi_mesh->size==0 || multi_mesh->visible_instances==0) continue; RasterizerStorageGLES3::Mesh *mesh = storage->mesh_owner.getptr(multi_mesh->mesh); if (!mesh) continue; //mesh not assigned int ssize = mesh->surfaces.size(); for (int i=0;i<ssize;i++) { RasterizerStorageGLES3::Surface *s = mesh->surfaces[i]; _add_geometry(s,inst,multi_mesh,-1,p_shadow); } } break; case VS::INSTANCE_IMMEDIATE: { } break; } } } void RasterizerSceneGLES3::_render_mrts(Environment *env,const CameraMatrix &p_cam_projection) { glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); if (env->ssao_enabled) { //copy diffuse to front buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); //copy from depth, convert to linear GLint ss[2]; ss[0]=storage->frame.current_rt->width; ss[1]=storage->frame.current_rt->height; for(int i=0;i<storage->frame.current_rt->effects.ssao.depth_mipmap_fbos.size();i++) { state.ssao_minify_shader.set_conditional(SsaoMinifyShaderGLES3::MINIFY_START,i==0); state.ssao_minify_shader.bind(); state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far()); state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near()); state.ssao_minify_shader.set_uniform(SsaoMinifyShaderGLES3::SOURCE_MIPMAP,MAX(0,i-1)); glUniform2iv(state.ssao_minify_shader.get_uniform(SsaoMinifyShaderGLES3::FROM_SIZE),1,ss); ss[0]>>=1; ss[1]>>=1; glActiveTexture(GL_TEXTURE0); if (i==0) { glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth); } else { glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.ssao.linear_depth); } glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.ssao.depth_mipmap_fbos[i]); //copy to front first glViewport(0,0,ss[0],ss[1]); _copy_screen(); } ss[0]=storage->frame.current_rt->width; ss[1]=storage->frame.current_rt->height; glViewport(0,0,ss[0],ss[1]); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_GREATER); // do SSAO! state.ssao_shader.set_conditional(SsaoShaderGLES3::ENABLE_RADIUS2,env->ssao_radius2>0.001); state.ssao_shader.bind(); state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far()); state.ssao_shader.set_uniform(SsaoShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near()); glUniform2iv(state.ssao_shader.get_uniform(SsaoShaderGLES3::SCREEN_SIZE),1,ss); float radius = env->ssao_radius; state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS,radius); float intensity = env->ssao_intensity; state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R6,intensity / pow(radius, 6.0f)); if (env->ssao_radius2>0.001) { float radius2 = env->ssao_radius2; state.ssao_shader.set_uniform(SsaoShaderGLES3::RADIUS2,radius2); float intensity2 = env->ssao_intensity2; state.ssao_shader.set_uniform(SsaoShaderGLES3::INTENSITY_DIV_R62,intensity2 / pow(radius2, 6.0f)); } float proj_info[4]={ -2.0f / (ss[0]*p_cam_projection.matrix[0][0]), -2.0f / (ss[1]*p_cam_projection.matrix[1][1]), ( 1.0f - p_cam_projection.matrix[0][2]) / p_cam_projection.matrix[0][0], ( 1.0f + p_cam_projection.matrix[1][2]) / p_cam_projection.matrix[1][1] }; glUniform4fv(state.ssao_shader.get_uniform(SsaoShaderGLES3::PROJ_INFO),1,proj_info); float pixels_per_meter = float(p_cam_projection.get_pixels_per_meter(ss[0])); state.ssao_shader.set_uniform(SsaoShaderGLES3::PROJ_SCALE,pixels_per_meter); state.ssao_shader.set_uniform(SsaoShaderGLES3::BIAS,env->ssao_bias); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.ssao.linear_depth); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.effect); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.ssao.blur_fbo[0]); //copy to front first Color white(1,1,1,1); glClearBufferfv(GL_COLOR,0,white.components); // specular _copy_screen(); //do the batm, i mean blur state.ssao_blur_shader.bind(); if (env->ssao_filter) { for(int i=0;i<2;i++) { state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far()); state.ssao_blur_shader.set_uniform(SsaoBlurShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near()); GLint axis[2]={i,1-i}; glUniform2iv(state.ssao_blur_shader.get_uniform(SsaoBlurShaderGLES3::AXIS),1,axis); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.ssao.blur_red[i]); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.ssao.blur_fbo[1-i]); if (i==0) { glClearBufferfv(GL_COLOR,0,white.components); // specular } _copy_screen(); } } glDisable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); // just copy diffuse while applying SSAO state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE,true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::SSAO_COLOR,env->ssao_color); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color); //previous level, since mipmaps[0] starts one level bigger glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.ssao.blur_red[0]); //previous level, since mipmaps[0] starts one level bigger glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SSAO_MERGE,false); } else { //copy diffuse to effect buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); } if (state.used_sss) {//sss enabled //copy diffuse while performing sss //copy normal and roughness to effect buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT3); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->buffers.effect_fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT , GL_NEAREST); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_11_SAMPLES,subsurface_scatter_quality==SSS_QUALITY_LOW); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_17_SAMPLES,subsurface_scatter_quality==SSS_QUALITY_MEDIUM); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::USE_25_SAMPLES,subsurface_scatter_quality==SSS_QUALITY_HIGH); state.sss_shader.set_conditional(SubsurfScatteringShaderGLES3::ENABLE_FOLLOW_SURFACE,subsurface_scatter_follow_surface); state.sss_shader.bind(); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::MAX_RADIUS,subsurface_scatter_size); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::FOVY,p_cam_projection.get_fov()); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near()); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far()); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR,Vector2(1,0)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.effect); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); //copy to front first _copy_screen(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color); state.sss_shader.set_uniform(SubsurfScatteringShaderGLES3::DIR,Vector2(0,1)); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level _copy_screen(); } if (env->ssr_enabled) { //copy normal and roughness to effect buffer glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT2); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->buffers.effect_fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT , GL_NEAREST); //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); for(int i=0;i<storage->frame.current_rt->effects.mip_maps[1].sizes.size();i++) { int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width; int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height; glViewport(0,0,vp_w,vp_h); //horizontal pass state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL,true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(i)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo); _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_HORIZONTAL,false); //vertical pass state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL,true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(i)); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[1].color); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[i+1].fbo); //next level, since mipmaps[0] starts one level bigger _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GAUSSIAN_VERTICAL,false); } //perform SSR state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::SMOOTH_ACCEL,env->ssr_accel>0 && env->ssr_smooth); state.ssr_shader.set_conditional(ScreenSpaceReflectionShaderGLES3::REFLECT_ROUGHNESS,env->ssr_accel>0 && env->ssr_roughness); state.ssr_shader.bind(); int ssr_w = storage->frame.current_rt->effects.mip_maps[1].sizes[0].width; int ssr_h = storage->frame.current_rt->effects.mip_maps[1].sizes[0].height; state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PIXEL_SIZE,Vector2(1.0/(ssr_w*0.5),1.0/(ssr_h*0.5))); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near()); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far()); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::PROJECTION,p_cam_projection); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::INVERSE_PROJECTION,p_cam_projection.inverse()); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::VIEWPORT_SIZE,Size2(ssr_w,ssr_h)); //state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FRAME_INDEX,int(render_pass)); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::FILTER_MIPMAP_LEVELS,float(storage->frame.current_rt->effects.mip_maps[0].sizes.size())); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::NUM_STEPS,env->ssr_max_steps); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::ACCELERATION,env->ssr_accel); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DEPTH_TOLERANCE,env->ssr_depth_tolerance); state.ssr_shader.set_uniform(ScreenSpaceReflectionShaderGLES3::DISTANCE_FADE,env->ssr_fade); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.effect); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[1].sizes[0].fbo); glViewport(0,0,ssr_w,ssr_h); _copy_screen(); glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height); } glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glReadBuffer(GL_COLOR_ATTACHMENT1); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->fbo); //glDrawBuffer(GL_COLOR_ATTACHMENT0); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST); glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); //copy reflection over diffuse, resolving SSR if needed state.resolve_shader.set_conditional(ResolveShaderGLES3::USE_SSR,env->ssr_enabled); state.resolve_shader.bind(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color); if (env->ssr_enabled) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[1].color); } glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_ONE,GL_ONE); //use additive to accumulate one over the other _copy_screen(); glDisable(GL_BLEND); //end additive state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY,true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(0)); { GLuint db = GL_COLOR_ATTACHMENT0; glDrawBuffers(1,&db); } glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::SIMPLE_COPY,false); } void RasterizerSceneGLES3::_post_process(Environment *env,const CameraMatrix &p_cam_projection){ //copy to front buffer glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_BLEND); glDepthFunc(GL_LEQUAL); glColorMask(1,1,1,1); //turn off everything used //copy specular to front buffer //copy diffuse to effect buffer glReadBuffer(GL_COLOR_ATTACHMENT0); glBindFramebuffer(GL_READ_FRAMEBUFFER, storage->frame.current_rt->buffers.fbo); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); glBlitFramebuffer(0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, 0, 0, storage->frame.current_rt->width, storage->frame.current_rt->height, GL_COLOR_BUFFER_BIT, GL_NEAREST); glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); if (!env) { //no environment, simply return and convert to SRGB glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,true); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,true); storage->shaders.copy.bind(); _copy_screen(); storage->shaders.copy.set_conditional(CopyShaderGLES3::LINEAR_TO_SRGB,false); storage->shaders.copy.set_conditional(CopyShaderGLES3::DISABLE_ALPHA,false); //compute luminance return; } //order of operation //1) DOF Blur (first blur, then copy to buffer applying the blur) //2) Motion Blur //3) Bloom //4) Tonemap //5) Adjustments GLuint composite_from = storage->frame.current_rt->effects.mip_maps[0].color; if (env->dof_blur_far_enabled) { //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); int vp_h = storage->frame.current_rt->height; int vp_w = storage->frame.current_rt->width; state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR,true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW,env->dof_blur_far_quality==VS::ENV_DOF_BLUR_QUALITY_LOW); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM,env->dof_blur_far_quality==VS::ENV_DOF_BLUR_QUALITY_MEDIUM); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH,env->dof_blur_far_quality==VS::ENV_DOF_BLUR_QUALITY_HIGH); state.effect_blur_shader.bind(); int qsteps[3]={4,10,20}; float radius = (env->dof_blur_far_amount*env->dof_blur_far_amount) / qsteps[env->dof_blur_far_quality]; state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN,env->dof_blur_far_distance); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END,env->dof_blur_far_distance+env->dof_blur_far_transition); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR,Vector2(1,0)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS,radius); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near()); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far()); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,composite_from); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); //copy to front first _copy_screen(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR,Vector2(0,1)); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_FAR_BLUR,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH,false); composite_from=storage->frame.current_rt->effects.mip_maps[0].color; } if (env->dof_blur_near_enabled) { //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); int vp_h = storage->frame.current_rt->height; int vp_w = storage->frame.current_rt->width; state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR,true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP,true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW,env->dof_blur_near_quality==VS::ENV_DOF_BLUR_QUALITY_LOW); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM,env->dof_blur_near_quality==VS::ENV_DOF_BLUR_QUALITY_MEDIUM); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH,env->dof_blur_near_quality==VS::ENV_DOF_BLUR_QUALITY_HIGH); state.effect_blur_shader.bind(); int qsteps[3]={4,10,20}; float radius = (env->dof_blur_near_amount*env->dof_blur_near_amount) / qsteps[env->dof_blur_near_quality]; state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN,env->dof_blur_near_distance); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END,env->dof_blur_near_distance-env->dof_blur_near_transition); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR,Vector2(1,0)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS,radius); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near()); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far()); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->depth); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,composite_from); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); //copy to front first _copy_screen(); //manually do the blend if this is the first operation resolving from the diffuse buffer state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE,composite_from == storage->frame.current_rt->buffers.diffuse); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP,false); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_BEGIN,env->dof_blur_near_distance); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_END,env->dof_blur_near_distance-env->dof_blur_near_transition); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_DIR,Vector2(0,1)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::DOF_RADIUS,radius); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_NEAR,p_cam_projection.get_z_near()); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::CAMERA_Z_FAR,p_cam_projection.get_z_far()); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->color); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[0].fbo); // copy to base level if (composite_from != storage->frame.current_rt->buffers.diffuse) { glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } else { glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.diffuse); } _copy_screen(); if (composite_from != storage->frame.current_rt->buffers.diffuse) { glDisable(GL_BLEND); } state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_FIRST_TAP,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_NEAR_BLUR_MERGE,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_LOW,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_MEDIUM,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::DOF_QUALITY_HIGH,false); composite_from=storage->frame.current_rt->effects.mip_maps[0].color; } if ( env->auto_exposure) { //compute auto exposure //first step, copy from image to luminance buffer state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN,true); state.exposure_shader.bind(); int ss[2]={ storage->frame.current_rt->width, storage->frame.current_rt->height, }; int ds[2]={ exposure_shrink_size, exposure_shrink_size, }; glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::SOURCE_RENDER_SIZE),1,ss); glUniform2iv(state.exposure_shader.get_uniform(ExposureShaderGLES3::TARGET_SIZE),1,ds); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->buffers.diffuse); glBindFramebuffer(GL_FRAMEBUFFER,exposure_shrink[0].fbo); glViewport(0,0,exposure_shrink_size,exposure_shrink_size); _copy_screen(); //second step, shrink to 2x2 pixels state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_BEGIN,false); state.exposure_shader.bind(); //shrink from second to previous to last level int s_size=exposure_shrink_size/3; for(int i=1;i<exposure_shrink.size()-1;i++) { glBindFramebuffer(GL_FRAMEBUFFER,exposure_shrink[i].fbo); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,exposure_shrink[i-1].color); _copy_screen(); glViewport(0,0,s_size,s_size); s_size/=3; } //third step, shrink to 1x1 pixel taking in consideration the previous exposure state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END,true); uint64_t tick = OS::get_singleton()->get_ticks_usec(); uint64_t tick_diff = storage->frame.current_rt->last_exposure_tick==0?0:tick-storage->frame.current_rt->last_exposure_tick; storage->frame.current_rt->last_exposure_tick=tick; if (tick_diff==0 || tick_diff>1000000) { state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET,true); } state.exposure_shader.bind(); glBindFramebuffer(GL_FRAMEBUFFER,exposure_shrink[exposure_shrink.size()-1].fbo); glViewport(0,0,1,1); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,exposure_shrink[exposure_shrink.size()-2].color); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color); //read from previous state.exposure_shader.set_uniform(ExposureShaderGLES3::EXPOSURE_ADJUST,env->auto_exposure_speed*(tick_diff/1000000.0)); state.exposure_shader.set_uniform(ExposureShaderGLES3::MAX_LUMINANCE,env->auto_exposure_max); state.exposure_shader.set_uniform(ExposureShaderGLES3::MIN_LUMINANCE,env->auto_exposure_min); _copy_screen(); state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_FORCE_SET,false); state.exposure_shader.set_conditional(ExposureShaderGLES3::EXPOSURE_END,false); //last step, swap with the framebuffer exposure, so the right exposure is kept int he framebuffer SWAP(exposure_shrink[exposure_shrink.size()-1].fbo,storage->frame.current_rt->exposure.fbo); SWAP(exposure_shrink[exposure_shrink.size()-1].color,storage->frame.current_rt->exposure.color); glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height); } int max_glow_level=-1; int glow_mask=0; if (env->glow_enabled) { for(int i=0;i<VS::MAX_GLOW_LEVELS;i++) { if (env->glow_levels&(1<<i)) { if (i>=storage->frame.current_rt->effects.mip_maps[1].sizes.size()) { max_glow_level=storage->frame.current_rt->effects.mip_maps[1].sizes.size()-1; glow_mask|=1<<max_glow_level; } else { max_glow_level=i; glow_mask|=(1<<i); } } } //blur diffuse into effect mipmaps using separatable convolution //storage->shaders.copy.set_conditional(CopyShaderGLES3::GAUSSIAN_HORIZONTAL,true); for(int i=0;i<(max_glow_level+1);i++) { int vp_w = storage->frame.current_rt->effects.mip_maps[1].sizes[i].width; int vp_h = storage->frame.current_rt->effects.mip_maps[1].sizes[i].height; glViewport(0,0,vp_w,vp_h); //horizontal pass if (i==0) { state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS,true); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE,env->auto_exposure); } state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL,true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(i)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH,env->glow_strength); glActiveTexture(GL_TEXTURE0); if (i==0) { glBindTexture(GL_TEXTURE_2D,composite_from); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::EXPOSURE,env->tone_mapper_exposure); if (env->auto_exposure) { state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::AUTO_EXPOSURE_GREY,env->auto_exposure_grey); } glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_BLOOM,env->glow_bloom); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_TRESHOLD,env->glow_hdr_bleed_treshold); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_HDR_SCALE,env->glow_hdr_bleed_scale); } else { glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); //previous level, since mipmaps[0] starts one level bigger } glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[1].sizes[i].fbo); _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_HORIZONTAL,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_FIRST_PASS,false); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_USE_AUTO_EXPOSURE,false); //vertical pass state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL,true); state.effect_blur_shader.bind(); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::PIXEL_SIZE,Vector2(1.0/vp_w,1.0/vp_h)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::LOD,float(i)); state.effect_blur_shader.set_uniform(EffectBlurShaderGLES3::GLOW_STRENGTH,env->glow_strength); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[1].color); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->effects.mip_maps[0].sizes[i+1].fbo); //next level, since mipmaps[0] starts one level bigger _copy_screen(); state.effect_blur_shader.set_conditional(EffectBlurShaderGLES3::GLOW_GAUSSIAN_VERTICAL,false); } glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height); } glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,composite_from); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER,env->tone_mapper==VS::ENV_TONE_MAPPER_FILMIC); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER,env->tone_mapper==VS::ENV_TONE_MAPPER_ACES); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINDHART_TONEMAPPER,env->tone_mapper==VS::ENV_TONE_MAPPER_REINHARDT); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE,env->auto_exposure); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC,env->glow_bicubic_upscale); if (max_glow_level>=0) { for(int i=0;i<(max_glow_level+1);i++) { if (glow_mask&(1<<i)) { if (i==0) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1,true); } if (i==1) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2,true); } if (i==2) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3,true); } if (i==3) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4,true); } if (i==4) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5,true); } if (i==5) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6,true); } if (i==6) { state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7,true); } } } state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN,env->glow_blend_mode==VS::GLOW_BLEND_MODE_SCREEN); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT,env->glow_blend_mode==VS::GLOW_BLEND_MODE_SOFTLIGHT); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE,env->glow_blend_mode==VS::GLOW_BLEND_MODE_REPLACE); glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->effects.mip_maps[0].color); } state.tonemap_shader.bind(); state.tonemap_shader.set_uniform(TonemapShaderGLES3::EXPOSURE,env->tone_mapper_exposure); state.tonemap_shader.set_uniform(TonemapShaderGLES3::WHITE,env->tone_mapper_exposure_white); if (max_glow_level>=0) { state.tonemap_shader.set_uniform(TonemapShaderGLES3::GLOW_INTENSITY,env->glow_intensity); int ss[2]={ storage->frame.current_rt->width, storage->frame.current_rt->height, }; glUniform2iv(state.tonemap_shader.get_uniform(TonemapShaderGLES3::GLOW_TEXTURE_SIZE),1,ss); } if (env->auto_exposure) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color); state.tonemap_shader.set_uniform(TonemapShaderGLES3::AUTO_EXPOSURE_GREY,env->auto_exposure_grey); } _copy_screen(); //turn off everything used state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_AUTO_EXPOSURE,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_FILMIC_TONEMAPPER,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_ACES_TONEMAPPER,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_REINDHART_TONEMAPPER,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL1,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL2,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL3,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL4,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL5,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL6,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_LEVEL7,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_REPLACE,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SCREEN,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_SOFTLIGHT,false); state.tonemap_shader.set_conditional(TonemapShaderGLES3::USE_GLOW_FILTER_BICUBIC,false); } void RasterizerSceneGLES3::render_scene(const Transform& p_cam_transform,const CameraMatrix& p_cam_projection,bool p_cam_ortogonal,InstanceBase** p_cull_result,int p_cull_count,RID* p_light_cull_result,int p_light_cull_count,RID* p_reflection_probe_cull_result,int p_reflection_probe_cull_count,RID p_environment,RID p_shadow_atlas,RID p_reflection_atlas,RID p_reflection_probe,int p_reflection_probe_pass){ //first of all, make a new render pass render_pass++; //fill up ubo Environment *env = environment_owner.getornull(p_environment); ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); ReflectionAtlas *reflection_atlas = reflection_atlas_owner.getornull(p_reflection_atlas); if (shadow_atlas && shadow_atlas->size) { glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-3); glBindTexture(GL_TEXTURE_2D,shadow_atlas->depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS); state.ubo_data.shadow_atlas_pixel_size[0]=1.0/shadow_atlas->size; state.ubo_data.shadow_atlas_pixel_size[1]=1.0/shadow_atlas->size; } if (reflection_atlas && reflection_atlas->size) { glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-5); glBindTexture(GL_TEXTURE_2D,reflection_atlas->color); } if (p_reflection_probe.is_valid()) { state.ubo_data.reflection_multiplier=0.0; } else { state.ubo_data.reflection_multiplier=1.0; } state.ubo_data.subsurface_scatter_width=subsurface_scatter_size; state.ubo_data.shadow_z_offset=0; state.ubo_data.shadow_slope_scale=0; state.ubo_data.shadow_dual_paraboloid_render_side=0; state.ubo_data.shadow_dual_paraboloid_render_zfar=0; _setup_environment(env,p_cam_projection,p_cam_transform); bool fb_cleared=false; glDepthFunc(GL_LEQUAL); if (storage->frame.current_rt && true) { //pre z pass glDisable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo); glDrawBuffers(0,NULL); glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height); glColorMask(0,0,0,0); glClearDepth(1.0f); glClear(GL_DEPTH_BUFFER_BIT); render_list.clear(); _fill_render_list(p_cull_result,p_cull_count,true); render_list.sort_by_depth(false); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH,true); _render_list(render_list.elements,render_list.element_count,p_cam_transform,p_cam_projection,0,false,false,true,false,false); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH,false); glColorMask(1,1,1,1); fb_cleared=true; render_pass++; } _setup_lights(p_light_cull_result,p_light_cull_count,p_cam_transform.affine_inverse(),p_cam_projection,p_shadow_atlas); _setup_reflections(p_reflection_probe_cull_result,p_reflection_probe_cull_count,p_cam_transform.affine_inverse(),p_cam_projection,p_reflection_atlas,env); render_list.clear(); bool use_mrt=false; _fill_render_list(p_cull_result,p_cull_count,false); // glEnable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); //rendering to a probe cubemap side ReflectionProbeInstance *probe = reflection_probe_instance_owner.getornull(p_reflection_probe); GLuint current_fbo; if (probe) { ReflectionAtlas *ref_atlas = reflection_atlas_owner.getptr(probe->atlas); ERR_FAIL_COND(!ref_atlas); int target_size=ref_atlas->size/ref_atlas->subdiv; int cubemap_index=reflection_cubemaps.size()-1; for(int i=reflection_cubemaps.size()-1;i>=0;i--) { //find appropriate cubemap to render to if (reflection_cubemaps[i].size>target_size*2) break; cubemap_index=i; } current_fbo=reflection_cubemaps[cubemap_index].fbo_id[p_reflection_probe_pass]; use_mrt=false; state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS,false); glViewport(0,0,reflection_cubemaps[cubemap_index].size,reflection_cubemaps[cubemap_index].size); glBindFramebuffer(GL_FRAMEBUFFER,current_fbo); } else { use_mrt = state.used_sss || (env && (env->ssao_enabled || env->ssr_enabled)); //only enable MRT rendering if any of these is enabled glViewport(0,0,storage->frame.current_rt->width,storage->frame.current_rt->height); if (use_mrt) { current_fbo=storage->frame.current_rt->buffers.fbo; glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo); state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS,true); Vector<GLenum> draw_buffers; draw_buffers.push_back(GL_COLOR_ATTACHMENT0); draw_buffers.push_back(GL_COLOR_ATTACHMENT1); draw_buffers.push_back(GL_COLOR_ATTACHMENT2); if (state.used_sss) { draw_buffers.push_back(GL_COLOR_ATTACHMENT3); } glDrawBuffers(draw_buffers.size(),draw_buffers.ptr()); Color black(0,0,0,0); glClearBufferfv(GL_COLOR,1,black.components); // specular glClearBufferfv(GL_COLOR,2,black.components); // normal metal rough if (state.used_sss) { glClearBufferfv(GL_COLOR,3,black.components); // normal metal rough } } else { current_fbo = storage->frame.current_rt->buffers.fbo; glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo); state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS,false); Vector<GLenum> draw_buffers; draw_buffers.push_back(GL_COLOR_ATTACHMENT0); glDrawBuffers(draw_buffers.size(),draw_buffers.ptr()); } } if (!fb_cleared) { glClearDepth(1.0f); glClear(GL_DEPTH_BUFFER_BIT); } Color clear_color(0,0,0,0); RasterizerStorageGLES3::SkyBox *skybox=NULL; GLuint env_radiance_tex=0; if (!env || env->bg_mode==VS::ENV_BG_CLEAR_COLOR) { if (storage->frame.clear_request) { clear_color = storage->frame.clear_request_color.to_linear(); storage->frame.clear_request=false; } } else if (env->bg_mode==VS::ENV_BG_COLOR) { clear_color = env->bg_color.to_linear(); storage->frame.clear_request=false; } else if (env->bg_mode==VS::ENV_BG_SKYBOX) { skybox = storage->skybox_owner.getornull(env->skybox); if (skybox) { env_radiance_tex=skybox->radiance; } storage->frame.clear_request=false; } else { storage->frame.clear_request=false; } glClearBufferfv(GL_COLOR,0,clear_color.components); // specular state.texscreen_copied=false; glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } glDisable(GL_BLEND); render_list.sort_by_key(false); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } if (state.directional_light_count==0) { directional_light=NULL; _render_list(render_list.elements,render_list.element_count,p_cam_transform,p_cam_projection,env_radiance_tex,false,false,false,false,shadow_atlas!=NULL); } else { for(int i=0;i<state.directional_light_count;i++) { directional_light=directional_lights[i]; if (i>0) { glEnable(GL_BLEND); } _setup_directional_light(i,p_cam_transform.affine_inverse(),shadow_atlas!=NULL); _render_list(render_list.elements,render_list.element_count,p_cam_transform,p_cam_projection,env_radiance_tex,false,false,false,i>0,shadow_atlas!=NULL); } } state.scene_shader.set_conditional(SceneShaderGLES3::USE_MULTIPLE_RENDER_TARGETS,false); if (use_mrt) { GLenum gldb = GL_COLOR_ATTACHMENT0; glDrawBuffers(1,&gldb); } if (env && env->bg_mode==VS::ENV_BG_SKYBOX) { /* if (use_mrt) { glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->buffers.fbo); //switch to alpha fbo for skybox, only diffuse/ambient matters */ _draw_skybox(skybox,p_cam_projection,p_cam_transform,storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP],env->skybox_scale); } //_render_list_forward(&alpha_render_list,camera_transform,camera_transform_inverse,camera_projection,false,fragment_lighting,true); //glColorMask(1,1,1,1); //state.scene_shader.set_conditional( SceneShaderGLES3::USE_FOG,false); if (use_mrt) { _render_mrts(env,p_cam_projection); } glEnable(GL_BLEND); glDepthMask(GL_TRUE); glEnable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); render_list.sort_by_depth(true); if (state.directional_light_count==0) { directional_light=NULL; _render_list(&render_list.elements[render_list.max_elements-render_list.alpha_element_count],render_list.alpha_element_count,p_cam_transform,p_cam_projection,env_radiance_tex,false,true,false,false,shadow_atlas!=NULL); } else { for(int i=0;i<state.directional_light_count;i++) { directional_light=directional_lights[i]; _setup_directional_light(i,p_cam_transform.affine_inverse(),shadow_atlas!=NULL); _render_list(&render_list.elements[render_list.max_elements-render_list.alpha_element_count],render_list.alpha_element_count,p_cam_transform,p_cam_projection,env_radiance_tex,false,true,false,i>0,shadow_atlas!=NULL); } } if (probe) { //rendering a probe, do no more! return; } _post_process(env,p_cam_projection); if (false && shadow_atlas) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,shadow_atlas->depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/2,storage->frame.current_rt->height/2),Rect2(0,0,1,1)); } if (false && storage->frame.current_rt) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,exposure_shrink[4].color); //glBindTexture(GL_TEXTURE_2D,storage->frame.current_rt->exposure.color); storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/16,storage->frame.current_rt->height/16),Rect2(0,0,1,1)); } if (false && reflection_atlas && storage->frame.current_rt) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,reflection_atlas->color); storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/2,storage->frame.current_rt->height/2),Rect2(0,0,1,1)); } if (false && directional_shadow.fbo) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,directional_shadow.depth); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE); storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/2,storage->frame.current_rt->height/2),Rect2(0,0,1,1)); } if (false && env_radiance_tex) { //_copy_texture_to_front_buffer(shadow_atlas->depth); storage->canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,env_radiance_tex); storage->canvas->draw_generic_textured_rect(Rect2(0,0,storage->frame.current_rt->width/2,storage->frame.current_rt->height/2),Rect2(0,0,1,1)); } #if 0 if (use_fb) { for(int i=0;i<VS::ARRAY_MAX;i++) { glDisableVertexAttribArray(i); } glBindBuffer(GL_ARRAY_BUFFER,0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); glDisable(GL_SCISSOR_TEST); glDepthMask(false); if (current_env && current_env->fx_enabled[VS::ENV_FX_HDR]) { int hdr_tm = current_env->fx_param[VS::ENV_FX_PARAM_HDR_TONEMAPPER]; switch(hdr_tm) { case VS::ENV_FX_HDR_TONE_MAPPER_LINEAR: { } break; case VS::ENV_FX_HDR_TONE_MAPPER_LOG: { copy_shader.set_conditional(CopyShaderGLES2::USE_LOG_TONEMAPPER,true); } break; case VS::ENV_FX_HDR_TONE_MAPPER_REINHARDT: { copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER,true); } break; case VS::ENV_FX_HDR_TONE_MAPPER_REINHARDT_AUTOWHITE: { copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER,true); copy_shader.set_conditional(CopyShaderGLES2::USE_AUTOWHITE,true); } break; } _process_hdr(); } if (current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]) { _process_glow_bloom(); int glow_transfer_mode=current_env->fx_param[VS::ENV_FX_PARAM_GLOW_BLUR_BLEND_MODE]; if (glow_transfer_mode==1) copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SCREEN,true); if (glow_transfer_mode==2) copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SOFTLIGHT,true); } glBindFramebuffer(GL_FRAMEBUFFER, current_rt?current_rt->fbo:base_framebuffer); Size2 size; if (current_rt) { glBindFramebuffer(GL_FRAMEBUFFER, current_rt->fbo); glViewport( 0,0,viewport.width,viewport.height); size=Size2(viewport.width,viewport.height); } else { glBindFramebuffer(GL_FRAMEBUFFER, base_framebuffer); glViewport( viewport.x, window_size.height-(viewport.height+viewport.y), viewport.width,viewport.height ); size=Size2(viewport.width,viewport.height); } //time to copy!!! copy_shader.set_conditional(CopyShaderGLES2::USE_BCS,current_env && current_env->fx_enabled[VS::ENV_FX_BCS]); copy_shader.set_conditional(CopyShaderGLES2::USE_SRGB,current_env && current_env->fx_enabled[VS::ENV_FX_SRGB]); copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW,current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]); copy_shader.set_conditional(CopyShaderGLES2::USE_HDR,current_env && current_env->fx_enabled[VS::ENV_FX_HDR]); copy_shader.set_conditional(CopyShaderGLES2::USE_NO_ALPHA,true); copy_shader.set_conditional(CopyShaderGLES2::USE_FXAA,current_env && current_env->fx_enabled[VS::ENV_FX_FXAA]); copy_shader.bind(); //copy_shader.set_uniform(CopyShaderGLES2::SOURCE,0); if (current_env && current_env->fx_enabled[VS::ENV_FX_GLOW]) { glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, framebuffer.blur[0].color ); glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::GLOW_SOURCE),1); } if (current_env && current_env->fx_enabled[VS::ENV_FX_HDR]) { glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, current_vd->lum_color ); glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::HDR_SOURCE),2); copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_EXPOSURE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_EXPOSURE])); copy_shader.set_uniform(CopyShaderGLES2::TONEMAP_WHITE,float(current_env->fx_param[VS::ENV_FX_PARAM_HDR_WHITE])); } if (current_env && current_env->fx_enabled[VS::ENV_FX_FXAA]) copy_shader.set_uniform(CopyShaderGLES2::PIXEL_SIZE,Size2(1.0/size.x,1.0/size.y)); if (current_env && current_env->fx_enabled[VS::ENV_FX_BCS]) { Vector3 bcs; bcs.x=current_env->fx_param[VS::ENV_FX_PARAM_BCS_BRIGHTNESS]; bcs.y=current_env->fx_param[VS::ENV_FX_PARAM_BCS_CONTRAST]; bcs.z=current_env->fx_param[VS::ENV_FX_PARAM_BCS_SATURATION]; copy_shader.set_uniform(CopyShaderGLES2::BCS,bcs); } glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, framebuffer.color ); glUniform1i(copy_shader.get_uniform_location(CopyShaderGLES2::SOURCE),0); _copy_screen_quad(); copy_shader.set_conditional(CopyShaderGLES2::USE_BCS,false); copy_shader.set_conditional(CopyShaderGLES2::USE_SRGB,false); copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW,false); copy_shader.set_conditional(CopyShaderGLES2::USE_HDR,false); copy_shader.set_conditional(CopyShaderGLES2::USE_NO_ALPHA,false); copy_shader.set_conditional(CopyShaderGLES2::USE_FXAA,false); copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SCREEN,false); copy_shader.set_conditional(CopyShaderGLES2::USE_GLOW_SOFTLIGHT,false); copy_shader.set_conditional(CopyShaderGLES2::USE_REINHARDT_TONEMAPPER,false); copy_shader.set_conditional(CopyShaderGLES2::USE_AUTOWHITE,false); copy_shader.set_conditional(CopyShaderGLES2::USE_LOG_TONEMAPPER,false); state.scene_shader.set_conditional(SceneShaderGLES3::USE_8BIT_HDR,false); if (current_env && current_env->fx_enabled[VS::ENV_FX_HDR] && GLOBAL_DEF("rasterizer/debug_hdr",false)) { _debug_luminances(); } } current_env=NULL; current_debug=VS::SCENARIO_DEBUG_DISABLED; if (GLOBAL_DEF("rasterizer/debug_shadow_maps",false)) { _debug_shadows(); } //_debug_luminances(); //_debug_samplers(); if (using_canvas_bg) { using_canvas_bg=false; glColorMask(1,1,1,1); //don't touch alpha } #endif } void RasterizerSceneGLES3::render_shadow(RID p_light,RID p_shadow_atlas,int p_pass,InstanceBase** p_cull_result,int p_cull_count) { render_pass++; directional_light=NULL; LightInstance *light_instance = light_instance_owner.getornull(p_light); ERR_FAIL_COND(!light_instance); RasterizerStorageGLES3::Light *light = storage->light_owner.getornull(light_instance->light); ERR_FAIL_COND(!light); uint32_t x,y,width,height,vp_height; float dp_direction=0.0; float zfar=0; bool flip_facing=false; int custom_vp_size=0; GLuint fbo; int current_cubemap=-1; float bias=0; float normal_bias=0; CameraMatrix light_projection; Transform light_transform; if (light->type==VS::LIGHT_DIRECTIONAL) { //set pssm stuff if (light_instance->last_scene_shadow_pass!=scene_pass) { //assign rect if unassigned light_instance->light_directional_index = directional_shadow.current_light; light_instance->last_scene_shadow_pass=scene_pass; directional_shadow.current_light++; if (directional_shadow.light_count==1) { light_instance->directional_rect=Rect2(0,0,directional_shadow.size,directional_shadow.size); } else if (directional_shadow.light_count==2) { light_instance->directional_rect=Rect2(0,0,directional_shadow.size,directional_shadow.size/2); if (light_instance->light_directional_index==1) { light_instance->directional_rect.pos.x+=light_instance->directional_rect.size.x; } } else { //3 and 4 light_instance->directional_rect=Rect2(0,0,directional_shadow.size/2,directional_shadow.size/2); if (light_instance->light_directional_index&1) { light_instance->directional_rect.pos.x+=light_instance->directional_rect.size.x; } if (light_instance->light_directional_index/2) { light_instance->directional_rect.pos.y+=light_instance->directional_rect.size.y; } } } light_projection=light_instance->shadow_transform[p_pass].camera; light_transform=light_instance->shadow_transform[p_pass].transform; x=light_instance->directional_rect.pos.x; y=light_instance->directional_rect.pos.y; width=light_instance->directional_rect.size.x; height=light_instance->directional_rect.size.y; if (light->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_4_SPLITS) { width/=2; height/=2; if (p_pass==0) { } else if (p_pass==1) { x+=width; } else if (p_pass==2) { y+=height; } else if (p_pass==3) { x+=width; y+=height; } } else if (light->directional_shadow_mode==VS::LIGHT_DIRECTIONAL_SHADOW_PARALLEL_2_SPLITS) { height/=2; if (p_pass==0) { } else { y+=height; } } zfar=light->param[VS::LIGHT_PARAM_RANGE]; bias=light->param[VS::LIGHT_PARAM_SHADOW_BIAS]; normal_bias=light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS]; fbo=directional_shadow.fbo; vp_height=directional_shadow.size; } else { //set from shadow atlas ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); ERR_FAIL_COND(!shadow_atlas); ERR_FAIL_COND(!shadow_atlas->shadow_owners.has(p_light)); fbo=shadow_atlas->fbo; vp_height=shadow_atlas->size; uint32_t key = shadow_atlas->shadow_owners[p_light]; uint32_t quadrant = (key >> ShadowAtlas::QUADRANT_SHIFT)&0x3; uint32_t shadow = key & ShadowAtlas::SHADOW_INDEX_MASK; ERR_FAIL_INDEX(shadow,shadow_atlas->quadrants[quadrant].shadows.size()); uint32_t quadrant_size = shadow_atlas->size>>1; x=(quadrant&1)*quadrant_size; y=(quadrant>>1)*quadrant_size; uint32_t shadow_size = (quadrant_size / shadow_atlas->quadrants[quadrant].subdivision); x+=(shadow % shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; y+=(shadow / shadow_atlas->quadrants[quadrant].subdivision) * shadow_size; width=shadow_size; height=shadow_size; if (light->type==VS::LIGHT_OMNI) { if (light->omni_shadow_mode==VS::LIGHT_OMNI_SHADOW_CUBE) { int cubemap_index=shadow_cubemaps.size()-1; for(int i=shadow_cubemaps.size()-1;i>=0;i--) { //find appropriate cubemap to render to if (shadow_cubemaps[i].size>shadow_size*2) break; cubemap_index=i; } fbo=shadow_cubemaps[cubemap_index].fbo_id[p_pass]; light_projection=light_instance->shadow_transform[0].camera; light_transform=light_instance->shadow_transform[0].transform; custom_vp_size=shadow_cubemaps[cubemap_index].size; zfar=light->param[VS::LIGHT_PARAM_RANGE]; current_cubemap=cubemap_index; } else { light_projection=light_instance->shadow_transform[0].camera; light_transform=light_instance->shadow_transform[0].transform; if (light->omni_shadow_detail==VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { height/=2; y+=p_pass*height; } else { width/=2; x+=p_pass*width; } dp_direction = p_pass==0?1.0:-1.0; flip_facing = (p_pass == 1); zfar=light->param[VS::LIGHT_PARAM_RANGE]; bias=light->param[VS::LIGHT_PARAM_SHADOW_BIAS]; state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID,true); } } else if (light->type==VS::LIGHT_SPOT) { light_projection=light_instance->shadow_transform[0].camera; light_transform=light_instance->shadow_transform[0].transform; dp_direction = 1.0; flip_facing = false; zfar=light->param[VS::LIGHT_PARAM_RANGE]; bias=light->param[VS::LIGHT_PARAM_SHADOW_BIAS]; normal_bias=light->param[VS::LIGHT_PARAM_SHADOW_NORMAL_BIAS]; } } //todo hacer que se redibuje cuando corresponde render_list.clear(); _fill_render_list(p_cull_result,p_cull_count,true); render_list.sort_by_depth(false); //shadow is front to back for performance glDepthMask(true); glColorMask(1,1,1,1); glDisable(GL_BLEND); glDisable(GL_DITHER); glEnable(GL_DEPTH_TEST); glBindFramebuffer(GL_FRAMEBUFFER,fbo); if (custom_vp_size) { glViewport(0,0,custom_vp_size,custom_vp_size); glScissor(0,0,custom_vp_size,custom_vp_size); } else { glViewport(x,y,width,height); glScissor(x,y,width,height); } glEnable(GL_SCISSOR_TEST); glClearDepth(1.0f); glClear(GL_DEPTH_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); state.ubo_data.shadow_z_offset=bias; state.ubo_data.shadow_slope_scale=normal_bias; state.ubo_data.shadow_dual_paraboloid_render_side=dp_direction; state.ubo_data.shadow_dual_paraboloid_render_zfar=zfar; _setup_environment(NULL,light_projection,light_transform); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH,true); _render_list(render_list.elements,render_list.element_count,light_transform,light_projection,0,!flip_facing,false,true,false,false); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH,false); state.scene_shader.set_conditional(SceneShaderGLES3::RENDER_DEPTH_DUAL_PARABOLOID,false); if (light->type==VS::LIGHT_OMNI && light->omni_shadow_mode==VS::LIGHT_OMNI_SHADOW_CUBE && p_pass==5) { //convert the chosen cubemap to dual paraboloid! ShadowAtlas *shadow_atlas = shadow_atlas_owner.getornull(p_shadow_atlas); glBindFramebuffer(GL_FRAMEBUFFER,shadow_atlas->fbo); state.cube_to_dp_shader.bind(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP,shadow_cubemaps[current_cubemap].cubemap); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_COMPARE_MODE, GL_NONE); glDisable(GL_CULL_FACE); for(int i=0;i<2;i++) { state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FLIP,i==1); state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_NEAR,light_projection.get_z_near()); state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::Z_FAR,light_projection.get_z_far()); state.cube_to_dp_shader.set_uniform(CubeToDpShaderGLES3::BIAS,light->param[VS::LIGHT_PARAM_SHADOW_BIAS]); uint32_t local_width=width,local_height=height; uint32_t local_x=x,local_y=y; if (light->omni_shadow_detail==VS::LIGHT_OMNI_SHADOW_DETAIL_HORIZONTAL) { local_height/=2; local_y+=i*local_height; } else { local_width/=2; local_x+=i*local_width; } glViewport(local_x,local_y,local_width,local_height); glScissor(local_x,local_y,local_width,local_height); glEnable(GL_SCISSOR_TEST); glClearDepth(1.0f); glClear(GL_DEPTH_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); //glDisable(GL_DEPTH_TEST); glDisable(GL_BLEND); _copy_screen(); } } glColorMask(1,1,1,1); } void RasterizerSceneGLES3::set_scene_pass(uint64_t p_pass) { scene_pass=p_pass; } bool RasterizerSceneGLES3::free(RID p_rid) { if (light_instance_owner.owns(p_rid)) { LightInstance *light_instance = light_instance_owner.getptr(p_rid); //remove from shadow atlases.. for(Set<RID>::Element *E=light_instance->shadow_atlases.front();E;E=E->next()) { ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(E->get()); ERR_CONTINUE(!shadow_atlas->shadow_owners.has(p_rid)); uint32_t key = shadow_atlas->shadow_owners[p_rid]; uint32_t q = (key>>ShadowAtlas::QUADRANT_SHIFT)&0x3; uint32_t s = key&ShadowAtlas::SHADOW_INDEX_MASK; shadow_atlas->quadrants[q].shadows[s].owner=RID(); shadow_atlas->shadow_owners.erase(p_rid); } light_instance_owner.free(p_rid); memdelete(light_instance); } else if (shadow_atlas_owner.owns(p_rid)) { ShadowAtlas *shadow_atlas = shadow_atlas_owner.get(p_rid); shadow_atlas_set_size(p_rid,0); shadow_atlas_owner.free(p_rid); memdelete(shadow_atlas); } else if (reflection_atlas_owner.owns(p_rid)) { ReflectionAtlas *reflection_atlas = reflection_atlas_owner.get(p_rid); reflection_atlas_set_size(p_rid,0); reflection_atlas_owner.free(p_rid); memdelete(reflection_atlas); } else if (reflection_probe_instance_owner.owns(p_rid)) { ReflectionProbeInstance *reflection_instance = reflection_probe_instance_owner.get(p_rid); reflection_probe_release_atlas_index(p_rid); reflection_probe_instance_owner.free(p_rid); memdelete(reflection_instance); } else { return false; } return true; } // http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html static _FORCE_INLINE_ float radicalInverse_VdC(uint32_t bits) { bits = (bits << 16u) | (bits >> 16u); bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); return float(bits) * 2.3283064365386963e-10f; // / 0x100000000 } static _FORCE_INLINE_ Vector2 Hammersley(uint32_t i, uint32_t N) { return Vector2(float(i) / float(N), radicalInverse_VdC(i)); } static _FORCE_INLINE_ Vector3 ImportanceSampleGGX(Vector2 Xi, float Roughness, Vector3 N) { float a = Roughness * Roughness; // DISNEY'S ROUGHNESS [see Burley'12 siggraph] // Compute distribution direction float Phi = 2.0f * Math_PI * Xi.x; float CosTheta = Math::sqrt((float)(1.0f - Xi.y) / (1.0f + (a*a - 1.0f) * Xi.y)); float SinTheta = Math::sqrt((float)Math::abs(1.0f - CosTheta * CosTheta)); // Convert to spherical direction Vector3 H; H.x = SinTheta * Math::cos(Phi); H.y = SinTheta * Math::sin(Phi); H.z = CosTheta; Vector3 UpVector = Math::abs(N.z) < 0.999 ? Vector3(0.0, 0.0, 1.0) : Vector3(1.0, 0.0, 0.0); Vector3 TangentX = UpVector.cross(N); TangentX.normalize(); Vector3 TangentY = N.cross(TangentX); // Tangent to world space return TangentX * H.x + TangentY * H.y + N * H.z; } static _FORCE_INLINE_ float GGX(float NdotV, float a) { float k = a / 2.0; return NdotV / (NdotV * (1.0 - k) + k); } // http://graphicrants.blogspot.com.au/2013/08/specular-brdf-reference.html float _FORCE_INLINE_ G_Smith(float a, float nDotV, float nDotL) { return GGX(nDotL, a * a) * GGX(nDotV, a * a); } void RasterizerSceneGLES3::_generate_brdf() { int brdf_size=GLOBAL_DEF("rendering/gles3/brdf_texture_size",64); PoolVector<uint8_t> brdf; brdf.resize(brdf_size*brdf_size*2); PoolVector<uint8_t>::Write w = brdf.write(); for(int i=0;i<brdf_size;i++) { for(int j=0;j<brdf_size;j++) { float Roughness = float(j)/(brdf_size-1); float NoV = float(i+1)/(brdf_size); //avoid storing nov0 Vector3 V; V.x = Math::sqrt( 1.0f - NoV * NoV ); V.y = 0.0; V.z = NoV; Vector3 N = Vector3(0.0, 0.0, 1.0); float A = 0; float B = 0; for(int s=0;s<512;s++) { Vector2 xi = Hammersley(s,512); Vector3 H = ImportanceSampleGGX( xi, Roughness, N ); Vector3 L = 2.0 * V.dot(H) * H - V; float NoL = CLAMP( L.z, 0.0, 1.0 ); float NoH = CLAMP( H.z, 0.0, 1.0 ); float VoH = CLAMP( V.dot(H), 0.0, 1.0 ); if ( NoL > 0.0 ) { float G = G_Smith( Roughness, NoV, NoL ); float G_Vis = G * VoH / (NoH * NoV); float Fc = pow(1.0 - VoH, 5.0); A += (1.0 - Fc) * G_Vis; B += Fc * G_Vis; } } A/=512.0; B/=512.0; int tofs = ((brdf_size-j-1)*brdf_size+i)*2; w[tofs+0]=CLAMP(A*255,0,255); w[tofs+1]=CLAMP(B*255,0,255); } } //set up brdf texture glGenTextures(1, &state.brdf_texture); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,state.brdf_texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RG8, brdf_size, brdf_size, 0, GL_RG, GL_UNSIGNED_BYTE,w.ptr()); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_2D,0); } void RasterizerSceneGLES3::initialize() { render_pass=0; state.scene_shader.init(); default_shader = storage->shader_create(VS::SHADER_SPATIAL); default_material = storage->material_create(); storage->material_set_shader(default_material,default_shader); default_shader_twosided = storage->shader_create(VS::SHADER_SPATIAL); default_material_twosided = storage->material_create(); storage->shader_set_code(default_shader_twosided,"render_mode cull_disabled;\n"); storage->material_set_shader(default_material_twosided,default_shader_twosided); glGenBuffers(1, &state.scene_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.scene_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(State::SceneDataUBO), &state.scene_ubo, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &state.env_radiance_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.env_radiance_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(State::EnvironmentRadianceUBO), &state.env_radiance_ubo, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); render_list.max_elements=GLOBAL_DEF("rendering/gles3/max_renderable_elements",(int)RenderList::DEFAULT_MAX_ELEMENTS); if (render_list.max_elements>1000000) render_list.max_elements=1000000; if (render_list.max_elements<1024) render_list.max_elements=1024; { //quad buffers glGenBuffers(1,&state.skybox_verts); glBindBuffer(GL_ARRAY_BUFFER,state.skybox_verts); glBufferData(GL_ARRAY_BUFFER,sizeof(Vector3)*8,NULL,GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind glGenVertexArrays(1,&state.skybox_array); glBindVertexArray(state.skybox_array); glBindBuffer(GL_ARRAY_BUFFER,state.skybox_verts); glVertexAttribPointer(VS::ARRAY_VERTEX,3,GL_FLOAT,GL_FALSE,sizeof(Vector3)*2,0); glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer(VS::ARRAY_TEX_UV,3,GL_FLOAT,GL_FALSE,sizeof(Vector3)*2,((uint8_t*)NULL)+sizeof(Vector3)); glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind } render_list.init(); state.cube_to_dp_shader.init(); _generate_brdf(); shadow_atlas_realloc_tolerance_msec=500; int max_shadow_cubemap_sampler_size=512; int cube_size = max_shadow_cubemap_sampler_size; glActiveTexture(GL_TEXTURE0); while(cube_size>=32) { ShadowCubeMap cube; cube.size=cube_size; glGenTextures(1,&cube.cubemap); glBindTexture(GL_TEXTURE_CUBE_MAP,cube.cubemap); //gen cubemap first for(int i=0;i<6;i++) { glTexImage2D(_cube_side_enum[i], 0, GL_DEPTH_COMPONENT, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Remove artifact on the edges of the shadowmap glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); //gen renderbuffers second, because it needs a complete cubemap for(int i=0;i<6;i++) { glGenFramebuffers(1, &cube.fbo_id[i]); glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo_id[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,_cube_side_enum[i], cube.cubemap, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE); } shadow_cubemaps.push_back(cube); cube_size>>=1; } { //directional light shadow directional_shadow.light_count=0; directional_shadow.size=nearest_power_of_2(GLOBAL_DEF("rendering/shadows/directional_shadow_size",2048)); glGenFramebuffers(1,&directional_shadow.fbo); glBindFramebuffer(GL_FRAMEBUFFER,directional_shadow.fbo); glGenTextures(1,&directional_shadow.depth); glBindTexture(GL_TEXTURE_2D,directional_shadow.depth); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, directional_shadow.size, directional_shadow.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D, directional_shadow.depth, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status!=GL_FRAMEBUFFER_COMPLETE) { ERR_PRINT("Directional shadow framebuffer status invalid"); } } { //spot and omni ubos int max_ubo_size; glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE,&max_ubo_size); const int ubo_light_size=160; state.ubo_light_size=ubo_light_size; state.max_ubo_lights=MIN(RenderList::MAX_LIGHTS,max_ubo_size/ubo_light_size); print_line("max ubo light: "+itos(state.max_ubo_lights)); state.spot_array_tmp = (uint8_t*)memalloc(ubo_light_size*state.max_ubo_lights); state.omni_array_tmp = (uint8_t*)memalloc(ubo_light_size*state.max_ubo_lights); glGenBuffers(1, &state.spot_array_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.spot_array_ubo); glBufferData(GL_UNIFORM_BUFFER, ubo_light_size*state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &state.omni_array_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.omni_array_ubo); glBufferData(GL_UNIFORM_BUFFER, ubo_light_size*state.max_ubo_lights, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); glGenBuffers(1, &state.directional_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.directional_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(LightDataUBO), NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.max_forward_lights_per_object=8; state.scene_shader.add_custom_define("#define MAX_LIGHT_DATA_STRUCTS "+itos(state.max_ubo_lights)+"\n"); state.scene_shader.add_custom_define("#define MAX_FORWARD_LIGHTS "+itos(state.max_forward_lights_per_object)+"\n"); state.max_ubo_reflections=MIN(RenderList::MAX_REFLECTIONS,max_ubo_size/sizeof(ReflectionProbeDataUBO)); print_line("max ubo reflections: "+itos(state.max_ubo_reflections)+" ubo size: "+itos(sizeof(ReflectionProbeDataUBO))); state.reflection_array_tmp = (uint8_t*)memalloc(sizeof(ReflectionProbeDataUBO)*state.max_ubo_reflections); glGenBuffers(1, &state.reflection_array_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.reflection_array_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(ReflectionProbeDataUBO)*state.max_ubo_reflections, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.scene_shader.add_custom_define("#define MAX_REFLECTION_DATA_STRUCTS "+itos(state.max_ubo_reflections)+"\n"); state.max_skeleton_bones=MIN(2048,max_ubo_size/(12*sizeof(float))); state.scene_shader.add_custom_define("#define MAX_SKELETON_BONES "+itos(state.max_skeleton_bones)+"\n"); } GLOBAL_DEF("rendering/gles3/shadow_filter_mode",1); GlobalConfig::get_singleton()->set_custom_property_info("rendering/gles3/shadow_filter_mode",PropertyInfo(Variant::INT,"rendering/gles3/shadow_filter_mode",PROPERTY_HINT_ENUM,"Disabled,PCF5,PCF13")); shadow_filter_mode=SHADOW_FILTER_NEAREST; { //reflection cubemaps int max_reflection_cubemap_sampler_size=512; int cube_size = max_reflection_cubemap_sampler_size; glActiveTexture(GL_TEXTURE0); bool use_float=true; GLenum internal_format = use_float?GL_RGBA16F:GL_RGB10_A2; GLenum format = GL_RGBA; GLenum type = use_float?GL_HALF_FLOAT:GL_UNSIGNED_INT_2_10_10_10_REV; while(cube_size>=32) { ReflectionCubeMap cube; cube.size=cube_size; glGenTextures(1,&cube.depth); glBindTexture(GL_TEXTURE_2D,cube.depth); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, cube.size, cube.size, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glGenTextures(1,&cube.cubemap); glBindTexture(GL_TEXTURE_CUBE_MAP,cube.cubemap); //gen cubemap first for(int i=0;i<6;i++) { glTexImage2D(_cube_side_enum[i], 0, internal_format, cube.size, cube.size, 0, format, type, NULL); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Remove artifact on the edges of the reflectionmap glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); //gen renderbuffers second, because it needs a complete cubemap for(int i=0;i<6;i++) { glGenFramebuffers(1, &cube.fbo_id[i]); glBindFramebuffer(GL_FRAMEBUFFER, cube.fbo_id[i]); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,_cube_side_enum[i], cube.cubemap, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,GL_TEXTURE_2D, cube.depth, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE); } reflection_cubemaps.push_back(cube); cube_size>>=1; } } { uint32_t immediate_buffer_size=GLOBAL_DEF("rendering/buffers/immediate_buffer_size_kb",2048); glGenBuffers(1, &state.immediate_buffer); glBindBuffer(GL_ARRAY_BUFFER, state.immediate_buffer); glBufferData(GL_ARRAY_BUFFER, immediate_buffer_size*1024, NULL, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenVertexArrays(1,&state.immediate_array); } #ifdef GLES_OVER_GL //"desktop" opengl needs this. glEnable(GL_PROGRAM_POINT_SIZE); #endif state.resolve_shader.init(); state.ssr_shader.init(); state.effect_blur_shader.init(); state.sss_shader.init(); state.ssao_minify_shader.init(); state.ssao_shader.init(); state.ssao_blur_shader.init(); state.exposure_shader.init(); state.tonemap_shader.init(); { GLOBAL_DEF("rendering/ssurf_scattering/quality",1); GlobalConfig::get_singleton()->set_custom_property_info("rendering/ssurf_scattering/quality",PropertyInfo(Variant::INT,"rendering/ssurf_scattering/quality",PROPERTY_HINT_ENUM,"Low,Medium,High")); GLOBAL_DEF("rendering/ssurf_scattering/max_size",1.0); GlobalConfig::get_singleton()->set_custom_property_info("rendering/ssurf_scattering/max_size",PropertyInfo(Variant::INT,"rendering/ssurf_scattering/max_size",PROPERTY_HINT_RANGE,"0.01,8,0.01")); GLOBAL_DEF("rendering/ssurf_scattering/follow_surface",false); GLOBAL_DEF("rendering/reflections/high_quality_vct_gi",true); } exposure_shrink_size=243; int max_exposure_shrink_size=exposure_shrink_size; while(max_exposure_shrink_size>0) { RasterizerStorageGLES3::RenderTarget::Exposure e; glGenFramebuffers(1, &e.fbo); glBindFramebuffer(GL_FRAMEBUFFER, e.fbo); glGenTextures(1, &e.color); glBindTexture(GL_TEXTURE_2D, e.color); glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, max_exposure_shrink_size, max_exposure_shrink_size, 0, GL_RED, GL_FLOAT, NULL); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, e.color, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); exposure_shrink.push_back(e); max_exposure_shrink_size/=3; GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); ERR_CONTINUE(status!=GL_FRAMEBUFFER_COMPLETE); } } void RasterizerSceneGLES3::iteration() { shadow_filter_mode=ShadowFilterMode(int(GlobalConfig::get_singleton()->get("rendering/gles3/shadow_filter_mode"))); subsurface_scatter_follow_surface=GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/follow_surface"); subsurface_scatter_quality=SubSurfaceScatterQuality(int(GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/quality"))); subsurface_scatter_size=GlobalConfig::get_singleton()->get("rendering/ssurf_scattering/max_size"); state.scene_shader.set_conditional(SceneShaderGLES3::VCT_QUALITY_HIGH,GlobalConfig::get_singleton()->get("rendering/reflections/high_quality_vct_gi")); } void RasterizerSceneGLES3::finalize(){ } RasterizerSceneGLES3::RasterizerSceneGLES3() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_pitch_shift.cpp
298
#include "audio_effect_pitch_shift.h" #include "servers/audio_server.h" #include "math_funcs.h" /**************************************************************************** * * NAME: smbPitchShift.cpp * VERSION: 1.2 * HOME URL: http://blogs.zynaptiq.com/bernsee * KNOWN BUGS: none * * SYNOPSIS: Routine for doing pitch shifting while maintaining * duration using the Short Time Fourier Transform. * * DESCRIPTION: The routine takes a pitchShift factor value which is between 0.5 * (one octave down) and 2. (one octave up). A value of exactly 1 does not change * the pitch. numSampsToProcess tells the routine how many samples in indata[0... * numSampsToProcess-1] should be pitch shifted and moved to outdata[0 ... * numSampsToProcess-1]. The two buffers can be identical (ie. it can process the * data in-place). fftFrameSize defines the FFT frame size used for the * processing. Typical values are 1024, 2048 and 4096. It may be any value <= * MAX_FRAME_LENGTH but it MUST be a power of 2. osamp is the STFT * oversampling factor which also determines the overlap between adjacent STFT * frames. It should at least be 4 for moderate scaling ratios. A value of 32 is * recommended for best quality. sampleRate takes the sample rate for the signal * in unit Hz, ie. 44100 for 44.1 kHz audio. The data passed to the routine in * indata[] should be in the range [-1.0, 1.0), which is also the output range * for the data, make sure you scale the data accordingly (for 16bit signed integers * you would have to divide (and multiply) by 32768). * * COPYRIGHT 1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com> * * The Wide Open License (WOL) * * Permission to use, copy, modify, distribute and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice and this license appear in all source copies. * THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF * ANY KIND. See http://www.dspguru.com/wol.htm for more information. * *****************************************************************************/ void SMBPitchShift::PitchShift(float pitchShift, long numSampsToProcess, long fftFrameSize, long osamp, float sampleRate, float *indata, float *outdata,int stride) { /* Routine smbPitchShift(). See top of file for explanation Purpose: doing pitch shifting while maintaining duration using the Short Time Fourier Transform. Author: (c)1999-2015 Stephan M. Bernsee <s.bernsee [AT] zynaptiq [DOT] com> */ double magn, phase, tmp, window, real, imag; double freqPerBin, expct; long i,k, qpd, index, inFifoLatency, stepSize, fftFrameSize2; /* set up some handy variables */ fftFrameSize2 = fftFrameSize/2; stepSize = fftFrameSize/osamp; freqPerBin = sampleRate/(double)fftFrameSize; expct = 2.*Math_PI*(double)stepSize/(double)fftFrameSize; inFifoLatency = fftFrameSize-stepSize; if (gRover == 0) gRover = inFifoLatency; /* initialize our static arrays */ /* main processing loop */ for (i = 0; i < numSampsToProcess; i++){ /* As long as we have not yet collected enough data just read in */ gInFIFO[gRover] = indata[i*stride]; outdata[i*stride] = gOutFIFO[gRover-inFifoLatency]; gRover++; /* now we have enough data for processing */ if (gRover >= fftFrameSize) { gRover = inFifoLatency; /* do windowing and re,im interleave */ for (k = 0; k < fftFrameSize;k++) { window = -.5*cos(2.*Math_PI*(double)k/(double)fftFrameSize)+.5; gFFTworksp[2*k] = gInFIFO[k] * window; gFFTworksp[2*k+1] = 0.; } /* ***************** ANALYSIS ******************* */ /* do transform */ smbFft(gFFTworksp, fftFrameSize, -1); /* this is the analysis step */ for (k = 0; k <= fftFrameSize2; k++) { /* de-interlace FFT buffer */ real = gFFTworksp[2*k]; imag = gFFTworksp[2*k+1]; /* compute magnitude and phase */ magn = 2.*sqrt(real*real + imag*imag); phase = atan2(imag,real); /* compute phase difference */ tmp = phase - gLastPhase[k]; gLastPhase[k] = phase; /* subtract expected phase difference */ tmp -= (double)k*expct; /* map delta phase into +/- Pi interval */ qpd = tmp/Math_PI; if (qpd >= 0) qpd += qpd&1; else qpd -= qpd&1; tmp -= Math_PI*(double)qpd; /* get deviation from bin frequency from the +/- Pi interval */ tmp = osamp*tmp/(2.*Math_PI); /* compute the k-th partials' true frequency */ tmp = (double)k*freqPerBin + tmp*freqPerBin; /* store magnitude and true frequency in analysis arrays */ gAnaMagn[k] = magn; gAnaFreq[k] = tmp; } /* ***************** PROCESSING ******************* */ /* this does the actual pitch shifting */ memset(gSynMagn, 0, fftFrameSize*sizeof(float)); memset(gSynFreq, 0, fftFrameSize*sizeof(float)); for (k = 0; k <= fftFrameSize2; k++) { index = k*pitchShift; if (index <= fftFrameSize2) { gSynMagn[index] += gAnaMagn[k]; gSynFreq[index] = gAnaFreq[k] * pitchShift; } } /* ***************** SYNTHESIS ******************* */ /* this is the synthesis step */ for (k = 0; k <= fftFrameSize2; k++) { /* get magnitude and true frequency from synthesis arrays */ magn = gSynMagn[k]; tmp = gSynFreq[k]; /* subtract bin mid frequency */ tmp -= (double)k*freqPerBin; /* get bin deviation from freq deviation */ tmp /= freqPerBin; /* take osamp into account */ tmp = 2.*Math_PI*tmp/osamp; /* add the overlap phase advance back in */ tmp += (double)k*expct; /* accumulate delta phase to get bin phase */ gSumPhase[k] += tmp; phase = gSumPhase[k]; /* get real and imag part and re-interleave */ gFFTworksp[2*k] = magn*cos(phase); gFFTworksp[2*k+1] = magn*sin(phase); } /* zero negative frequencies */ for (k = fftFrameSize+2; k < 2*fftFrameSize; k++) gFFTworksp[k] = 0.; /* do inverse transform */ smbFft(gFFTworksp, fftFrameSize, 1); /* do windowing and add to output accumulator */ for(k=0; k < fftFrameSize; k++) { window = -.5*cos(2.*Math_PI*(double)k/(double)fftFrameSize)+.5; gOutputAccum[k] += 2.*window*gFFTworksp[2*k]/(fftFrameSize2*osamp); } for (k = 0; k < stepSize; k++) gOutFIFO[k] = gOutputAccum[k]; /* shift accumulator */ memmove(gOutputAccum, gOutputAccum+stepSize, fftFrameSize*sizeof(float)); /* move input FIFO */ for (k = 0; k < inFifoLatency; k++) gInFIFO[k] = gInFIFO[k+stepSize]; } } } void SMBPitchShift::smbFft(float *fftBuffer, long fftFrameSize, long sign) /* FFT routine, (C)1996 S.M.Bernsee. Sign = -1 is FFT, 1 is iFFT (inverse) Fills fftBuffer[0...2*fftFrameSize-1] with the Fourier transform of the time domain data in fftBuffer[0...2*fftFrameSize-1]. The FFT array takes and returns the cosine and sine parts in an interleaved manner, ie. fftBuffer[0] = cosPart[0], fftBuffer[1] = sinPart[0], asf. fftFrameSize must be a power of 2. It expects a complex input signal (see footnote 2), ie. when working with 'common' audio signals our input signal has to be passed as {in[0],0.,in[1],0.,in[2],0.,...} asf. In that case, the transform of the frequencies of interest is in fftBuffer[0...fftFrameSize]. */ { float wr, wi, arg, *p1, *p2, temp; float tr, ti, ur, ui, *p1r, *p1i, *p2r, *p2i; long i, bitm, j, le, le2, k; for (i = 2; i < 2*fftFrameSize-2; i += 2) { for (bitm = 2, j = 0; bitm < 2*fftFrameSize; bitm <<= 1) { if (i & bitm) j++; j <<= 1; } if (i < j) { p1 = fftBuffer+i; p2 = fftBuffer+j; temp = *p1; *(p1++) = *p2; *(p2++) = temp; temp = *p1; *p1 = *p2; *p2 = temp; } } for (k = 0, le = 2; k < (long)(log(fftFrameSize)/log(2.)+.5); k++) { le <<= 1; le2 = le>>1; ur = 1.0; ui = 0.0; arg = Math_PI / (le2>>1); wr = cos(arg); wi = sign*sin(arg); for (j = 0; j < le2; j += 2) { p1r = fftBuffer+j; p1i = p1r+1; p2r = p1r+le2; p2i = p2r+1; for (i = j; i < 2*fftFrameSize; i += le) { tr = *p2r * ur - *p2i * ui; ti = *p2r * ui + *p2i * ur; *p2r = *p1r - tr; *p2i = *p1i - ti; *p1r += tr; *p1i += ti; p1r += le; p1i += le; p2r += le; p2i += le; } tr = ur*wr - ui*wi; ui = ur*wi + ui*wr; ur = tr; } } } void AudioEffectPitchShiftInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { float sample_rate = AudioServer::get_singleton()->get_mix_rate(); float *in_l = (float*)p_src_frames; float *in_r = in_l + 1; float *out_l = (float*)p_dst_frames; float *out_r = out_l + 1; shift_l.PitchShift(base->pitch_scale,p_frame_count,2048,4,sample_rate,in_l,out_l,2); shift_r.PitchShift(base->pitch_scale,p_frame_count,2048,4,sample_rate,in_r,out_r,2); } Ref<AudioEffectInstance> AudioEffectPitchShift::instance() { Ref<AudioEffectPitchShiftInstance> ins; ins.instance(); ins->base=Ref<AudioEffectPitchShift>(this); return ins; } void AudioEffectPitchShift::set_pitch_scale(float p_adjust) { pitch_scale=p_adjust; } float AudioEffectPitchShift::get_pitch_scale() const { return pitch_scale; } void AudioEffectPitchShift::_bind_methods() { ClassDB::bind_method(_MD("set_pitch_scale","rate"),&AudioEffectPitchShift::set_pitch_scale); ClassDB::bind_method(_MD("get_pitch_scale"),&AudioEffectPitchShift::get_pitch_scale); ADD_PROPERTY(PropertyInfo(Variant::REAL,"pitch_scale",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_pitch_scale"),_SCS("get_pitch_scale")); } AudioEffectPitchShift::AudioEffectPitchShift() { pitch_scale=1.0; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
thirdparty/zlib/gzread.c
654
/* gzread.c -- zlib functions for reading gzip files * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" /* Local functions */ local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *)); local int gz_avail OF((gz_statep)); local int gz_look OF((gz_statep)); local int gz_decomp OF((gz_statep)); local int gz_fetch OF((gz_statep)); local int gz_skip OF((gz_statep, z_off64_t)); local z_size_t gz_read OF((gz_statep, voidp, z_size_t)); /* Use read() to load a buffer -- return -1 on error, otherwise 0. Read from state->fd, and update state->eof, state->err, and state->msg as appropriate. This function needs to loop on read(), since read() is not guaranteed to read the number of bytes requested, depending on the type of descriptor. */ local int gz_load(state, buf, len, have) gz_statep state; unsigned char *buf; unsigned len; unsigned *have; { int ret; unsigned get, max = ((unsigned)-1 >> 2) + 1; *have = 0; do { get = len - *have; if (get > max) get = max; ret = read(state->fd, buf + *have, get); if (ret <= 0) break; *have += (unsigned)ret; } while (*have < len); if (ret < 0) { gz_error(state, Z_ERRNO, zstrerror()); return -1; } if (ret == 0) state->eof = 1; return 0; } /* Load up input buffer and set eof flag if last data loaded -- return -1 on error, 0 otherwise. Note that the eof flag is set when the end of the input file is reached, even though there may be unused data in the buffer. Once that data has been used, no more attempts will be made to read the file. If strm->avail_in != 0, then the current data is moved to the beginning of the input buffer, and then the remainder of the buffer is loaded with the available data from the input file. */ local int gz_avail(state) gz_statep state; { unsigned got; z_streamp strm = &(state->strm); if (state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; if (state->eof == 0) { if (strm->avail_in) { /* copy what's there to the start */ unsigned char *p = state->in; unsigned const char *q = strm->next_in; unsigned n = strm->avail_in; do { *p++ = *q++; } while (--n); } if (gz_load(state, state->in + strm->avail_in, state->size - strm->avail_in, &got) == -1) return -1; strm->avail_in += got; strm->next_in = state->in; } return 0; } /* Look for gzip header, set up for inflate or copy. state->x.have must be 0. If this is the first time in, allocate required memory. state->how will be left unchanged if there is no more input data available, will be set to COPY if there is no gzip header and direct copying will be performed, or it will be set to GZIP for decompression. If direct copying, then leftover input data from the input buffer will be copied to the output buffer. In that case, all further file reads will be directly to either the output buffer or a user buffer. If decompressing, the inflate state will be initialized. gz_look() will return 0 on success or -1 on failure. */ local int gz_look(state) gz_statep state; { z_streamp strm = &(state->strm); /* allocate read buffers and inflate memory */ if (state->size == 0) { /* allocate buffers */ state->in = (unsigned char *)malloc(state->want); state->out = (unsigned char *)malloc(state->want << 1); if (state->in == NULL || state->out == NULL) { free(state->out); free(state->in); gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } state->size = state->want; /* allocate inflate memory */ state->strm.zalloc = Z_NULL; state->strm.zfree = Z_NULL; state->strm.opaque = Z_NULL; state->strm.avail_in = 0; state->strm.next_in = Z_NULL; if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) { /* gunzip */ free(state->out); free(state->in); state->size = 0; gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } } /* get at least the magic bytes in the input buffer */ if (strm->avail_in < 2) { if (gz_avail(state) == -1) return -1; if (strm->avail_in == 0) return 0; } /* look for gzip magic bytes -- if there, do gzip decoding (note: there is a logical dilemma here when considering the case of a partially written gzip file, to wit, if a single 31 byte is written, then we cannot tell whether this is a single-byte file, or just a partially written gzip file -- for here we assume that if a gzip file is being written, then the header will be written in a single operation, so that reading a single byte is sufficient indication that it is not a gzip file) */ if (strm->avail_in > 1 && strm->next_in[0] == 31 && strm->next_in[1] == 139) { inflateReset(strm); state->how = GZIP; state->direct = 0; return 0; } /* no gzip header -- if we were decoding gzip before, then this is trailing garbage. Ignore the trailing garbage and finish. */ if (state->direct == 0) { strm->avail_in = 0; state->eof = 1; state->x.have = 0; return 0; } /* doing raw i/o, copy any leftover input to output -- this assumes that the output buffer is larger than the input buffer, which also assures space for gzungetc() */ state->x.next = state->out; if (strm->avail_in) { memcpy(state->x.next, strm->next_in, strm->avail_in); state->x.have = strm->avail_in; strm->avail_in = 0; } state->how = COPY; state->direct = 1; return 0; } /* Decompress from input to the provided next_out and avail_out in the state. On return, state->x.have and state->x.next point to the just decompressed data. If the gzip stream completes, state->how is reset to LOOK to look for the next gzip stream or raw data, once state->x.have is depleted. Returns 0 on success, -1 on failure. */ local int gz_decomp(state) gz_statep state; { int ret = Z_OK; unsigned had; z_streamp strm = &(state->strm); /* fill output buffer up to end of deflate stream */ had = strm->avail_out; do { /* get more input for inflate() */ if (strm->avail_in == 0 && gz_avail(state) == -1) return -1; if (strm->avail_in == 0) { gz_error(state, Z_BUF_ERROR, "unexpected end of file"); break; } /* decompress and handle errors */ ret = inflate(strm, Z_NO_FLUSH); if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) { gz_error(state, Z_STREAM_ERROR, "internal error: inflate stream corrupt"); return -1; } if (ret == Z_MEM_ERROR) { gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } if (ret == Z_DATA_ERROR) { /* deflate stream invalid */ gz_error(state, Z_DATA_ERROR, strm->msg == NULL ? "compressed data error" : strm->msg); return -1; } } while (strm->avail_out && ret != Z_STREAM_END); /* update available output */ state->x.have = had - strm->avail_out; state->x.next = strm->next_out - state->x.have; /* if the gzip stream completed successfully, look for another */ if (ret == Z_STREAM_END) state->how = LOOK; /* good decompression */ return 0; } /* Fetch data and put it in the output buffer. Assumes state->x.have is 0. Data is either copied from the input file or decompressed from the input file depending on state->how. If state->how is LOOK, then a gzip header is looked for to determine whether to copy or decompress. Returns -1 on error, otherwise 0. gz_fetch() will leave state->how as COPY or GZIP unless the end of the input file has been reached and all data has been processed. */ local int gz_fetch(state) gz_statep state; { z_streamp strm = &(state->strm); do { switch(state->how) { case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */ if (gz_look(state) == -1) return -1; if (state->how == LOOK) return 0; break; case COPY: /* -> COPY */ if (gz_load(state, state->out, state->size << 1, &(state->x.have)) == -1) return -1; state->x.next = state->out; return 0; case GZIP: /* -> GZIP or LOOK (if end of gzip stream) */ strm->avail_out = state->size << 1; strm->next_out = state->out; if (gz_decomp(state) == -1) return -1; } } while (state->x.have == 0 && (!state->eof || strm->avail_in)); return 0; } /* Skip len uncompressed bytes of output. Return -1 on error, 0 on success. */ local int gz_skip(state, len) gz_statep state; z_off64_t len; { unsigned n; /* skip over len bytes or reach end-of-file, whichever comes first */ while (len) /* skip over whatever is in output buffer */ if (state->x.have) { n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ? (unsigned)len : state->x.have; state->x.have -= n; state->x.next += n; state->x.pos += n; len -= n; } /* output buffer empty -- return if we're at the end of the input */ else if (state->eof && state->strm.avail_in == 0) break; /* need more data to skip -- load up output buffer */ else { /* get more output, looking for header if required */ if (gz_fetch(state) == -1) return -1; } return 0; } /* Read len bytes into buf from file, or less than len up to the end of the input. Return the number of bytes read. If zero is returned, either the end of file was reached, or there was an error. state->err must be consulted in that case to determine which. */ local z_size_t gz_read(state, buf, len) gz_statep state; voidp buf; z_size_t len; { z_size_t got; unsigned n; /* if len is zero, avoid unnecessary operations */ if (len == 0) return 0; /* process a skip request */ if (state->seek) { state->seek = 0; if (gz_skip(state, state->skip) == -1) return 0; } /* get len bytes to buf, or less than len if at the end */ got = 0; do { /* set n to the maximum amount of len that fits in an unsigned int */ n = -1; if (n > len) n = len; /* first just try copying data from the output buffer */ if (state->x.have) { if (state->x.have < n) n = state->x.have; memcpy(buf, state->x.next, n); state->x.next += n; state->x.have -= n; } /* output buffer empty -- return if we're at the end of the input */ else if (state->eof && state->strm.avail_in == 0) { state->past = 1; /* tried to read past end */ break; } /* need output data -- for small len or new stream load up our output buffer */ else if (state->how == LOOK || n < (state->size << 1)) { /* get more output, looking for header if required */ if (gz_fetch(state) == -1) return 0; continue; /* no progress yet -- go back to copy above */ /* the copy above assures that we will leave with space in the output buffer, allowing at least one gzungetc() to succeed */ } /* large len -- read directly into user buffer */ else if (state->how == COPY) { /* read directly */ if (gz_load(state, (unsigned char *)buf, n, &n) == -1) return 0; } /* large len -- decompress directly into user buffer */ else { /* state->how == GZIP */ state->strm.avail_out = n; state->strm.next_out = (unsigned char *)buf; if (gz_decomp(state) == -1) return 0; n = state->x.have; state->x.have = 0; } /* update progress */ len -= n; buf = (char *)buf + n; got += n; state->x.pos += n; } while (len); /* return number of bytes read into user buffer */ return got; } /* -- see zlib.h -- */ int ZEXPORT gzread(file, buf, len) gzFile file; voidp buf; unsigned len; { gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no (serious) error */ if (state->mode != GZ_READ || (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids a flaw in the interface) */ if ((int)len < 0) { gz_error(state, Z_STREAM_ERROR, "request does not fit in an int"); return -1; } /* read len or fewer bytes to buf */ len = gz_read(state, buf, len); /* check for an error */ if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR) return -1; /* return the number of bytes read (this is assured to fit in an int) */ return (int)len; } /* -- see zlib.h -- */ z_size_t ZEXPORT gzfread(buf, size, nitems, file) voidp buf; z_size_t size; z_size_t nitems; gzFile file; { z_size_t len; gz_statep state; /* get internal structure */ if (file == NULL) return 0; state = (gz_statep)file; /* check that we're reading and that there's no (serious) error */ if (state->mode != GZ_READ || (state->err != Z_OK && state->err != Z_BUF_ERROR)) return 0; /* compute bytes to read -- error on overflow */ len = nitems * size; if (size && len / size != nitems) { gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t"); return 0; } /* read len or fewer bytes to buf, return the number of full items read */ return len ? gz_read(state, buf, len) / size : 0; } /* -- see zlib.h -- */ #ifdef Z_PREFIX_SET # undef z_gzgetc #else # undef gzgetc #endif int ZEXPORT gzgetc(file) gzFile file; { int ret; unsigned char buf[1]; gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no (serious) error */ if (state->mode != GZ_READ || (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* try output buffer (no need to check for skip request) */ if (state->x.have) { state->x.have--; state->x.pos++; return *(state->x.next)++; } /* nothing there -- try gz_read() */ ret = gz_read(state, buf, 1); return ret < 1 ? -1 : buf[0]; } int ZEXPORT gzgetc_(file) gzFile file; { return gzgetc(file); } /* -- see zlib.h -- */ int ZEXPORT gzungetc(c, file) int c; gzFile file; { gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're reading and that there's no (serious) error */ if (state->mode != GZ_READ || (state->err != Z_OK && state->err != Z_BUF_ERROR)) return -1; /* process a skip request */ if (state->seek) { state->seek = 0; if (gz_skip(state, state->skip) == -1) return -1; } /* can't push EOF */ if (c < 0) return -1; /* if output buffer empty, put byte at end (allows more pushing) */ if (state->x.have == 0) { state->x.have = 1; state->x.next = state->out + (state->size << 1) - 1; state->x.next[0] = (unsigned char)c; state->x.pos--; state->past = 0; return c; } /* if no room, give up (must have already done a gzungetc()) */ if (state->x.have == (state->size << 1)) { gz_error(state, Z_DATA_ERROR, "out of room to push characters"); return -1; } /* slide output data if needed and insert byte before existing data */ if (state->x.next == state->out) { unsigned char *src = state->out + state->x.have; unsigned char *dest = state->out + (state->size << 1); while (src > state->out) *--dest = *--src; state->x.next = dest; } state->x.have++; state->x.next--; state->x.next[0] = (unsigned char)c; state->x.pos--; state->past = 0; return c; } /* -- see zlib.h -- */ char * ZEXPORT gzgets(file, buf, len) gzFile file; char *buf; int len; { unsigned left, n; char *str; unsigned char *eol; gz_statep state; /* check parameters and get internal structure */ if (file == NULL || buf == NULL || len < 1) return NULL; state = (gz_statep)file; /* check that we're reading and that there's no (serious) error */ if (state->mode != GZ_READ || (state->err != Z_OK && state->err != Z_BUF_ERROR)) return NULL; /* process a skip request */ if (state->seek) { state->seek = 0; if (gz_skip(state, state->skip) == -1) return NULL; } /* copy output bytes up to new line or len - 1, whichever comes first -- append a terminating zero to the string (we don't check for a zero in the contents, let the user worry about that) */ str = buf; left = (unsigned)len - 1; if (left) do { /* assure that something is in the output buffer */ if (state->x.have == 0 && gz_fetch(state) == -1) return NULL; /* error */ if (state->x.have == 0) { /* end of file */ state->past = 1; /* read past end */ break; /* return what we have */ } /* look for end-of-line in current output buffer */ n = state->x.have > left ? left : state->x.have; eol = (unsigned char *)memchr(state->x.next, '\n', n); if (eol != NULL) n = (unsigned)(eol - state->x.next) + 1; /* copy through end-of-line, or remainder if not found */ memcpy(buf, state->x.next, n); state->x.have -= n; state->x.next += n; state->x.pos += n; left -= n; buf += n; } while (left && eol == NULL); /* return terminated string, or if nothing, end of file */ if (buf == str) return NULL; buf[0] = 0; return str; } /* -- see zlib.h -- */ int ZEXPORT gzdirect(file) gzFile file; { gz_statep state; /* get internal structure */ if (file == NULL) return 0; state = (gz_statep)file; /* if the state is not known, but we can find out, then do so (this is mainly for right after a gzopen() or gzdopen()) */ if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) (void)gz_look(state); /* return 1 if transparent, 0 if processing a gzip stream */ return state->direct; } /* -- see zlib.h -- */ int ZEXPORT gzclose_r(file) gzFile file; { int ret, err; gz_statep state; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; /* check that we're reading */ if (state->mode != GZ_READ) return Z_STREAM_ERROR; /* free memory and close file */ if (state->size) { inflateEnd(&(state->strm)); free(state->out); free(state->in); } err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK; gz_error(state, Z_OK, NULL); free(state->path); ret = close(state->fd); free(state); return ret ? Z_ERRNO : err; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
thirdparty/glad/glad.c
1,818
/* OpenGL loader generated by glad 0.1.13a0 on Fri Jan 6 19:27:07 2017. Language/Generator: C/C++ Specification: gl APIs: gl=3.3 Profile: compatibility Extensions: GL_ARB_debug_output Loader: True Local files: False Omit khrplatform: False Commandline: --profile="compatibility" --api="gl=3.3" --generator="c" --spec="gl" --extensions="GL_ARB_debug_output" Online: http://glad.dav1d.de/#profile=compatibility&language=c&specification=gl&loader=on&api=gl%3D3.3&extensions=GL_ARB_debug_output */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <glad/glad.h> static void* get_proc(const char *namez); #ifdef _WIN32 #include <windows.h> static HMODULE libGL; typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*); PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; static int open_gl(void) { libGL = LoadLibraryW(L"opengl32.dll"); if(libGL != NULL) { gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE)GetProcAddress( libGL, "wglGetProcAddress"); return gladGetProcAddressPtr != NULL; } return 0; } static void close_gl(void) { if(libGL != NULL) { FreeLibrary(libGL); libGL = NULL; } } #else #include <dlfcn.h> static void* libGL; #ifndef __APPLE__ typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*); PFNGLXGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr; #endif static int open_gl(void) { #ifdef __APPLE__ static const char *NAMES[] = { "../Frameworks/OpenGL.framework/OpenGL", "/Library/Frameworks/OpenGL.framework/OpenGL", "/System/Library/Frameworks/OpenGL.framework/OpenGL", "/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL" }; #else static const char *NAMES[] = {"libGL.so.1", "libGL.so"}; #endif unsigned int index = 0; for(index = 0; index < (sizeof(NAMES) / sizeof(NAMES[0])); index++) { libGL = dlopen(NAMES[index], RTLD_NOW | RTLD_GLOBAL); if(libGL != NULL) { #ifdef __APPLE__ return 1; #else gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL, "glXGetProcAddressARB"); return gladGetProcAddressPtr != NULL; #endif } } return 0; } static void close_gl() { if(libGL != NULL) { dlclose(libGL); libGL = NULL; } } #endif static void* get_proc(const char *namez) { void* result = NULL; if(libGL == NULL) return NULL; #ifndef __APPLE__ if(gladGetProcAddressPtr != NULL) { result = gladGetProcAddressPtr(namez); } #endif if(result == NULL) { #ifdef _WIN32 result = (void*)GetProcAddress(libGL, namez); #else result = dlsym(libGL, namez); #endif } return result; } int gladLoadGL(void) { int status = 0; if(open_gl()) { status = gladLoadGLLoader(&get_proc); close_gl(); } return status; } struct gladGLversionStruct GLVersion; #if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0) #define _GLAD_IS_SOME_NEW_VERSION 1 #endif static int max_loaded_major; static int max_loaded_minor; static const char *exts = NULL; static int num_exts_i = 0; static const char **exts_i = NULL; static int get_exts(void) { #ifdef _GLAD_IS_SOME_NEW_VERSION if(max_loaded_major < 3) { #endif exts = (const char *)glGetString(GL_EXTENSIONS); #ifdef _GLAD_IS_SOME_NEW_VERSION } else { int index; num_exts_i = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i); if (num_exts_i > 0) { exts_i = (const char **)realloc((void *)exts_i, num_exts_i * sizeof *exts_i); } if (exts_i == NULL) { return 0; } for(index = 0; index < num_exts_i; index++) { exts_i[index] = (const char*)glGetStringi(GL_EXTENSIONS, index); } } #endif return 1; } static void free_exts(void) { if (exts_i != NULL) { free((char **)exts_i); exts_i = NULL; } } static int has_ext(const char *ext) { #ifdef _GLAD_IS_SOME_NEW_VERSION if(max_loaded_major < 3) { #endif const char *extensions; const char *loc; const char *terminator; extensions = exts; if(extensions == NULL || ext == NULL) { return 0; } while(1) { loc = strstr(extensions, ext); if(loc == NULL) { return 0; } terminator = loc + strlen(ext); if((loc == extensions || *(loc - 1) == ' ') && (*terminator == ' ' || *terminator == '\0')) { return 1; } extensions = terminator; } #ifdef _GLAD_IS_SOME_NEW_VERSION } else { int index; for(index = 0; index < num_exts_i; index++) { const char *e = exts_i[index]; if(strcmp(e, ext) == 0) { return 1; } } } #endif return 0; } int GLAD_GL_VERSION_1_0; int GLAD_GL_VERSION_1_1; int GLAD_GL_VERSION_1_2; int GLAD_GL_VERSION_1_3; int GLAD_GL_VERSION_1_4; int GLAD_GL_VERSION_1_5; int GLAD_GL_VERSION_2_0; int GLAD_GL_VERSION_2_1; int GLAD_GL_VERSION_3_0; int GLAD_GL_VERSION_3_1; int GLAD_GL_VERSION_3_2; int GLAD_GL_VERSION_3_3; PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D; PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui; PFNGLWINDOWPOS2SPROC glad_glWindowPos2s; PFNGLWINDOWPOS2IPROC glad_glWindowPos2i; PFNGLWINDOWPOS2FPROC glad_glWindowPos2f; PFNGLWINDOWPOS2DPROC glad_glWindowPos2d; PFNGLVERTEX2FVPROC glad_glVertex2fv; PFNGLINDEXIPROC glad_glIndexi; PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer; PFNGLRECTDVPROC glad_glRectdv; PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D; PFNGLEVALCOORD2DPROC glad_glEvalCoord2d; PFNGLEVALCOORD2FPROC glad_glEvalCoord2f; PFNGLINDEXDPROC glad_glIndexd; PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv; PFNGLINDEXFPROC glad_glIndexf; PFNGLBINDSAMPLERPROC glad_glBindSampler; PFNGLLINEWIDTHPROC glad_glLineWidth; PFNGLCOLORP3UIVPROC glad_glColorP3uiv; PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v; PFNGLGETMAPFVPROC glad_glGetMapfv; PFNGLINDEXSPROC glad_glIndexs; PFNGLCOMPILESHADERPROC glad_glCompileShader; PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying; PFNGLWINDOWPOS2IVPROC glad_glWindowPos2iv; PFNGLINDEXFVPROC glad_glIndexfv; PFNGLFOGIVPROC glad_glFogiv; PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate; PFNGLRASTERPOS2FVPROC glad_glRasterPos2fv; PFNGLLIGHTMODELIVPROC glad_glLightModeliv; PFNGLCOLOR4UIPROC glad_glColor4ui; PFNGLSECONDARYCOLOR3FVPROC glad_glSecondaryColor3fv; PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui; PFNGLFOGFVPROC glad_glFogfv; PFNGLVERTEXP4UIPROC glad_glVertexP4ui; PFNGLENABLEIPROC glad_glEnablei; PFNGLVERTEX4IVPROC glad_glVertex4iv; PFNGLEVALCOORD1FVPROC glad_glEvalCoord1fv; PFNGLWINDOWPOS2SVPROC glad_glWindowPos2sv; PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui; PFNGLCREATESHADERPROC glad_glCreateShader; PFNGLISBUFFERPROC glad_glIsBuffer; PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv; PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers; PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D; PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D; PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f; PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate; PFNGLVERTEX4FVPROC glad_glVertex4fv; PFNGLBINDTEXTUREPROC glad_glBindTexture; PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s; PFNGLTEXCOORD2FVPROC glad_glTexCoord2fv; PFNGLSAMPLEMASKIPROC glad_glSampleMaski; PFNGLVERTEXP2UIPROC glad_glVertexP2ui; PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex; PFNGLTEXCOORD4FVPROC glad_glTexCoord4fv; PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv; PFNGLPOINTSIZEPROC glad_glPointSize; PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv; PFNGLDELETEPROGRAMPROC glad_glDeleteProgram; PFNGLCOLOR4BVPROC glad_glColor4bv; PFNGLRASTERPOS2FPROC glad_glRasterPos2f; PFNGLRASTERPOS2DPROC glad_glRasterPos2d; PFNGLLOADIDENTITYPROC glad_glLoadIdentity; PFNGLRASTERPOS2IPROC glad_glRasterPos2i; PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage; PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv; PFNGLCOLOR3BPROC glad_glColor3b; PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv; PFNGLEDGEFLAGPROC glad_glEdgeFlag; PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers; PFNGLVERTEX3DPROC glad_glVertex3d; PFNGLVERTEX3FPROC glad_glVertex3f; PFNGLVERTEX3IPROC glad_glVertex3i; PFNGLCOLOR3IPROC glad_glColor3i; PFNGLUNIFORM3FPROC glad_glUniform3f; PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv; PFNGLCOLOR3SPROC glad_glColor3s; PFNGLVERTEX3SPROC glad_glVertex3s; PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui; PFNGLCOLORMASKIPROC glad_glColorMaski; PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi; PFNGLTEXCOORD1IVPROC glad_glTexCoord1iv; PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer; PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui; PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv; PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex; PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f; PFNGLVERTEX2IVPROC glad_glVertex2iv; PFNGLCOLOR3SVPROC glad_glColor3sv; PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv; PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv; PFNGLNORMALPOINTERPROC glad_glNormalPointer; PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv; PFNGLVERTEX4SVPROC glad_glVertex4sv; PFNGLPASSTHROUGHPROC glad_glPassThrough; PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui; PFNGLFOGIPROC glad_glFogi; PFNGLBEGINPROC glad_glBegin; PFNGLEVALCOORD2DVPROC glad_glEvalCoord2dv; PFNGLCOLOR3UBVPROC glad_glColor3ubv; PFNGLVERTEXPOINTERPROC glad_glVertexPointer; PFNGLSECONDARYCOLOR3UIVPROC glad_glSecondaryColor3uiv; PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers; PFNGLDRAWARRAYSPROC glad_glDrawArrays; PFNGLUNIFORM1UIPROC glad_glUniform1ui; PFNGLMULTITEXCOORD1DPROC glad_glMultiTexCoord1d; PFNGLMULTITEXCOORD1FPROC glad_glMultiTexCoord1f; PFNGLLIGHTFVPROC glad_glLightfv; PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui; PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d; PFNGLCLEARPROC glad_glClear; PFNGLMULTITEXCOORD1IPROC glad_glMultiTexCoord1i; PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName; PFNGLMULTITEXCOORD1SPROC glad_glMultiTexCoord1s; PFNGLISENABLEDPROC glad_glIsEnabled; PFNGLSTENCILOPPROC glad_glStencilOp; PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv; PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D; PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv; PFNGLTRANSLATEFPROC glad_glTranslatef; PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub; PFNGLTRANSLATEDPROC glad_glTranslated; PFNGLTEXCOORD3SVPROC glad_glTexCoord3sv; PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation; PFNGLTEXIMAGE1DPROC glad_glTexImage1D; PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv; PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv; PFNGLSECONDARYCOLOR3BVPROC glad_glSecondaryColor3bv; PFNGLGETMATERIALFVPROC glad_glGetMaterialfv; PFNGLGETTEXIMAGEPROC glad_glGetTexImage; PFNGLFOGCOORDFVPROC glad_glFogCoordfv; PFNGLPIXELMAPUIVPROC glad_glPixelMapuiv; PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog; PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v; PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers; PFNGLINDEXSVPROC glad_glIndexsv; PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders; PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer; PFNGLVERTEX3IVPROC glad_glVertex3iv; PFNGLBITMAPPROC glad_glBitmap; PFNGLMATERIALIPROC glad_glMateriali; PFNGLISVERTEXARRAYPROC glad_glIsVertexArray; PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray; PFNGLGETQUERYIVPROC glad_glGetQueryiv; PFNGLTEXCOORD4FPROC glad_glTexCoord4f; PFNGLTEXCOORD4DPROC glad_glTexCoord4d; PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv; PFNGLTEXCOORD4IPROC glad_glTexCoord4i; PFNGLMATERIALFPROC glad_glMaterialf; PFNGLTEXCOORD4SPROC glad_glTexCoord4s; PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices; PFNGLISSHADERPROC glad_glIsShader; PFNGLMULTITEXCOORD2SPROC glad_glMultiTexCoord2s; PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv; PFNGLVERTEX3DVPROC glad_glVertex3dv; PFNGLGETINTEGER64VPROC glad_glGetInteger64v; PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv; PFNGLENABLEPROC glad_glEnable; PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv; PFNGLCOLOR4FVPROC glad_glColor4fv; PFNGLTEXCOORD1FVPROC glad_glTexCoord1fv; PFNGLTEXCOORD2SVPROC glad_glTexCoord2sv; PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv; PFNGLMULTITEXCOORD1DVPROC glad_glMultiTexCoord1dv; PFNGLMULTITEXCOORD2IPROC glad_glMultiTexCoord2i; PFNGLTEXCOORD3FVPROC glad_glTexCoord3fv; PFNGLSECONDARYCOLOR3USVPROC glad_glSecondaryColor3usv; PFNGLTEXGENFPROC glad_glTexGenf; PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv; PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui; PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui; PFNGLGETPOINTERVPROC glad_glGetPointerv; PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset; PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv; PFNGLNORMAL3FVPROC glad_glNormal3fv; PFNGLSECONDARYCOLOR3SPROC glad_glSecondaryColor3s; PFNGLDEPTHRANGEPROC glad_glDepthRange; PFNGLFRUSTUMPROC glad_glFrustum; PFNGLMULTITEXCOORD4SVPROC glad_glMultiTexCoord4sv; PFNGLDRAWBUFFERPROC glad_glDrawBuffer; PFNGLPUSHMATRIXPROC glad_glPushMatrix; PFNGLRASTERPOS3FVPROC glad_glRasterPos3fv; PFNGLORTHOPROC glad_glOrtho; PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced; PFNGLWINDOWPOS3SVPROC glad_glWindowPos3sv; PFNGLCLEARINDEXPROC glad_glClearIndex; PFNGLMAP1DPROC glad_glMap1d; PFNGLMAP1FPROC glad_glMap1f; PFNGLFLUSHPROC glad_glFlush; PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv; PFNGLINDEXIVPROC glad_glIndexiv; PFNGLRASTERPOS3SVPROC glad_glRasterPos3sv; PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv; PFNGLPIXELZOOMPROC glad_glPixelZoom; PFNGLFENCESYNCPROC glad_glFenceSync; PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays; PFNGLCOLORP3UIPROC glad_glColorP3ui; PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv; PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender; PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex; PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv; PFNGLLIGHTIPROC glad_glLighti; PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv; PFNGLLIGHTFPROC glad_glLightf; PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation; PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate; PFNGLGENSAMPLERSPROC glad_glGenSamplers; PFNGLCLAMPCOLORPROC glad_glClampColor; PFNGLUNIFORM4IVPROC glad_glUniform4iv; PFNGLCLEARSTENCILPROC glad_glClearStencil; PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv; PFNGLMULTITEXCOORD3FVPROC glad_glMultiTexCoord3fv; PFNGLGETPIXELMAPUIVPROC glad_glGetPixelMapuiv; PFNGLGENTEXTURESPROC glad_glGenTextures; PFNGLTEXCOORD4IVPROC glad_glTexCoord4iv; PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv; PFNGLINDEXPOINTERPROC glad_glIndexPointer; PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv; PFNGLISSYNCPROC glad_glIsSync; PFNGLVERTEX2FPROC glad_glVertex2f; PFNGLVERTEX2DPROC glad_glVertex2d; PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers; PFNGLUNIFORM2IPROC glad_glUniform2i; PFNGLMAPGRID2DPROC glad_glMapGrid2d; PFNGLMAPGRID2FPROC glad_glMapGrid2f; PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui; PFNGLVERTEX2IPROC glad_glVertex2i; PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer; PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer; PFNGLVERTEX2SPROC glad_glVertex2s; PFNGLNORMAL3BVPROC glad_glNormal3bv; PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv; PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange; PFNGLSECONDARYCOLOR3SVPROC glad_glSecondaryColor3sv; PFNGLVERTEX3SVPROC glad_glVertex3sv; PFNGLGENQUERIESPROC glad_glGenQueries; PFNGLGETPIXELMAPFVPROC glad_glGetPixelMapfv; PFNGLTEXENVFPROC glad_glTexEnvf; PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui; PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D; PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v; PFNGLFOGCOORDDPROC glad_glFogCoordd; PFNGLFOGCOORDFPROC glad_glFogCoordf; PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D; PFNGLTEXENVIPROC glad_glTexEnvi; PFNGLMULTITEXCOORD1IVPROC glad_glMultiTexCoord1iv; PFNGLISENABLEDIPROC glad_glIsEnabledi; PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui; PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i; PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed; PFNGLMULTITEXCOORD2DVPROC glad_glMultiTexCoord2dv; PFNGLUNIFORM2IVPROC glad_glUniform2iv; PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv; PFNGLUNIFORM4UIVPROC glad_glUniform4uiv; PFNGLMATRIXMODEPROC glad_glMatrixMode; PFNGLFEEDBACKBUFFERPROC glad_glFeedbackBuffer; PFNGLGETMAPIVPROC glad_glGetMapiv; PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D; PFNGLGETSHADERIVPROC glad_glGetShaderiv; PFNGLMULTITEXCOORD2DPROC glad_glMultiTexCoord2d; PFNGLMULTITEXCOORD2FPROC glad_glMultiTexCoord2f; PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation; PFNGLPRIORITIZETEXTURESPROC glad_glPrioritizeTextures; PFNGLCALLLISTPROC glad_glCallList; PFNGLSECONDARYCOLOR3UBVPROC glad_glSecondaryColor3ubv; PFNGLGETDOUBLEVPROC glad_glGetDoublev; PFNGLMULTITEXCOORD3IVPROC glad_glMultiTexCoord3iv; PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d; PFNGLLIGHTMODELFPROC glad_glLightModelf; PFNGLGETUNIFORMIVPROC glad_glGetUniformiv; PFNGLVERTEX2SVPROC glad_glVertex2sv; PFNGLLIGHTMODELIPROC glad_glLightModeli; PFNGLWINDOWPOS3IVPROC glad_glWindowPos3iv; PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv; PFNGLUNIFORM3FVPROC glad_glUniform3fv; PFNGLPIXELSTOREIPROC glad_glPixelStorei; PFNGLCALLLISTSPROC glad_glCallLists; PFNGLMAPBUFFERPROC glad_glMapBuffer; PFNGLSECONDARYCOLOR3DPROC glad_glSecondaryColor3d; PFNGLTEXCOORD3IPROC glad_glTexCoord3i; PFNGLMULTITEXCOORD4FVPROC glad_glMultiTexCoord4fv; PFNGLRASTERPOS3IPROC glad_glRasterPos3i; PFNGLSECONDARYCOLOR3BPROC glad_glSecondaryColor3b; PFNGLRASTERPOS3DPROC glad_glRasterPos3d; PFNGLRASTERPOS3FPROC glad_glRasterPos3f; PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D; PFNGLTEXCOORD3FPROC glad_glTexCoord3f; PFNGLDELETESYNCPROC glad_glDeleteSync; PFNGLTEXCOORD3DPROC glad_glTexCoord3d; PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample; PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv; PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements; PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv; PFNGLTEXCOORD3SPROC glad_glTexCoord3s; PFNGLUNIFORM3IVPROC glad_glUniform3iv; PFNGLRASTERPOS3SPROC glad_glRasterPos3s; PFNGLPOLYGONMODEPROC glad_glPolygonMode; PFNGLDRAWBUFFERSPROC glad_glDrawBuffers; PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv; PFNGLARETEXTURESRESIDENTPROC glad_glAreTexturesResident; PFNGLISLISTPROC glad_glIsList; PFNGLRASTERPOS2SVPROC glad_glRasterPos2sv; PFNGLRASTERPOS4SVPROC glad_glRasterPos4sv; PFNGLCOLOR4SPROC glad_glColor4s; PFNGLUSEPROGRAMPROC glad_glUseProgram; PFNGLLINESTIPPLEPROC glad_glLineStipple; PFNGLMULTITEXCOORD1SVPROC glad_glMultiTexCoord1sv; PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog; PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv; PFNGLMULTITEXCOORD2IVPROC glad_glMultiTexCoord2iv; PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv; PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray; PFNGLCOLOR4BPROC glad_glColor4b; PFNGLSECONDARYCOLOR3FPROC glad_glSecondaryColor3f; PFNGLCOLOR4FPROC glad_glColor4f; PFNGLCOLOR4DPROC glad_glColor4d; PFNGLCOLOR4IPROC glad_glColor4i; PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv; PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex; PFNGLRASTERPOS3IVPROC glad_glRasterPos3iv; PFNGLVERTEX2DVPROC glad_glVertex2dv; PFNGLTEXCOORD4SVPROC glad_glTexCoord4sv; PFNGLUNIFORM2UIVPROC glad_glUniform2uiv; PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D; PFNGLFINISHPROC glad_glFinish; PFNGLGETBOOLEANVPROC glad_glGetBooleanv; PFNGLDELETESHADERPROC glad_glDeleteShader; PFNGLDRAWELEMENTSPROC glad_glDrawElements; PFNGLRASTERPOS2SPROC glad_glRasterPos2s; PFNGLGETMAPDVPROC glad_glGetMapdv; PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv; PFNGLMATERIALFVPROC glad_glMaterialfv; PFNGLVIEWPORTPROC glad_glViewport; PFNGLUNIFORM1UIVPROC glad_glUniform1uiv; PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings; PFNGLINDEXDVPROC glad_glIndexdv; PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D; PFNGLTEXCOORD3IVPROC glad_glTexCoord3iv; PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i; PFNGLCLEARDEPTHPROC glad_glClearDepth; PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv; PFNGLTEXPARAMETERFPROC glad_glTexParameterf; PFNGLTEXPARAMETERIPROC glad_glTexParameteri; PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource; PFNGLTEXBUFFERPROC glad_glTexBuffer; PFNGLPOPNAMEPROC glad_glPopName; PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram; PFNGLPIXELSTOREFPROC glad_glPixelStoref; PFNGLUNIFORM3UIVPROC glad_glUniform3uiv; PFNGLRASTERPOS4FVPROC glad_glRasterPos4fv; PFNGLEVALCOORD1DVPROC glad_glEvalCoord1dv; PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv; PFNGLRECTIPROC glad_glRecti; PFNGLCOLOR4UBPROC glad_glColor4ub; PFNGLMULTTRANSPOSEMATRIXFPROC glad_glMultTransposeMatrixf; PFNGLRECTFPROC glad_glRectf; PFNGLRECTDPROC glad_glRectd; PFNGLNORMAL3SVPROC glad_glNormal3sv; PFNGLNEWLISTPROC glad_glNewList; PFNGLCOLOR4USPROC glad_glColor4us; PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv; PFNGLLINKPROGRAMPROC glad_glLinkProgram; PFNGLHINTPROC glad_glHint; PFNGLRECTSPROC glad_glRects; PFNGLTEXCOORD2DVPROC glad_glTexCoord2dv; PFNGLRASTERPOS4IVPROC glad_glRasterPos4iv; PFNGLGETSTRINGPROC glad_glGetString; PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv; PFNGLEDGEFLAGVPROC glad_glEdgeFlagv; PFNGLDETACHSHADERPROC glad_glDetachShader; PFNGLSCALEFPROC glad_glScalef; PFNGLENDQUERYPROC glad_glEndQuery; PFNGLSCALEDPROC glad_glScaled; PFNGLEDGEFLAGPOINTERPROC glad_glEdgeFlagPointer; PFNGLCOPYPIXELSPROC glad_glCopyPixels; PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui; PFNGLPOPATTRIBPROC glad_glPopAttrib; PFNGLDELETETEXTURESPROC glad_glDeleteTextures; PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate; PFNGLDELETEQUERIESPROC glad_glDeleteQueries; PFNGLNORMALP3UIVPROC glad_glNormalP3uiv; PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f; PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d; PFNGLINITNAMESPROC glad_glInitNames; PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v; PFNGLCOLOR3DVPROC glad_glColor3dv; PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i; PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv; PFNGLWAITSYNCPROC glad_glWaitSync; PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s; PFNGLCOLORMATERIALPROC glad_glColorMaterial; PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage; PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri; PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf; PFNGLUNIFORM1FPROC glad_glUniform1f; PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv; PFNGLRENDERMODEPROC glad_glRenderMode; PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage; PFNGLWINDOWPOS2DVPROC glad_glWindowPos2dv; PFNGLUNIFORM1IPROC glad_glUniform1i; PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib; PFNGLUNIFORM3IPROC glad_glUniform3i; PFNGLPIXELTRANSFERIPROC glad_glPixelTransferi; PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D; PFNGLDISABLEPROC glad_glDisable; PFNGLLOGICOPPROC glad_glLogicOp; PFNGLEVALPOINT2PROC glad_glEvalPoint2; PFNGLPIXELTRANSFERFPROC glad_glPixelTransferf; PFNGLSECONDARYCOLOR3IPROC glad_glSecondaryColor3i; PFNGLUNIFORM4UIPROC glad_glUniform4ui; PFNGLCOLOR3FPROC glad_glColor3f; PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer; PFNGLGETTEXENVFVPROC glad_glGetTexEnvfv; PFNGLRECTFVPROC glad_glRectfv; PFNGLCULLFACEPROC glad_glCullFace; PFNGLGETLIGHTFVPROC glad_glGetLightfv; PFNGLCOLOR3DPROC glad_glColor3d; PFNGLTEXGENDPROC glad_glTexGend; PFNGLTEXGENIPROC glad_glTexGeni; PFNGLMULTITEXCOORD3SPROC glad_glMultiTexCoord3s; PFNGLGETSTRINGIPROC glad_glGetStringi; PFNGLMULTITEXCOORD3IPROC glad_glMultiTexCoord3i; PFNGLMULTITEXCOORD3FPROC glad_glMultiTexCoord3f; PFNGLMULTITEXCOORD3DPROC glad_glMultiTexCoord3d; PFNGLATTACHSHADERPROC glad_glAttachShader; PFNGLFOGCOORDDVPROC glad_glFogCoorddv; PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv; PFNGLGETTEXGENFVPROC glad_glGetTexGenfv; PFNGLQUERYCOUNTERPROC glad_glQueryCounter; PFNGLFOGCOORDPOINTERPROC glad_glFogCoordPointer; PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex; PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D; PFNGLTEXGENIVPROC glad_glTexGeniv; PFNGLRASTERPOS2DVPROC glad_glRasterPos2dv; PFNGLSECONDARYCOLOR3DVPROC glad_glSecondaryColor3dv; PFNGLCLIENTACTIVETEXTUREPROC glad_glClientActiveTexture; PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv; PFNGLSECONDARYCOLOR3USPROC glad_glSecondaryColor3us; PFNGLNORMALP3UIPROC glad_glNormalP3ui; PFNGLTEXENVFVPROC glad_glTexEnvfv; PFNGLREADBUFFERPROC glad_glReadBuffer; PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv; PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced; PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap; PFNGLWINDOWPOS3FVPROC glad_glWindowPos3fv; PFNGLLIGHTMODELFVPROC glad_glLightModelfv; PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv; PFNGLDELETELISTSPROC glad_glDeleteLists; PFNGLGETCLIPPLANEPROC glad_glGetClipPlane; PFNGLVERTEX4DVPROC glad_glVertex4dv; PFNGLTEXCOORD2DPROC glad_glTexCoord2d; PFNGLPOPMATRIXPROC glad_glPopMatrix; PFNGLTEXCOORD2FPROC glad_glTexCoord2f; PFNGLCOLOR4IVPROC glad_glColor4iv; PFNGLINDEXUBVPROC glad_glIndexubv; PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer; PFNGLTEXCOORD2IPROC glad_glTexCoord2i; PFNGLRASTERPOS4DPROC glad_glRasterPos4d; PFNGLRASTERPOS4FPROC glad_glRasterPos4f; PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s; PFNGLTEXCOORD2SPROC glad_glTexCoord2s; PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer; PFNGLVERTEX3FVPROC glad_glVertex3fv; PFNGLTEXCOORD4DVPROC glad_glTexCoord4dv; PFNGLMATERIALIVPROC glad_glMaterialiv; PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv; PFNGLISPROGRAMPROC glad_glIsProgram; PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv; PFNGLVERTEX4SPROC glad_glVertex4s; PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv; PFNGLNORMAL3DVPROC glad_glNormal3dv; PFNGLUNIFORM4IPROC glad_glUniform4i; PFNGLACTIVETEXTUREPROC glad_glActiveTexture; PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray; PFNGLROTATEDPROC glad_glRotated; PFNGLROTATEFPROC glad_glRotatef; PFNGLVERTEX4IPROC glad_glVertex4i; PFNGLREADPIXELSPROC glad_glReadPixels; PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv; PFNGLLOADNAMEPROC glad_glLoadName; PFNGLUNIFORM4FPROC glad_glUniform4f; PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample; PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays; PFNGLSHADEMODELPROC glad_glShadeModel; PFNGLMAPGRID1DPROC glad_glMapGrid1d; PFNGLGETUNIFORMFVPROC glad_glGetUniformfv; PFNGLMAPGRID1FPROC glad_glMapGrid1f; PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv; PFNGLDISABLECLIENTSTATEPROC glad_glDisableClientState; PFNGLMULTITEXCOORD3SVPROC glad_glMultiTexCoord3sv; PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex; PFNGLSECONDARYCOLORPOINTERPROC glad_glSecondaryColorPointer; PFNGLALPHAFUNCPROC glad_glAlphaFunc; PFNGLUNIFORM1IVPROC glad_glUniform1iv; PFNGLMULTITEXCOORD4IVPROC glad_glMultiTexCoord4iv; PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv; PFNGLSTENCILFUNCPROC glad_glStencilFunc; PFNGLMULTITEXCOORD1FVPROC glad_glMultiTexCoord1fv; PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding; PFNGLCOLOR4UIVPROC glad_glColor4uiv; PFNGLRECTIVPROC glad_glRectiv; PFNGLCOLORP4UIPROC glad_glColorP4ui; PFNGLRASTERPOS3DVPROC glad_glRasterPos3dv; PFNGLEVALMESH2PROC glad_glEvalMesh2; PFNGLEVALMESH1PROC glad_glEvalMesh1; PFNGLTEXCOORDPOINTERPROC glad_glTexCoordPointer; PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv; PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv; PFNGLEVALCOORD2FVPROC glad_glEvalCoord2fv; PFNGLCOLOR4UBVPROC glad_glColor4ubv; PFNGLLOADTRANSPOSEMATRIXDPROC glad_glLoadTransposeMatrixd; PFNGLLOADTRANSPOSEMATRIXFPROC glad_glLoadTransposeMatrixf; PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i; PFNGLRASTERPOS2IVPROC glad_glRasterPos2iv; PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData; PFNGLTEXENVIVPROC glad_glTexEnviv; PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate; PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui; PFNGLGENBUFFERSPROC glad_glGenBuffers; PFNGLSELECTBUFFERPROC glad_glSelectBuffer; PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv; PFNGLPUSHATTRIBPROC glad_glPushAttrib; PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer; PFNGLBLENDFUNCPROC glad_glBlendFunc; PFNGLCREATEPROGRAMPROC glad_glCreateProgram; PFNGLTEXIMAGE3DPROC glad_glTexImage3D; PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer; PFNGLLIGHTIVPROC glad_glLightiv; PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex; PFNGLTEXGENFVPROC glad_glTexGenfv; PFNGLENDPROC glad_glEnd; PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers; PFNGLSCISSORPROC glad_glScissor; PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv; PFNGLCLIPPLANEPROC glad_glClipPlane; PFNGLPUSHNAMEPROC glad_glPushName; PFNGLTEXGENDVPROC glad_glTexGendv; PFNGLINDEXUBPROC glad_glIndexub; PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv; PFNGLSECONDARYCOLOR3IVPROC glad_glSecondaryColor3iv; PFNGLRASTERPOS4IPROC glad_glRasterPos4i; PFNGLMULTTRANSPOSEMATRIXDPROC glad_glMultTransposeMatrixd; PFNGLCLEARCOLORPROC glad_glClearColor; PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv; PFNGLNORMAL3SPROC glad_glNormal3s; PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv; PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv; PFNGLPOINTPARAMETERIPROC glad_glPointParameteri; PFNGLCOLORP4UIVPROC glad_glColorP4uiv; PFNGLBLENDCOLORPROC glad_glBlendColor; PFNGLWINDOWPOS3DPROC glad_glWindowPos3d; PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv; PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv; PFNGLUNIFORM3UIPROC glad_glUniform3ui; PFNGLCOLOR4DVPROC glad_glColor4dv; PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv; PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv; PFNGLUNIFORM2FVPROC glad_glUniform2fv; PFNGLSECONDARYCOLOR3UBPROC glad_glSecondaryColor3ub; PFNGLSECONDARYCOLOR3UIPROC glad_glSecondaryColor3ui; PFNGLTEXCOORD3DVPROC glad_glTexCoord3dv; PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv; PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange; PFNGLNORMAL3IVPROC glad_glNormal3iv; PFNGLWINDOWPOS3SPROC glad_glWindowPos3s; PFNGLPOINTPARAMETERFPROC glad_glPointParameterf; PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv; PFNGLWINDOWPOS3IPROC glad_glWindowPos3i; PFNGLMULTITEXCOORD4SPROC glad_glMultiTexCoord4s; PFNGLWINDOWPOS3FPROC glad_glWindowPos3f; PFNGLCOLOR3USPROC glad_glColor3us; PFNGLCOLOR3UIVPROC glad_glColor3uiv; PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv; PFNGLGETLIGHTIVPROC glad_glGetLightiv; PFNGLDEPTHFUNCPROC glad_glDepthFunc; PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D; PFNGLLISTBASEPROC glad_glListBase; PFNGLMULTITEXCOORD4FPROC glad_glMultiTexCoord4f; PFNGLCOLOR3UBPROC glad_glColor3ub; PFNGLMULTITEXCOORD4DPROC glad_glMultiTexCoord4d; PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv; PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv; PFNGLCOLOR3UIPROC glad_glColor3ui; PFNGLMULTITEXCOORD4IPROC glad_glMultiTexCoord4i; PFNGLGETPOLYGONSTIPPLEPROC glad_glGetPolygonStipple; PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync; PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui; PFNGLMULTITEXCOORD4DVPROC glad_glMultiTexCoord4dv; PFNGLCOLORMASKPROC glad_glColorMask; PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv; PFNGLBLENDEQUATIONPROC glad_glBlendEquation; PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation; PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv; PFNGLRASTERPOS4SPROC glad_glRasterPos4s; PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback; PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv; PFNGLMULTITEXCOORD3DVPROC glad_glMultiTexCoord3dv; PFNGLCOLOR4SVPROC glad_glColor4sv; PFNGLPOPCLIENTATTRIBPROC glad_glPopClientAttrib; PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback; PFNGLFOGFPROC glad_glFogf; PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv; PFNGLISSAMPLERPROC glad_glIsSampler; PFNGLVERTEXP3UIPROC glad_glVertexP3ui; PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor; PFNGLCOLOR3IVPROC glad_glColor3iv; PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D; PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D; PFNGLTEXCOORD1IPROC glad_glTexCoord1i; PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus; PFNGLTEXCOORD1DPROC glad_glTexCoord1d; PFNGLTEXCOORD1FPROC glad_glTexCoord1f; PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender; PFNGLENABLECLIENTSTATEPROC glad_glEnableClientState; PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation; PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv; PFNGLMULTITEXCOORD2SVPROC glad_glMultiTexCoord2sv; PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv; PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements; PFNGLTEXCOORD1SPROC glad_glTexCoord1s; PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase; PFNGLBUFFERSUBDATAPROC glad_glBufferSubData; PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv; PFNGLGENLISTSPROC glad_glGenLists; PFNGLCOLOR3BVPROC glad_glColor3bv; PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange; PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture; PFNGLGETTEXGENDVPROC glad_glGetTexGendv; PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays; PFNGLENDLISTPROC glad_glEndList; PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv; PFNGLUNIFORM2UIPROC glad_glUniform2ui; PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv; PFNGLCOLOR3USVPROC glad_glColor3usv; PFNGLWINDOWPOS2FVPROC glad_glWindowPos2fv; PFNGLDISABLEIPROC glad_glDisablei; PFNGLINDEXMASKPROC glad_glIndexMask; PFNGLPUSHCLIENTATTRIBPROC glad_glPushClientAttrib; PFNGLSHADERSOURCEPROC glad_glShaderSource; PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName; PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv; PFNGLCLEARACCUMPROC glad_glClearAccum; PFNGLGETSYNCIVPROC glad_glGetSynciv; PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv; PFNGLUNIFORM2FPROC glad_glUniform2f; PFNGLBEGINQUERYPROC glad_glBeginQuery; PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex; PFNGLBINDBUFFERPROC glad_glBindBuffer; PFNGLMAP2DPROC glad_glMap2d; PFNGLMAP2FPROC glad_glMap2f; PFNGLVERTEX4DPROC glad_glVertex4d; PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv; PFNGLTEXCOORD1SVPROC glad_glTexCoord1sv; PFNGLBUFFERDATAPROC glad_glBufferData; PFNGLEVALPOINT1PROC glad_glEvalPoint1; PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv; PFNGLTEXCOORD1DVPROC glad_glTexCoord1dv; PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui; PFNGLGETERRORPROC glad_glGetError; PFNGLGETTEXENVIVPROC glad_glGetTexEnviv; PFNGLGETPROGRAMIVPROC glad_glGetProgramiv; PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui; PFNGLGETFLOATVPROC glad_glGetFloatv; PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D; PFNGLMULTITEXCOORD2FVPROC glad_glMultiTexCoord2fv; PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv; PFNGLEVALCOORD1DPROC glad_glEvalCoord1d; PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv; PFNGLEVALCOORD1FPROC glad_glEvalCoord1f; PFNGLPIXELMAPFVPROC glad_glPixelMapfv; PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv; PFNGLGETPIXELMAPUSVPROC glad_glGetPixelMapusv; PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv; PFNGLGETINTEGERVPROC glad_glGetIntegerv; PFNGLACCUMPROC glad_glAccum; PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv; PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv; PFNGLRASTERPOS4DVPROC glad_glRasterPos4dv; PFNGLTEXCOORD2IVPROC glad_glTexCoord2iv; PFNGLISQUERYPROC glad_glIsQuery; PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv; PFNGLWINDOWPOS3DVPROC glad_glWindowPos3dv; PFNGLTEXIMAGE2DPROC glad_glTexImage2D; PFNGLSTENCILMASKPROC glad_glStencilMask; PFNGLDRAWPIXELSPROC glad_glDrawPixels; PFNGLMULTMATRIXDPROC glad_glMultMatrixd; PFNGLMULTMATRIXFPROC glad_glMultMatrixf; PFNGLISTEXTUREPROC glad_glIsTexture; PFNGLGETMATERIALIVPROC glad_glGetMaterialiv; PFNGLUNIFORM1FVPROC glad_glUniform1fv; PFNGLLOADMATRIXFPROC glad_glLoadMatrixf; PFNGLLOADMATRIXDPROC glad_glLoadMatrixd; PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv; PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv; PFNGLVERTEX4FPROC glad_glVertex4f; PFNGLRECTSVPROC glad_glRectsv; PFNGLCOLOR4USVPROC glad_glColor4usv; PFNGLPOLYGONSTIPPLEPROC glad_glPolygonStipple; PFNGLINTERLEAVEDARRAYSPROC glad_glInterleavedArrays; PFNGLNORMAL3IPROC glad_glNormal3i; PFNGLNORMAL3FPROC glad_glNormal3f; PFNGLNORMAL3DPROC glad_glNormal3d; PFNGLNORMAL3BPROC glad_glNormal3b; PFNGLPIXELMAPUSVPROC glad_glPixelMapusv; PFNGLGETTEXGENIVPROC glad_glGetTexGeniv; PFNGLARRAYELEMENTPROC glad_glArrayElement; PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData; PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv; PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d; PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f; PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv; PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v; PFNGLDEPTHMASKPROC glad_glDepthMask; PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s; PFNGLCOLOR3FVPROC glad_glColor3fv; PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample; PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv; PFNGLUNIFORM4FVPROC glad_glUniform4fv; PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform; PFNGLCOLORPOINTERPROC glad_glColorPointer; PFNGLFRONTFACEPROC glad_glFrontFace; PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v; PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv; int GLAD_GL_ARB_debug_output; PFNGLDEBUGMESSAGECONTROLARBPROC glad_glDebugMessageControlARB; PFNGLDEBUGMESSAGEINSERTARBPROC glad_glDebugMessageInsertARB; PFNGLDEBUGMESSAGECALLBACKARBPROC glad_glDebugMessageCallbackARB; PFNGLGETDEBUGMESSAGELOGARBPROC glad_glGetDebugMessageLogARB; static void load_GL_VERSION_1_0(GLADloadproc load) { if(!GLAD_GL_VERSION_1_0) return; glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace"); glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace"); glad_glHint = (PFNGLHINTPROC)load("glHint"); glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth"); glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize"); glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode"); glad_glScissor = (PFNGLSCISSORPROC)load("glScissor"); glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf"); glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv"); glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri"); glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv"); glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D"); glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D"); glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer"); glad_glClear = (PFNGLCLEARPROC)load("glClear"); glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor"); glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil"); glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth"); glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask"); glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask"); glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask"); glad_glDisable = (PFNGLDISABLEPROC)load("glDisable"); glad_glEnable = (PFNGLENABLEPROC)load("glEnable"); glad_glFinish = (PFNGLFINISHPROC)load("glFinish"); glad_glFlush = (PFNGLFLUSHPROC)load("glFlush"); glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc"); glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp"); glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc"); glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp"); glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc"); glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref"); glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei"); glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer"); glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels"); glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv"); glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev"); glad_glGetError = (PFNGLGETERRORPROC)load("glGetError"); glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv"); glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv"); glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage"); glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv"); glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv"); glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv"); glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv"); glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled"); glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange"); glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport"); glad_glNewList = (PFNGLNEWLISTPROC)load("glNewList"); glad_glEndList = (PFNGLENDLISTPROC)load("glEndList"); glad_glCallList = (PFNGLCALLLISTPROC)load("glCallList"); glad_glCallLists = (PFNGLCALLLISTSPROC)load("glCallLists"); glad_glDeleteLists = (PFNGLDELETELISTSPROC)load("glDeleteLists"); glad_glGenLists = (PFNGLGENLISTSPROC)load("glGenLists"); glad_glListBase = (PFNGLLISTBASEPROC)load("glListBase"); glad_glBegin = (PFNGLBEGINPROC)load("glBegin"); glad_glBitmap = (PFNGLBITMAPPROC)load("glBitmap"); glad_glColor3b = (PFNGLCOLOR3BPROC)load("glColor3b"); glad_glColor3bv = (PFNGLCOLOR3BVPROC)load("glColor3bv"); glad_glColor3d = (PFNGLCOLOR3DPROC)load("glColor3d"); glad_glColor3dv = (PFNGLCOLOR3DVPROC)load("glColor3dv"); glad_glColor3f = (PFNGLCOLOR3FPROC)load("glColor3f"); glad_glColor3fv = (PFNGLCOLOR3FVPROC)load("glColor3fv"); glad_glColor3i = (PFNGLCOLOR3IPROC)load("glColor3i"); glad_glColor3iv = (PFNGLCOLOR3IVPROC)load("glColor3iv"); glad_glColor3s = (PFNGLCOLOR3SPROC)load("glColor3s"); glad_glColor3sv = (PFNGLCOLOR3SVPROC)load("glColor3sv"); glad_glColor3ub = (PFNGLCOLOR3UBPROC)load("glColor3ub"); glad_glColor3ubv = (PFNGLCOLOR3UBVPROC)load("glColor3ubv"); glad_glColor3ui = (PFNGLCOLOR3UIPROC)load("glColor3ui"); glad_glColor3uiv = (PFNGLCOLOR3UIVPROC)load("glColor3uiv"); glad_glColor3us = (PFNGLCOLOR3USPROC)load("glColor3us"); glad_glColor3usv = (PFNGLCOLOR3USVPROC)load("glColor3usv"); glad_glColor4b = (PFNGLCOLOR4BPROC)load("glColor4b"); glad_glColor4bv = (PFNGLCOLOR4BVPROC)load("glColor4bv"); glad_glColor4d = (PFNGLCOLOR4DPROC)load("glColor4d"); glad_glColor4dv = (PFNGLCOLOR4DVPROC)load("glColor4dv"); glad_glColor4f = (PFNGLCOLOR4FPROC)load("glColor4f"); glad_glColor4fv = (PFNGLCOLOR4FVPROC)load("glColor4fv"); glad_glColor4i = (PFNGLCOLOR4IPROC)load("glColor4i"); glad_glColor4iv = (PFNGLCOLOR4IVPROC)load("glColor4iv"); glad_glColor4s = (PFNGLCOLOR4SPROC)load("glColor4s"); glad_glColor4sv = (PFNGLCOLOR4SVPROC)load("glColor4sv"); glad_glColor4ub = (PFNGLCOLOR4UBPROC)load("glColor4ub"); glad_glColor4ubv = (PFNGLCOLOR4UBVPROC)load("glColor4ubv"); glad_glColor4ui = (PFNGLCOLOR4UIPROC)load("glColor4ui"); glad_glColor4uiv = (PFNGLCOLOR4UIVPROC)load("glColor4uiv"); glad_glColor4us = (PFNGLCOLOR4USPROC)load("glColor4us"); glad_glColor4usv = (PFNGLCOLOR4USVPROC)load("glColor4usv"); glad_glEdgeFlag = (PFNGLEDGEFLAGPROC)load("glEdgeFlag"); glad_glEdgeFlagv = (PFNGLEDGEFLAGVPROC)load("glEdgeFlagv"); glad_glEnd = (PFNGLENDPROC)load("glEnd"); glad_glIndexd = (PFNGLINDEXDPROC)load("glIndexd"); glad_glIndexdv = (PFNGLINDEXDVPROC)load("glIndexdv"); glad_glIndexf = (PFNGLINDEXFPROC)load("glIndexf"); glad_glIndexfv = (PFNGLINDEXFVPROC)load("glIndexfv"); glad_glIndexi = (PFNGLINDEXIPROC)load("glIndexi"); glad_glIndexiv = (PFNGLINDEXIVPROC)load("glIndexiv"); glad_glIndexs = (PFNGLINDEXSPROC)load("glIndexs"); glad_glIndexsv = (PFNGLINDEXSVPROC)load("glIndexsv"); glad_glNormal3b = (PFNGLNORMAL3BPROC)load("glNormal3b"); glad_glNormal3bv = (PFNGLNORMAL3BVPROC)load("glNormal3bv"); glad_glNormal3d = (PFNGLNORMAL3DPROC)load("glNormal3d"); glad_glNormal3dv = (PFNGLNORMAL3DVPROC)load("glNormal3dv"); glad_glNormal3f = (PFNGLNORMAL3FPROC)load("glNormal3f"); glad_glNormal3fv = (PFNGLNORMAL3FVPROC)load("glNormal3fv"); glad_glNormal3i = (PFNGLNORMAL3IPROC)load("glNormal3i"); glad_glNormal3iv = (PFNGLNORMAL3IVPROC)load("glNormal3iv"); glad_glNormal3s = (PFNGLNORMAL3SPROC)load("glNormal3s"); glad_glNormal3sv = (PFNGLNORMAL3SVPROC)load("glNormal3sv"); glad_glRasterPos2d = (PFNGLRASTERPOS2DPROC)load("glRasterPos2d"); glad_glRasterPos2dv = (PFNGLRASTERPOS2DVPROC)load("glRasterPos2dv"); glad_glRasterPos2f = (PFNGLRASTERPOS2FPROC)load("glRasterPos2f"); glad_glRasterPos2fv = (PFNGLRASTERPOS2FVPROC)load("glRasterPos2fv"); glad_glRasterPos2i = (PFNGLRASTERPOS2IPROC)load("glRasterPos2i"); glad_glRasterPos2iv = (PFNGLRASTERPOS2IVPROC)load("glRasterPos2iv"); glad_glRasterPos2s = (PFNGLRASTERPOS2SPROC)load("glRasterPos2s"); glad_glRasterPos2sv = (PFNGLRASTERPOS2SVPROC)load("glRasterPos2sv"); glad_glRasterPos3d = (PFNGLRASTERPOS3DPROC)load("glRasterPos3d"); glad_glRasterPos3dv = (PFNGLRASTERPOS3DVPROC)load("glRasterPos3dv"); glad_glRasterPos3f = (PFNGLRASTERPOS3FPROC)load("glRasterPos3f"); glad_glRasterPos3fv = (PFNGLRASTERPOS3FVPROC)load("glRasterPos3fv"); glad_glRasterPos3i = (PFNGLRASTERPOS3IPROC)load("glRasterPos3i"); glad_glRasterPos3iv = (PFNGLRASTERPOS3IVPROC)load("glRasterPos3iv"); glad_glRasterPos3s = (PFNGLRASTERPOS3SPROC)load("glRasterPos3s"); glad_glRasterPos3sv = (PFNGLRASTERPOS3SVPROC)load("glRasterPos3sv"); glad_glRasterPos4d = (PFNGLRASTERPOS4DPROC)load("glRasterPos4d"); glad_glRasterPos4dv = (PFNGLRASTERPOS4DVPROC)load("glRasterPos4dv"); glad_glRasterPos4f = (PFNGLRASTERPOS4FPROC)load("glRasterPos4f"); glad_glRasterPos4fv = (PFNGLRASTERPOS4FVPROC)load("glRasterPos4fv"); glad_glRasterPos4i = (PFNGLRASTERPOS4IPROC)load("glRasterPos4i"); glad_glRasterPos4iv = (PFNGLRASTERPOS4IVPROC)load("glRasterPos4iv"); glad_glRasterPos4s = (PFNGLRASTERPOS4SPROC)load("glRasterPos4s"); glad_glRasterPos4sv = (PFNGLRASTERPOS4SVPROC)load("glRasterPos4sv"); glad_glRectd = (PFNGLRECTDPROC)load("glRectd"); glad_glRectdv = (PFNGLRECTDVPROC)load("glRectdv"); glad_glRectf = (PFNGLRECTFPROC)load("glRectf"); glad_glRectfv = (PFNGLRECTFVPROC)load("glRectfv"); glad_glRecti = (PFNGLRECTIPROC)load("glRecti"); glad_glRectiv = (PFNGLRECTIVPROC)load("glRectiv"); glad_glRects = (PFNGLRECTSPROC)load("glRects"); glad_glRectsv = (PFNGLRECTSVPROC)load("glRectsv"); glad_glTexCoord1d = (PFNGLTEXCOORD1DPROC)load("glTexCoord1d"); glad_glTexCoord1dv = (PFNGLTEXCOORD1DVPROC)load("glTexCoord1dv"); glad_glTexCoord1f = (PFNGLTEXCOORD1FPROC)load("glTexCoord1f"); glad_glTexCoord1fv = (PFNGLTEXCOORD1FVPROC)load("glTexCoord1fv"); glad_glTexCoord1i = (PFNGLTEXCOORD1IPROC)load("glTexCoord1i"); glad_glTexCoord1iv = (PFNGLTEXCOORD1IVPROC)load("glTexCoord1iv"); glad_glTexCoord1s = (PFNGLTEXCOORD1SPROC)load("glTexCoord1s"); glad_glTexCoord1sv = (PFNGLTEXCOORD1SVPROC)load("glTexCoord1sv"); glad_glTexCoord2d = (PFNGLTEXCOORD2DPROC)load("glTexCoord2d"); glad_glTexCoord2dv = (PFNGLTEXCOORD2DVPROC)load("glTexCoord2dv"); glad_glTexCoord2f = (PFNGLTEXCOORD2FPROC)load("glTexCoord2f"); glad_glTexCoord2fv = (PFNGLTEXCOORD2FVPROC)load("glTexCoord2fv"); glad_glTexCoord2i = (PFNGLTEXCOORD2IPROC)load("glTexCoord2i"); glad_glTexCoord2iv = (PFNGLTEXCOORD2IVPROC)load("glTexCoord2iv"); glad_glTexCoord2s = (PFNGLTEXCOORD2SPROC)load("glTexCoord2s"); glad_glTexCoord2sv = (PFNGLTEXCOORD2SVPROC)load("glTexCoord2sv"); glad_glTexCoord3d = (PFNGLTEXCOORD3DPROC)load("glTexCoord3d"); glad_glTexCoord3dv = (PFNGLTEXCOORD3DVPROC)load("glTexCoord3dv"); glad_glTexCoord3f = (PFNGLTEXCOORD3FPROC)load("glTexCoord3f"); glad_glTexCoord3fv = (PFNGLTEXCOORD3FVPROC)load("glTexCoord3fv"); glad_glTexCoord3i = (PFNGLTEXCOORD3IPROC)load("glTexCoord3i"); glad_glTexCoord3iv = (PFNGLTEXCOORD3IVPROC)load("glTexCoord3iv"); glad_glTexCoord3s = (PFNGLTEXCOORD3SPROC)load("glTexCoord3s"); glad_glTexCoord3sv = (PFNGLTEXCOORD3SVPROC)load("glTexCoord3sv"); glad_glTexCoord4d = (PFNGLTEXCOORD4DPROC)load("glTexCoord4d"); glad_glTexCoord4dv = (PFNGLTEXCOORD4DVPROC)load("glTexCoord4dv"); glad_glTexCoord4f = (PFNGLTEXCOORD4FPROC)load("glTexCoord4f"); glad_glTexCoord4fv = (PFNGLTEXCOORD4FVPROC)load("glTexCoord4fv"); glad_glTexCoord4i = (PFNGLTEXCOORD4IPROC)load("glTexCoord4i"); glad_glTexCoord4iv = (PFNGLTEXCOORD4IVPROC)load("glTexCoord4iv"); glad_glTexCoord4s = (PFNGLTEXCOORD4SPROC)load("glTexCoord4s"); glad_glTexCoord4sv = (PFNGLTEXCOORD4SVPROC)load("glTexCoord4sv"); glad_glVertex2d = (PFNGLVERTEX2DPROC)load("glVertex2d"); glad_glVertex2dv = (PFNGLVERTEX2DVPROC)load("glVertex2dv"); glad_glVertex2f = (PFNGLVERTEX2FPROC)load("glVertex2f"); glad_glVertex2fv = (PFNGLVERTEX2FVPROC)load("glVertex2fv"); glad_glVertex2i = (PFNGLVERTEX2IPROC)load("glVertex2i"); glad_glVertex2iv = (PFNGLVERTEX2IVPROC)load("glVertex2iv"); glad_glVertex2s = (PFNGLVERTEX2SPROC)load("glVertex2s"); glad_glVertex2sv = (PFNGLVERTEX2SVPROC)load("glVertex2sv"); glad_glVertex3d = (PFNGLVERTEX3DPROC)load("glVertex3d"); glad_glVertex3dv = (PFNGLVERTEX3DVPROC)load("glVertex3dv"); glad_glVertex3f = (PFNGLVERTEX3FPROC)load("glVertex3f"); glad_glVertex3fv = (PFNGLVERTEX3FVPROC)load("glVertex3fv"); glad_glVertex3i = (PFNGLVERTEX3IPROC)load("glVertex3i"); glad_glVertex3iv = (PFNGLVERTEX3IVPROC)load("glVertex3iv"); glad_glVertex3s = (PFNGLVERTEX3SPROC)load("glVertex3s"); glad_glVertex3sv = (PFNGLVERTEX3SVPROC)load("glVertex3sv"); glad_glVertex4d = (PFNGLVERTEX4DPROC)load("glVertex4d"); glad_glVertex4dv = (PFNGLVERTEX4DVPROC)load("glVertex4dv"); glad_glVertex4f = (PFNGLVERTEX4FPROC)load("glVertex4f"); glad_glVertex4fv = (PFNGLVERTEX4FVPROC)load("glVertex4fv"); glad_glVertex4i = (PFNGLVERTEX4IPROC)load("glVertex4i"); glad_glVertex4iv = (PFNGLVERTEX4IVPROC)load("glVertex4iv"); glad_glVertex4s = (PFNGLVERTEX4SPROC)load("glVertex4s"); glad_glVertex4sv = (PFNGLVERTEX4SVPROC)load("glVertex4sv"); glad_glClipPlane = (PFNGLCLIPPLANEPROC)load("glClipPlane"); glad_glColorMaterial = (PFNGLCOLORMATERIALPROC)load("glColorMaterial"); glad_glFogf = (PFNGLFOGFPROC)load("glFogf"); glad_glFogfv = (PFNGLFOGFVPROC)load("glFogfv"); glad_glFogi = (PFNGLFOGIPROC)load("glFogi"); glad_glFogiv = (PFNGLFOGIVPROC)load("glFogiv"); glad_glLightf = (PFNGLLIGHTFPROC)load("glLightf"); glad_glLightfv = (PFNGLLIGHTFVPROC)load("glLightfv"); glad_glLighti = (PFNGLLIGHTIPROC)load("glLighti"); glad_glLightiv = (PFNGLLIGHTIVPROC)load("glLightiv"); glad_glLightModelf = (PFNGLLIGHTMODELFPROC)load("glLightModelf"); glad_glLightModelfv = (PFNGLLIGHTMODELFVPROC)load("glLightModelfv"); glad_glLightModeli = (PFNGLLIGHTMODELIPROC)load("glLightModeli"); glad_glLightModeliv = (PFNGLLIGHTMODELIVPROC)load("glLightModeliv"); glad_glLineStipple = (PFNGLLINESTIPPLEPROC)load("glLineStipple"); glad_glMaterialf = (PFNGLMATERIALFPROC)load("glMaterialf"); glad_glMaterialfv = (PFNGLMATERIALFVPROC)load("glMaterialfv"); glad_glMateriali = (PFNGLMATERIALIPROC)load("glMateriali"); glad_glMaterialiv = (PFNGLMATERIALIVPROC)load("glMaterialiv"); glad_glPolygonStipple = (PFNGLPOLYGONSTIPPLEPROC)load("glPolygonStipple"); glad_glShadeModel = (PFNGLSHADEMODELPROC)load("glShadeModel"); glad_glTexEnvf = (PFNGLTEXENVFPROC)load("glTexEnvf"); glad_glTexEnvfv = (PFNGLTEXENVFVPROC)load("glTexEnvfv"); glad_glTexEnvi = (PFNGLTEXENVIPROC)load("glTexEnvi"); glad_glTexEnviv = (PFNGLTEXENVIVPROC)load("glTexEnviv"); glad_glTexGend = (PFNGLTEXGENDPROC)load("glTexGend"); glad_glTexGendv = (PFNGLTEXGENDVPROC)load("glTexGendv"); glad_glTexGenf = (PFNGLTEXGENFPROC)load("glTexGenf"); glad_glTexGenfv = (PFNGLTEXGENFVPROC)load("glTexGenfv"); glad_glTexGeni = (PFNGLTEXGENIPROC)load("glTexGeni"); glad_glTexGeniv = (PFNGLTEXGENIVPROC)load("glTexGeniv"); glad_glFeedbackBuffer = (PFNGLFEEDBACKBUFFERPROC)load("glFeedbackBuffer"); glad_glSelectBuffer = (PFNGLSELECTBUFFERPROC)load("glSelectBuffer"); glad_glRenderMode = (PFNGLRENDERMODEPROC)load("glRenderMode"); glad_glInitNames = (PFNGLINITNAMESPROC)load("glInitNames"); glad_glLoadName = (PFNGLLOADNAMEPROC)load("glLoadName"); glad_glPassThrough = (PFNGLPASSTHROUGHPROC)load("glPassThrough"); glad_glPopName = (PFNGLPOPNAMEPROC)load("glPopName"); glad_glPushName = (PFNGLPUSHNAMEPROC)load("glPushName"); glad_glClearAccum = (PFNGLCLEARACCUMPROC)load("glClearAccum"); glad_glClearIndex = (PFNGLCLEARINDEXPROC)load("glClearIndex"); glad_glIndexMask = (PFNGLINDEXMASKPROC)load("glIndexMask"); glad_glAccum = (PFNGLACCUMPROC)load("glAccum"); glad_glPopAttrib = (PFNGLPOPATTRIBPROC)load("glPopAttrib"); glad_glPushAttrib = (PFNGLPUSHATTRIBPROC)load("glPushAttrib"); glad_glMap1d = (PFNGLMAP1DPROC)load("glMap1d"); glad_glMap1f = (PFNGLMAP1FPROC)load("glMap1f"); glad_glMap2d = (PFNGLMAP2DPROC)load("glMap2d"); glad_glMap2f = (PFNGLMAP2FPROC)load("glMap2f"); glad_glMapGrid1d = (PFNGLMAPGRID1DPROC)load("glMapGrid1d"); glad_glMapGrid1f = (PFNGLMAPGRID1FPROC)load("glMapGrid1f"); glad_glMapGrid2d = (PFNGLMAPGRID2DPROC)load("glMapGrid2d"); glad_glMapGrid2f = (PFNGLMAPGRID2FPROC)load("glMapGrid2f"); glad_glEvalCoord1d = (PFNGLEVALCOORD1DPROC)load("glEvalCoord1d"); glad_glEvalCoord1dv = (PFNGLEVALCOORD1DVPROC)load("glEvalCoord1dv"); glad_glEvalCoord1f = (PFNGLEVALCOORD1FPROC)load("glEvalCoord1f"); glad_glEvalCoord1fv = (PFNGLEVALCOORD1FVPROC)load("glEvalCoord1fv"); glad_glEvalCoord2d = (PFNGLEVALCOORD2DPROC)load("glEvalCoord2d"); glad_glEvalCoord2dv = (PFNGLEVALCOORD2DVPROC)load("glEvalCoord2dv"); glad_glEvalCoord2f = (PFNGLEVALCOORD2FPROC)load("glEvalCoord2f"); glad_glEvalCoord2fv = (PFNGLEVALCOORD2FVPROC)load("glEvalCoord2fv"); glad_glEvalMesh1 = (PFNGLEVALMESH1PROC)load("glEvalMesh1"); glad_glEvalPoint1 = (PFNGLEVALPOINT1PROC)load("glEvalPoint1"); glad_glEvalMesh2 = (PFNGLEVALMESH2PROC)load("glEvalMesh2"); glad_glEvalPoint2 = (PFNGLEVALPOINT2PROC)load("glEvalPoint2"); glad_glAlphaFunc = (PFNGLALPHAFUNCPROC)load("glAlphaFunc"); glad_glPixelZoom = (PFNGLPIXELZOOMPROC)load("glPixelZoom"); glad_glPixelTransferf = (PFNGLPIXELTRANSFERFPROC)load("glPixelTransferf"); glad_glPixelTransferi = (PFNGLPIXELTRANSFERIPROC)load("glPixelTransferi"); glad_glPixelMapfv = (PFNGLPIXELMAPFVPROC)load("glPixelMapfv"); glad_glPixelMapuiv = (PFNGLPIXELMAPUIVPROC)load("glPixelMapuiv"); glad_glPixelMapusv = (PFNGLPIXELMAPUSVPROC)load("glPixelMapusv"); glad_glCopyPixels = (PFNGLCOPYPIXELSPROC)load("glCopyPixels"); glad_glDrawPixels = (PFNGLDRAWPIXELSPROC)load("glDrawPixels"); glad_glGetClipPlane = (PFNGLGETCLIPPLANEPROC)load("glGetClipPlane"); glad_glGetLightfv = (PFNGLGETLIGHTFVPROC)load("glGetLightfv"); glad_glGetLightiv = (PFNGLGETLIGHTIVPROC)load("glGetLightiv"); glad_glGetMapdv = (PFNGLGETMAPDVPROC)load("glGetMapdv"); glad_glGetMapfv = (PFNGLGETMAPFVPROC)load("glGetMapfv"); glad_glGetMapiv = (PFNGLGETMAPIVPROC)load("glGetMapiv"); glad_glGetMaterialfv = (PFNGLGETMATERIALFVPROC)load("glGetMaterialfv"); glad_glGetMaterialiv = (PFNGLGETMATERIALIVPROC)load("glGetMaterialiv"); glad_glGetPixelMapfv = (PFNGLGETPIXELMAPFVPROC)load("glGetPixelMapfv"); glad_glGetPixelMapuiv = (PFNGLGETPIXELMAPUIVPROC)load("glGetPixelMapuiv"); glad_glGetPixelMapusv = (PFNGLGETPIXELMAPUSVPROC)load("glGetPixelMapusv"); glad_glGetPolygonStipple = (PFNGLGETPOLYGONSTIPPLEPROC)load("glGetPolygonStipple"); glad_glGetTexEnvfv = (PFNGLGETTEXENVFVPROC)load("glGetTexEnvfv"); glad_glGetTexEnviv = (PFNGLGETTEXENVIVPROC)load("glGetTexEnviv"); glad_glGetTexGendv = (PFNGLGETTEXGENDVPROC)load("glGetTexGendv"); glad_glGetTexGenfv = (PFNGLGETTEXGENFVPROC)load("glGetTexGenfv"); glad_glGetTexGeniv = (PFNGLGETTEXGENIVPROC)load("glGetTexGeniv"); glad_glIsList = (PFNGLISLISTPROC)load("glIsList"); glad_glFrustum = (PFNGLFRUSTUMPROC)load("glFrustum"); glad_glLoadIdentity = (PFNGLLOADIDENTITYPROC)load("glLoadIdentity"); glad_glLoadMatrixf = (PFNGLLOADMATRIXFPROC)load("glLoadMatrixf"); glad_glLoadMatrixd = (PFNGLLOADMATRIXDPROC)load("glLoadMatrixd"); glad_glMatrixMode = (PFNGLMATRIXMODEPROC)load("glMatrixMode"); glad_glMultMatrixf = (PFNGLMULTMATRIXFPROC)load("glMultMatrixf"); glad_glMultMatrixd = (PFNGLMULTMATRIXDPROC)load("glMultMatrixd"); glad_glOrtho = (PFNGLORTHOPROC)load("glOrtho"); glad_glPopMatrix = (PFNGLPOPMATRIXPROC)load("glPopMatrix"); glad_glPushMatrix = (PFNGLPUSHMATRIXPROC)load("glPushMatrix"); glad_glRotated = (PFNGLROTATEDPROC)load("glRotated"); glad_glRotatef = (PFNGLROTATEFPROC)load("glRotatef"); glad_glScaled = (PFNGLSCALEDPROC)load("glScaled"); glad_glScalef = (PFNGLSCALEFPROC)load("glScalef"); glad_glTranslated = (PFNGLTRANSLATEDPROC)load("glTranslated"); glad_glTranslatef = (PFNGLTRANSLATEFPROC)load("glTranslatef"); } static void load_GL_VERSION_1_1(GLADloadproc load) { if(!GLAD_GL_VERSION_1_1) return; glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays"); glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements"); glad_glGetPointerv = (PFNGLGETPOINTERVPROC)load("glGetPointerv"); glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset"); glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D"); glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D"); glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D"); glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D"); glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D"); glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D"); glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture"); glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures"); glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures"); glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture"); glad_glArrayElement = (PFNGLARRAYELEMENTPROC)load("glArrayElement"); glad_glColorPointer = (PFNGLCOLORPOINTERPROC)load("glColorPointer"); glad_glDisableClientState = (PFNGLDISABLECLIENTSTATEPROC)load("glDisableClientState"); glad_glEdgeFlagPointer = (PFNGLEDGEFLAGPOINTERPROC)load("glEdgeFlagPointer"); glad_glEnableClientState = (PFNGLENABLECLIENTSTATEPROC)load("glEnableClientState"); glad_glIndexPointer = (PFNGLINDEXPOINTERPROC)load("glIndexPointer"); glad_glInterleavedArrays = (PFNGLINTERLEAVEDARRAYSPROC)load("glInterleavedArrays"); glad_glNormalPointer = (PFNGLNORMALPOINTERPROC)load("glNormalPointer"); glad_glTexCoordPointer = (PFNGLTEXCOORDPOINTERPROC)load("glTexCoordPointer"); glad_glVertexPointer = (PFNGLVERTEXPOINTERPROC)load("glVertexPointer"); glad_glAreTexturesResident = (PFNGLARETEXTURESRESIDENTPROC)load("glAreTexturesResident"); glad_glPrioritizeTextures = (PFNGLPRIORITIZETEXTURESPROC)load("glPrioritizeTextures"); glad_glIndexub = (PFNGLINDEXUBPROC)load("glIndexub"); glad_glIndexubv = (PFNGLINDEXUBVPROC)load("glIndexubv"); glad_glPopClientAttrib = (PFNGLPOPCLIENTATTRIBPROC)load("glPopClientAttrib"); glad_glPushClientAttrib = (PFNGLPUSHCLIENTATTRIBPROC)load("glPushClientAttrib"); } static void load_GL_VERSION_1_2(GLADloadproc load) { if(!GLAD_GL_VERSION_1_2) return; glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements"); glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D"); glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D"); glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D"); } static void load_GL_VERSION_1_3(GLADloadproc load) { if(!GLAD_GL_VERSION_1_3) return; glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture"); glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage"); glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D"); glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D"); glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D"); glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D"); glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D"); glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D"); glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage"); glad_glClientActiveTexture = (PFNGLCLIENTACTIVETEXTUREPROC)load("glClientActiveTexture"); glad_glMultiTexCoord1d = (PFNGLMULTITEXCOORD1DPROC)load("glMultiTexCoord1d"); glad_glMultiTexCoord1dv = (PFNGLMULTITEXCOORD1DVPROC)load("glMultiTexCoord1dv"); glad_glMultiTexCoord1f = (PFNGLMULTITEXCOORD1FPROC)load("glMultiTexCoord1f"); glad_glMultiTexCoord1fv = (PFNGLMULTITEXCOORD1FVPROC)load("glMultiTexCoord1fv"); glad_glMultiTexCoord1i = (PFNGLMULTITEXCOORD1IPROC)load("glMultiTexCoord1i"); glad_glMultiTexCoord1iv = (PFNGLMULTITEXCOORD1IVPROC)load("glMultiTexCoord1iv"); glad_glMultiTexCoord1s = (PFNGLMULTITEXCOORD1SPROC)load("glMultiTexCoord1s"); glad_glMultiTexCoord1sv = (PFNGLMULTITEXCOORD1SVPROC)load("glMultiTexCoord1sv"); glad_glMultiTexCoord2d = (PFNGLMULTITEXCOORD2DPROC)load("glMultiTexCoord2d"); glad_glMultiTexCoord2dv = (PFNGLMULTITEXCOORD2DVPROC)load("glMultiTexCoord2dv"); glad_glMultiTexCoord2f = (PFNGLMULTITEXCOORD2FPROC)load("glMultiTexCoord2f"); glad_glMultiTexCoord2fv = (PFNGLMULTITEXCOORD2FVPROC)load("glMultiTexCoord2fv"); glad_glMultiTexCoord2i = (PFNGLMULTITEXCOORD2IPROC)load("glMultiTexCoord2i"); glad_glMultiTexCoord2iv = (PFNGLMULTITEXCOORD2IVPROC)load("glMultiTexCoord2iv"); glad_glMultiTexCoord2s = (PFNGLMULTITEXCOORD2SPROC)load("glMultiTexCoord2s"); glad_glMultiTexCoord2sv = (PFNGLMULTITEXCOORD2SVPROC)load("glMultiTexCoord2sv"); glad_glMultiTexCoord3d = (PFNGLMULTITEXCOORD3DPROC)load("glMultiTexCoord3d"); glad_glMultiTexCoord3dv = (PFNGLMULTITEXCOORD3DVPROC)load("glMultiTexCoord3dv"); glad_glMultiTexCoord3f = (PFNGLMULTITEXCOORD3FPROC)load("glMultiTexCoord3f"); glad_glMultiTexCoord3fv = (PFNGLMULTITEXCOORD3FVPROC)load("glMultiTexCoord3fv"); glad_glMultiTexCoord3i = (PFNGLMULTITEXCOORD3IPROC)load("glMultiTexCoord3i"); glad_glMultiTexCoord3iv = (PFNGLMULTITEXCOORD3IVPROC)load("glMultiTexCoord3iv"); glad_glMultiTexCoord3s = (PFNGLMULTITEXCOORD3SPROC)load("glMultiTexCoord3s"); glad_glMultiTexCoord3sv = (PFNGLMULTITEXCOORD3SVPROC)load("glMultiTexCoord3sv"); glad_glMultiTexCoord4d = (PFNGLMULTITEXCOORD4DPROC)load("glMultiTexCoord4d"); glad_glMultiTexCoord4dv = (PFNGLMULTITEXCOORD4DVPROC)load("glMultiTexCoord4dv"); glad_glMultiTexCoord4f = (PFNGLMULTITEXCOORD4FPROC)load("glMultiTexCoord4f"); glad_glMultiTexCoord4fv = (PFNGLMULTITEXCOORD4FVPROC)load("glMultiTexCoord4fv"); glad_glMultiTexCoord4i = (PFNGLMULTITEXCOORD4IPROC)load("glMultiTexCoord4i"); glad_glMultiTexCoord4iv = (PFNGLMULTITEXCOORD4IVPROC)load("glMultiTexCoord4iv"); glad_glMultiTexCoord4s = (PFNGLMULTITEXCOORD4SPROC)load("glMultiTexCoord4s"); glad_glMultiTexCoord4sv = (PFNGLMULTITEXCOORD4SVPROC)load("glMultiTexCoord4sv"); glad_glLoadTransposeMatrixf = (PFNGLLOADTRANSPOSEMATRIXFPROC)load("glLoadTransposeMatrixf"); glad_glLoadTransposeMatrixd = (PFNGLLOADTRANSPOSEMATRIXDPROC)load("glLoadTransposeMatrixd"); glad_glMultTransposeMatrixf = (PFNGLMULTTRANSPOSEMATRIXFPROC)load("glMultTransposeMatrixf"); glad_glMultTransposeMatrixd = (PFNGLMULTTRANSPOSEMATRIXDPROC)load("glMultTransposeMatrixd"); } static void load_GL_VERSION_1_4(GLADloadproc load) { if(!GLAD_GL_VERSION_1_4) return; glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate"); glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays"); glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements"); glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf"); glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv"); glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri"); glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv"); glad_glFogCoordf = (PFNGLFOGCOORDFPROC)load("glFogCoordf"); glad_glFogCoordfv = (PFNGLFOGCOORDFVPROC)load("glFogCoordfv"); glad_glFogCoordd = (PFNGLFOGCOORDDPROC)load("glFogCoordd"); glad_glFogCoorddv = (PFNGLFOGCOORDDVPROC)load("glFogCoorddv"); glad_glFogCoordPointer = (PFNGLFOGCOORDPOINTERPROC)load("glFogCoordPointer"); glad_glSecondaryColor3b = (PFNGLSECONDARYCOLOR3BPROC)load("glSecondaryColor3b"); glad_glSecondaryColor3bv = (PFNGLSECONDARYCOLOR3BVPROC)load("glSecondaryColor3bv"); glad_glSecondaryColor3d = (PFNGLSECONDARYCOLOR3DPROC)load("glSecondaryColor3d"); glad_glSecondaryColor3dv = (PFNGLSECONDARYCOLOR3DVPROC)load("glSecondaryColor3dv"); glad_glSecondaryColor3f = (PFNGLSECONDARYCOLOR3FPROC)load("glSecondaryColor3f"); glad_glSecondaryColor3fv = (PFNGLSECONDARYCOLOR3FVPROC)load("glSecondaryColor3fv"); glad_glSecondaryColor3i = (PFNGLSECONDARYCOLOR3IPROC)load("glSecondaryColor3i"); glad_glSecondaryColor3iv = (PFNGLSECONDARYCOLOR3IVPROC)load("glSecondaryColor3iv"); glad_glSecondaryColor3s = (PFNGLSECONDARYCOLOR3SPROC)load("glSecondaryColor3s"); glad_glSecondaryColor3sv = (PFNGLSECONDARYCOLOR3SVPROC)load("glSecondaryColor3sv"); glad_glSecondaryColor3ub = (PFNGLSECONDARYCOLOR3UBPROC)load("glSecondaryColor3ub"); glad_glSecondaryColor3ubv = (PFNGLSECONDARYCOLOR3UBVPROC)load("glSecondaryColor3ubv"); glad_glSecondaryColor3ui = (PFNGLSECONDARYCOLOR3UIPROC)load("glSecondaryColor3ui"); glad_glSecondaryColor3uiv = (PFNGLSECONDARYCOLOR3UIVPROC)load("glSecondaryColor3uiv"); glad_glSecondaryColor3us = (PFNGLSECONDARYCOLOR3USPROC)load("glSecondaryColor3us"); glad_glSecondaryColor3usv = (PFNGLSECONDARYCOLOR3USVPROC)load("glSecondaryColor3usv"); glad_glSecondaryColorPointer = (PFNGLSECONDARYCOLORPOINTERPROC)load("glSecondaryColorPointer"); glad_glWindowPos2d = (PFNGLWINDOWPOS2DPROC)load("glWindowPos2d"); glad_glWindowPos2dv = (PFNGLWINDOWPOS2DVPROC)load("glWindowPos2dv"); glad_glWindowPos2f = (PFNGLWINDOWPOS2FPROC)load("glWindowPos2f"); glad_glWindowPos2fv = (PFNGLWINDOWPOS2FVPROC)load("glWindowPos2fv"); glad_glWindowPos2i = (PFNGLWINDOWPOS2IPROC)load("glWindowPos2i"); glad_glWindowPos2iv = (PFNGLWINDOWPOS2IVPROC)load("glWindowPos2iv"); glad_glWindowPos2s = (PFNGLWINDOWPOS2SPROC)load("glWindowPos2s"); glad_glWindowPos2sv = (PFNGLWINDOWPOS2SVPROC)load("glWindowPos2sv"); glad_glWindowPos3d = (PFNGLWINDOWPOS3DPROC)load("glWindowPos3d"); glad_glWindowPos3dv = (PFNGLWINDOWPOS3DVPROC)load("glWindowPos3dv"); glad_glWindowPos3f = (PFNGLWINDOWPOS3FPROC)load("glWindowPos3f"); glad_glWindowPos3fv = (PFNGLWINDOWPOS3FVPROC)load("glWindowPos3fv"); glad_glWindowPos3i = (PFNGLWINDOWPOS3IPROC)load("glWindowPos3i"); glad_glWindowPos3iv = (PFNGLWINDOWPOS3IVPROC)load("glWindowPos3iv"); glad_glWindowPos3s = (PFNGLWINDOWPOS3SPROC)load("glWindowPos3s"); glad_glWindowPos3sv = (PFNGLWINDOWPOS3SVPROC)load("glWindowPos3sv"); glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor"); glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation"); } static void load_GL_VERSION_1_5(GLADloadproc load) { if(!GLAD_GL_VERSION_1_5) return; glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries"); glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries"); glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery"); glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery"); glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery"); glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv"); glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv"); glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv"); glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer"); glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers"); glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers"); glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer"); glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData"); glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData"); glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData"); glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer"); glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer"); glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv"); glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv"); } static void load_GL_VERSION_2_0(GLADloadproc load) { if(!GLAD_GL_VERSION_2_0) return; glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate"); glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers"); glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate"); glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate"); glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate"); glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader"); glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation"); glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader"); glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram"); glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader"); glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram"); glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader"); glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader"); glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray"); glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray"); glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib"); glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform"); glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders"); glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation"); glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv"); glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog"); glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv"); glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog"); glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource"); glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation"); glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv"); glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv"); glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv"); glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv"); glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv"); glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv"); glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram"); glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader"); glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram"); glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource"); glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram"); glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f"); glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f"); glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f"); glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f"); glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i"); glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i"); glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i"); glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i"); glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv"); glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv"); glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv"); glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv"); glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv"); glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv"); glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv"); glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv"); glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv"); glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv"); glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv"); glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram"); glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d"); glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv"); glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f"); glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv"); glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s"); glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv"); glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d"); glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv"); glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f"); glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv"); glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s"); glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv"); glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d"); glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv"); glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f"); glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv"); glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s"); glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv"); glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv"); glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv"); glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv"); glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub"); glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv"); glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv"); glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv"); glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv"); glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d"); glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv"); glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f"); glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv"); glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv"); glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s"); glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv"); glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv"); glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv"); glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv"); glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer"); } static void load_GL_VERSION_2_1(GLADloadproc load) { if(!GLAD_GL_VERSION_2_1) return; glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv"); glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv"); glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv"); glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv"); glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv"); glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv"); } static void load_GL_VERSION_3_0(GLADloadproc load) { if(!GLAD_GL_VERSION_3_0) return; glad_glColorMaski = (PFNGLCOLORMASKIPROC)load("glColorMaski"); glad_glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)load("glGetBooleani_v"); glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); glad_glEnablei = (PFNGLENABLEIPROC)load("glEnablei"); glad_glDisablei = (PFNGLDISABLEIPROC)load("glDisablei"); glad_glIsEnabledi = (PFNGLISENABLEDIPROC)load("glIsEnabledi"); glad_glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)load("glBeginTransformFeedback"); glad_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)load("glEndTransformFeedback"); glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); glad_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)load("glTransformFeedbackVaryings"); glad_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)load("glGetTransformFeedbackVarying"); glad_glClampColor = (PFNGLCLAMPCOLORPROC)load("glClampColor"); glad_glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)load("glBeginConditionalRender"); glad_glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)load("glEndConditionalRender"); glad_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)load("glVertexAttribIPointer"); glad_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)load("glGetVertexAttribIiv"); glad_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)load("glGetVertexAttribIuiv"); glad_glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)load("glVertexAttribI1i"); glad_glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)load("glVertexAttribI2i"); glad_glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)load("glVertexAttribI3i"); glad_glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)load("glVertexAttribI4i"); glad_glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)load("glVertexAttribI1ui"); glad_glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)load("glVertexAttribI2ui"); glad_glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)load("glVertexAttribI3ui"); glad_glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)load("glVertexAttribI4ui"); glad_glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)load("glVertexAttribI1iv"); glad_glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)load("glVertexAttribI2iv"); glad_glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)load("glVertexAttribI3iv"); glad_glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)load("glVertexAttribI4iv"); glad_glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)load("glVertexAttribI1uiv"); glad_glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)load("glVertexAttribI2uiv"); glad_glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)load("glVertexAttribI3uiv"); glad_glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)load("glVertexAttribI4uiv"); glad_glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)load("glVertexAttribI4bv"); glad_glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)load("glVertexAttribI4sv"); glad_glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)load("glVertexAttribI4ubv"); glad_glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)load("glVertexAttribI4usv"); glad_glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)load("glGetUniformuiv"); glad_glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)load("glBindFragDataLocation"); glad_glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)load("glGetFragDataLocation"); glad_glUniform1ui = (PFNGLUNIFORM1UIPROC)load("glUniform1ui"); glad_glUniform2ui = (PFNGLUNIFORM2UIPROC)load("glUniform2ui"); glad_glUniform3ui = (PFNGLUNIFORM3UIPROC)load("glUniform3ui"); glad_glUniform4ui = (PFNGLUNIFORM4UIPROC)load("glUniform4ui"); glad_glUniform1uiv = (PFNGLUNIFORM1UIVPROC)load("glUniform1uiv"); glad_glUniform2uiv = (PFNGLUNIFORM2UIVPROC)load("glUniform2uiv"); glad_glUniform3uiv = (PFNGLUNIFORM3UIVPROC)load("glUniform3uiv"); glad_glUniform4uiv = (PFNGLUNIFORM4UIVPROC)load("glUniform4uiv"); glad_glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)load("glTexParameterIiv"); glad_glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)load("glTexParameterIuiv"); glad_glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)load("glGetTexParameterIiv"); glad_glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)load("glGetTexParameterIuiv"); glad_glClearBufferiv = (PFNGLCLEARBUFFERIVPROC)load("glClearBufferiv"); glad_glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)load("glClearBufferuiv"); glad_glClearBufferfv = (PFNGLCLEARBUFFERFVPROC)load("glClearBufferfv"); glad_glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)load("glClearBufferfi"); glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi"); glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer"); glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer"); glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers"); glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers"); glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage"); glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv"); glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer"); glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer"); glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers"); glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers"); glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus"); glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D"); glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D"); glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D"); glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer"); glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv"); glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap"); glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer"); glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample"); glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer"); glad_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)load("glMapBufferRange"); glad_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)load("glFlushMappedBufferRange"); glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray"); glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays"); glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays"); glad_glIsVertexArray = (PFNGLISVERTEXARRAYPROC)load("glIsVertexArray"); } static void load_GL_VERSION_3_1(GLADloadproc load) { if(!GLAD_GL_VERSION_3_1) return; glad_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)load("glDrawArraysInstanced"); glad_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)load("glDrawElementsInstanced"); glad_glTexBuffer = (PFNGLTEXBUFFERPROC)load("glTexBuffer"); glad_glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)load("glPrimitiveRestartIndex"); glad_glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)load("glCopyBufferSubData"); glad_glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)load("glGetUniformIndices"); glad_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)load("glGetActiveUniformsiv"); glad_glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)load("glGetActiveUniformName"); glad_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)load("glGetUniformBlockIndex"); glad_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)load("glGetActiveUniformBlockiv"); glad_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)load("glGetActiveUniformBlockName"); glad_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)load("glUniformBlockBinding"); glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange"); glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase"); glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v"); } static void load_GL_VERSION_3_2(GLADloadproc load) { if(!GLAD_GL_VERSION_3_2) return; glad_glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)load("glDrawElementsBaseVertex"); glad_glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)load("glDrawRangeElementsBaseVertex"); glad_glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)load("glDrawElementsInstancedBaseVertex"); glad_glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)load("glMultiDrawElementsBaseVertex"); glad_glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)load("glProvokingVertex"); glad_glFenceSync = (PFNGLFENCESYNCPROC)load("glFenceSync"); glad_glIsSync = (PFNGLISSYNCPROC)load("glIsSync"); glad_glDeleteSync = (PFNGLDELETESYNCPROC)load("glDeleteSync"); glad_glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)load("glClientWaitSync"); glad_glWaitSync = (PFNGLWAITSYNCPROC)load("glWaitSync"); glad_glGetInteger64v = (PFNGLGETINTEGER64VPROC)load("glGetInteger64v"); glad_glGetSynciv = (PFNGLGETSYNCIVPROC)load("glGetSynciv"); glad_glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)load("glGetInteger64i_v"); glad_glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)load("glGetBufferParameteri64v"); glad_glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)load("glFramebufferTexture"); glad_glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)load("glTexImage2DMultisample"); glad_glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)load("glTexImage3DMultisample"); glad_glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)load("glGetMultisamplefv"); glad_glSampleMaski = (PFNGLSAMPLEMASKIPROC)load("glSampleMaski"); } static void load_GL_VERSION_3_3(GLADloadproc load) { if(!GLAD_GL_VERSION_3_3) return; glad_glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)load("glBindFragDataLocationIndexed"); glad_glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)load("glGetFragDataIndex"); glad_glGenSamplers = (PFNGLGENSAMPLERSPROC)load("glGenSamplers"); glad_glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)load("glDeleteSamplers"); glad_glIsSampler = (PFNGLISSAMPLERPROC)load("glIsSampler"); glad_glBindSampler = (PFNGLBINDSAMPLERPROC)load("glBindSampler"); glad_glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)load("glSamplerParameteri"); glad_glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)load("glSamplerParameteriv"); glad_glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)load("glSamplerParameterf"); glad_glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)load("glSamplerParameterfv"); glad_glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)load("glSamplerParameterIiv"); glad_glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)load("glSamplerParameterIuiv"); glad_glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)load("glGetSamplerParameteriv"); glad_glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)load("glGetSamplerParameterIiv"); glad_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)load("glGetSamplerParameterfv"); glad_glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)load("glGetSamplerParameterIuiv"); glad_glQueryCounter = (PFNGLQUERYCOUNTERPROC)load("glQueryCounter"); glad_glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)load("glGetQueryObjecti64v"); glad_glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)load("glGetQueryObjectui64v"); glad_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)load("glVertexAttribDivisor"); glad_glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)load("glVertexAttribP1ui"); glad_glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)load("glVertexAttribP1uiv"); glad_glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)load("glVertexAttribP2ui"); glad_glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)load("glVertexAttribP2uiv"); glad_glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)load("glVertexAttribP3ui"); glad_glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)load("glVertexAttribP3uiv"); glad_glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)load("glVertexAttribP4ui"); glad_glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)load("glVertexAttribP4uiv"); glad_glVertexP2ui = (PFNGLVERTEXP2UIPROC)load("glVertexP2ui"); glad_glVertexP2uiv = (PFNGLVERTEXP2UIVPROC)load("glVertexP2uiv"); glad_glVertexP3ui = (PFNGLVERTEXP3UIPROC)load("glVertexP3ui"); glad_glVertexP3uiv = (PFNGLVERTEXP3UIVPROC)load("glVertexP3uiv"); glad_glVertexP4ui = (PFNGLVERTEXP4UIPROC)load("glVertexP4ui"); glad_glVertexP4uiv = (PFNGLVERTEXP4UIVPROC)load("glVertexP4uiv"); glad_glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)load("glTexCoordP1ui"); glad_glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)load("glTexCoordP1uiv"); glad_glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)load("glTexCoordP2ui"); glad_glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)load("glTexCoordP2uiv"); glad_glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)load("glTexCoordP3ui"); glad_glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)load("glTexCoordP3uiv"); glad_glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)load("glTexCoordP4ui"); glad_glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)load("glTexCoordP4uiv"); glad_glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)load("glMultiTexCoordP1ui"); glad_glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)load("glMultiTexCoordP1uiv"); glad_glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)load("glMultiTexCoordP2ui"); glad_glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)load("glMultiTexCoordP2uiv"); glad_glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)load("glMultiTexCoordP3ui"); glad_glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)load("glMultiTexCoordP3uiv"); glad_glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)load("glMultiTexCoordP4ui"); glad_glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)load("glMultiTexCoordP4uiv"); glad_glNormalP3ui = (PFNGLNORMALP3UIPROC)load("glNormalP3ui"); glad_glNormalP3uiv = (PFNGLNORMALP3UIVPROC)load("glNormalP3uiv"); glad_glColorP3ui = (PFNGLCOLORP3UIPROC)load("glColorP3ui"); glad_glColorP3uiv = (PFNGLCOLORP3UIVPROC)load("glColorP3uiv"); glad_glColorP4ui = (PFNGLCOLORP4UIPROC)load("glColorP4ui"); glad_glColorP4uiv = (PFNGLCOLORP4UIVPROC)load("glColorP4uiv"); glad_glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)load("glSecondaryColorP3ui"); glad_glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)load("glSecondaryColorP3uiv"); } static void load_GL_ARB_debug_output(GLADloadproc load) { if(!GLAD_GL_ARB_debug_output) return; glad_glDebugMessageControlARB = (PFNGLDEBUGMESSAGECONTROLARBPROC)load("glDebugMessageControlARB"); glad_glDebugMessageInsertARB = (PFNGLDEBUGMESSAGEINSERTARBPROC)load("glDebugMessageInsertARB"); glad_glDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKARBPROC)load("glDebugMessageCallbackARB"); glad_glGetDebugMessageLogARB = (PFNGLGETDEBUGMESSAGELOGARBPROC)load("glGetDebugMessageLogARB"); } static int find_extensionsGL(void) { if (!get_exts()) return 0; GLAD_GL_ARB_debug_output = has_ext("GL_ARB_debug_output"); free_exts(); return 1; } static void find_coreGL(void) { /* Thank you @elmindreda * https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176 * https://github.com/glfw/glfw/blob/master/src/context.c#L36 */ int i, major, minor; const char* version; const char* prefixes[] = { "OpenGL ES-CM ", "OpenGL ES-CL ", "OpenGL ES ", NULL }; version = (const char*) glGetString(GL_VERSION); if (!version) return; for (i = 0; prefixes[i]; i++) { const size_t length = strlen(prefixes[i]); if (strncmp(version, prefixes[i], length) == 0) { version += length; break; } } /* PR #18 */ #ifdef _MSC_VER sscanf_s(version, "%d.%d", &major, &minor); #else sscanf(version, "%d.%d", &major, &minor); #endif GLVersion.major = major; GLVersion.minor = minor; max_loaded_major = major; max_loaded_minor = minor; GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1; GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1; GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1; GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1; GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1; GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1; GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2; GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2; GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3; GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3; GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3; GLAD_GL_VERSION_3_3 = (major == 3 && minor >= 3) || major > 3; if (GLVersion.major > 3 || (GLVersion.major >= 3 && GLVersion.minor >= 3)) { max_loaded_major = 3; max_loaded_minor = 3; } } int gladLoadGLLoader(GLADloadproc load) { GLVersion.major = 0; GLVersion.minor = 0; glGetString = (PFNGLGETSTRINGPROC)load("glGetString"); if(glGetString == NULL) return 0; if(glGetString(GL_VERSION) == NULL) return 0; find_coreGL(); load_GL_VERSION_1_0(load); load_GL_VERSION_1_1(load); load_GL_VERSION_1_2(load); load_GL_VERSION_1_3(load); load_GL_VERSION_1_4(load); load_GL_VERSION_1_5(load); load_GL_VERSION_2_0(load); load_GL_VERSION_2_1(load); load_GL_VERSION_3_0(load); load_GL_VERSION_3_1(load); load_GL_VERSION_3_2(load); load_GL_VERSION_3_3(load); if (!find_extensionsGL()) return 0; load_GL_ARB_debug_output(load); return GLVersion.major != 0 || GLVersion.minor != 0; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/visual/visual_server_viewport.cpp
568
#include "visual_server_viewport.h" #include "visual_server_global.h" #include "visual_server_canvas.h" #include "visual_server_scene.h" #include "globals.h" void VisualServerViewport::_draw_viewport(Viewport *p_viewport) { /* Camera should always be BEFORE any other 3D */ #if 0 bool scenario_draw_canvas_bg=false; int scenario_canvas_max_layer=0; if (!p_viewport->hide_canvas && !p_viewport->disable_environment && scenario_owner.owns(p_viewport->scenario)) { Scenario *scenario=scenario_owner.get(p_viewport->scenario); if (scenario->environment.is_valid()) { if (rasterizer->is_environment(scenario->environment)) { scenario_draw_canvas_bg=rasterizer->environment_get_background(scenario->environment)==VS::ENV_BG_CANVAS; scenario_canvas_max_layer=rasterizer->environment_get_background_param(scenario->environment,VS::ENV_BG_PARAM_CANVAS_MAX_LAYER); } } } bool can_draw_3d=!p_viewport->hide_scenario && camera_owner.owns(p_viewport->camera) && scenario_owner.owns(p_viewport->scenario); if (scenario_draw_canvas_bg) { rasterizer->begin_canvas_bg(); } if (!scenario_draw_canvas_bg && can_draw_3d) { _draw_viewport_camera(p_viewport,false); } else if (true /*|| !p_viewport->canvas_list.empty()*/){ //clear the viewport black because of no camera? i seriously should.. if (p_viewport->render_target_clear_on_new_frame || p_viewport->render_target_clear) { if (p_viewport->transparent_bg) { rasterizer->clear_viewport(Color(0,0,0,0)); } else { Color cc=clear_color; if (scenario_draw_canvas_bg) cc.a=0; rasterizer->clear_viewport(cc); } p_viewport->render_target_clear=false; } } #endif if (p_viewport->clear_mode!=VS::VIEWPORT_CLEAR_NEVER) { VSG::rasterizer->clear_render_target(clear_color); if (p_viewport->clear_mode==VS::VIEWPORT_CLEAR_ONLY_NEXT_FRAME) { p_viewport->clear_mode=VS::VIEWPORT_CLEAR_NEVER; } } if (!p_viewport->disable_3d && p_viewport->camera.is_valid()) { VSG::scene->render_camera(p_viewport->camera,p_viewport->scenario,p_viewport->size,p_viewport->shadow_atlas); } if (!p_viewport->hide_canvas) { int i=0; Map<Viewport::CanvasKey,Viewport::CanvasData*> canvas_map; Rect2 clip_rect(0,0,p_viewport->size.x,p_viewport->size.y); RasterizerCanvas::Light *lights=NULL; RasterizerCanvas::Light *lights_with_shadow=NULL; RasterizerCanvas::Light *lights_with_mask=NULL; Rect2 shadow_rect; int light_count=0; for (Map<RID,Viewport::CanvasData>::Element *E=p_viewport->canvas_map.front();E;E=E->next()) { Transform2D xf = p_viewport->global_transform * E->get().transform; VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get().canvas); //find lights in canvas for(Set<RasterizerCanvas::Light*>::Element *F=canvas->lights.front();F;F=F->next()) { RasterizerCanvas::Light* cl=F->get(); if (cl->enabled && cl->texture.is_valid()) { //not super efficient.. Size2 tsize(VSG::storage->texture_get_width(cl->texture),VSG::storage->texture_get_height(cl->texture)); tsize*=cl->scale; Vector2 offset=tsize/2.0; cl->rect_cache=Rect2(-offset+cl->texture_offset,tsize); cl->xform_cache=xf * cl->xform; if (clip_rect.intersects_transformed(cl->xform_cache,cl->rect_cache)) { cl->filter_next_ptr=lights; lights=cl; cl->texture_cache=NULL; Transform2D scale; scale.scale(cl->rect_cache.size); scale.elements[2]=cl->rect_cache.pos; cl->light_shader_xform = (cl->xform_cache * scale).affine_inverse(); cl->light_shader_pos=cl->xform_cache[2]; if (cl->shadow_buffer.is_valid()) { cl->shadows_next_ptr=lights_with_shadow; if (lights_with_shadow==NULL) { shadow_rect = cl->xform_cache.xform(cl->rect_cache); } else { shadow_rect=shadow_rect.merge( cl->xform_cache.xform(cl->rect_cache) ); } lights_with_shadow=cl; cl->radius_cache=cl->rect_cache.size.length(); } if (cl->mode==VS::CANVAS_LIGHT_MODE_MASK) { cl->mask_next_ptr=lights_with_mask; lights_with_mask=cl; } light_count++; } VSG::canvas_render->light_internal_update(cl->light_internal,cl); } } //print_line("lights: "+itos(light_count)); canvas_map[ Viewport::CanvasKey( E->key(), E->get().layer) ]=&E->get(); } if (lights_with_shadow) { //update shadows if any RasterizerCanvas::LightOccluderInstance * occluders=NULL; //make list of occluders for (Map<RID,Viewport::CanvasData>::Element *E=p_viewport->canvas_map.front();E;E=E->next()) { VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get().canvas); Transform2D xf = p_viewport->global_transform * E->get().transform; for(Set<RasterizerCanvas::LightOccluderInstance*>::Element *F=canvas->occluders.front();F;F=F->next()) { if (!F->get()->enabled) continue; F->get()->xform_cache = xf * F->get()->xform; if (shadow_rect.intersects_transformed(F->get()->xform_cache,F->get()->aabb_cache)) { F->get()->next=occluders; occluders=F->get(); } } } //update the light shadowmaps with them RasterizerCanvas::Light *light=lights_with_shadow; while(light) { VSG::canvas_render->canvas_light_shadow_buffer_update(light->shadow_buffer,light->xform_cache.affine_inverse(),light->item_mask,light->radius_cache/1000.0,light->radius_cache*1.1,occluders,&light->shadow_matrix_cache); light=light->shadows_next_ptr; } //VSG::canvas_render->reset_canvas(); } VSG::rasterizer->restore_render_target(); #if 0 if (scenario_draw_canvas_bg && canvas_map.front() && canvas_map.front()->key().layer>scenario_canvas_max_layer) { _draw_viewport_camera(p_viewport,!can_draw_3d); scenario_draw_canvas_bg=false; } #endif for (Map<Viewport::CanvasKey,Viewport::CanvasData*>::Element *E=canvas_map.front();E;E=E->next()) { VisualServerCanvas::Canvas *canvas = static_cast<VisualServerCanvas::Canvas*>(E->get()->canvas); //print_line("canvas "+itos(i)+" size: "+itos(I->get()->canvas->child_items.size())); //print_line("GT "+p_viewport->global_transform+". CT: "+E->get()->transform); Transform2D xform = p_viewport->global_transform * E->get()->transform; RasterizerCanvas::Light *canvas_lights=NULL; RasterizerCanvas::Light *ptr=lights; while(ptr) { if (E->get()->layer>=ptr->layer_min && E->get()->layer<=ptr->layer_max) { ptr->next_ptr=canvas_lights; canvas_lights=ptr; } ptr=ptr->filter_next_ptr; } VSG::canvas->render_canvas( canvas,xform,canvas_lights,lights_with_mask,clip_rect ); i++; #if 0 if (scenario_draw_canvas_bg && E->key().layer>=scenario_canvas_max_layer) { _draw_viewport_camera(p_viewport,!can_draw_3d); scenario_draw_canvas_bg=false; } #endif } #if 0 if (scenario_draw_canvas_bg) { _draw_viewport_camera(p_viewport,!can_draw_3d); scenario_draw_canvas_bg=false; } #endif //VSG::canvas_render->canvas_debug_viewport_shadows(lights_with_shadow); } } void VisualServerViewport::draw_viewports() { //sort viewports //draw viewports clear_color=GLOBAL_GET("rendering/viewport/default_clear_color"); active_viewports.sort_custom<ViewportSort>(); for(int i=0;i<active_viewports.size();i++) { Viewport *vp = active_viewports[i]; if (vp->update_mode==VS::VIEWPORT_UPDATE_DISABLED) continue; ERR_CONTINUE( !vp->render_target.is_valid() ); bool visible = vp->viewport_to_screen_rect!=Rect2() || vp->update_mode==VS::VIEWPORT_UPDATE_ALWAYS || vp->update_mode==VS::VIEWPORT_UPDATE_ONCE; if (!visible) continue; VSG::rasterizer->set_current_render_target(vp->render_target); _draw_viewport(vp); if (vp->viewport_to_screen_rect!=Rect2()) { //copy to screen if set as such VSG::rasterizer->set_current_render_target(RID()); VSG::rasterizer->blit_render_target_to_screen(vp->render_target,vp->viewport_to_screen_rect,vp->viewport_to_screen); } if (vp->update_mode==VS::VIEWPORT_UPDATE_ONCE) { vp->update_mode=VS::VIEWPORT_UPDATE_DISABLED; } } } RID VisualServerViewport::viewport_create() { Viewport * viewport = memnew( Viewport ); RID rid = viewport_owner.make_rid(viewport); viewport->self=rid; viewport->hide_scenario=false; viewport->hide_canvas=false; viewport->render_target=VSG::storage->render_target_create(); viewport->shadow_atlas=VSG::scene_render->shadow_atlas_create(); return rid; } void VisualServerViewport::viewport_set_size(RID p_viewport,int p_width,int p_height){ ERR_FAIL_COND(p_width<0 && p_height<0); Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->size=Size2(p_width,p_height); VSG::storage->render_target_set_size(viewport->render_target,p_width,p_height); } void VisualServerViewport::viewport_set_active(RID p_viewport,bool p_active) { Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); if (p_active) { ERR_FAIL_COND(active_viewports.find(viewport)!=-1);//already active active_viewports.push_back(viewport); } else { active_viewports.erase(viewport); } } void VisualServerViewport::viewport_set_parent_viewport(RID p_viewport,RID p_parent_viewport) { Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->parent=p_parent_viewport; } void VisualServerViewport::viewport_set_clear_mode(RID p_viewport,VS::ViewportClearMode p_clear_mode) { Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->clear_mode=p_clear_mode; } void VisualServerViewport::viewport_attach_to_screen(RID p_viewport,const Rect2& p_rect,int p_screen){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->viewport_to_screen_rect=p_rect; viewport->viewport_to_screen=p_screen; } void VisualServerViewport::viewport_detach(RID p_viewport){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->viewport_to_screen_rect=Rect2(); viewport->viewport_to_screen=0; } void VisualServerViewport::viewport_set_update_mode(RID p_viewport,VS::ViewportUpdateMode p_mode){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->update_mode=p_mode; } void VisualServerViewport::viewport_set_vflip(RID p_viewport,bool p_enable){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_VFLIP,p_enable); } RID VisualServerViewport::viewport_get_texture(RID p_viewport) const{ const Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND_V(!viewport,RID()); return VSG::storage->render_target_get_texture(viewport->render_target); } void VisualServerViewport::viewport_set_hide_scenario(RID p_viewport,bool p_hide){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->hide_scenario=p_hide; } void VisualServerViewport::viewport_set_hide_canvas(RID p_viewport,bool p_hide){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->hide_canvas=p_hide; } void VisualServerViewport::viewport_set_disable_environment(RID p_viewport,bool p_disable){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->disable_environment=p_disable; } void VisualServerViewport::viewport_set_disable_3d(RID p_viewport,bool p_disable){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->disable_3d=p_disable; VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_NO_3D,p_disable); } void VisualServerViewport::viewport_attach_camera(RID p_viewport,RID p_camera){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->camera=p_camera; } void VisualServerViewport::viewport_set_scenario(RID p_viewport,RID p_scenario){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->scenario=p_scenario; } void VisualServerViewport::viewport_attach_canvas(RID p_viewport,RID p_canvas){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); ERR_FAIL_COND(viewport->canvas_map.has(p_canvas)); VisualServerCanvas::Canvas *canvas = VSG::canvas->canvas_owner.getornull(p_canvas); ERR_FAIL_COND(!canvas); canvas->viewports.insert(p_viewport); viewport->canvas_map[p_canvas]=Viewport::CanvasData(); viewport->canvas_map[p_canvas].layer=0; viewport->canvas_map[p_canvas].canvas=canvas; } void VisualServerViewport::viewport_remove_canvas(RID p_viewport,RID p_canvas){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); VisualServerCanvas::Canvas *canvas = VSG::canvas->canvas_owner.getornull(p_canvas); ERR_FAIL_COND(!canvas); viewport->canvas_map.erase(p_canvas); canvas->viewports.erase(p_viewport); } void VisualServerViewport::viewport_set_canvas_transform(RID p_viewport,RID p_canvas,const Transform2D& p_offset){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); ERR_FAIL_COND(!viewport->canvas_map.has(p_canvas)); viewport->canvas_map[p_canvas].transform=p_offset; } void VisualServerViewport::viewport_set_transparent_background(RID p_viewport,bool p_enabled){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_TRANSPARENT,p_enabled); } void VisualServerViewport::viewport_set_global_canvas_transform(RID p_viewport,const Transform2D& p_transform){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->global_transform=p_transform; } void VisualServerViewport::viewport_set_canvas_layer(RID p_viewport,RID p_canvas,int p_layer){ Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); ERR_FAIL_COND(!viewport->canvas_map.has(p_canvas)); viewport->canvas_map[p_canvas].layer=p_layer; } void VisualServerViewport::viewport_set_shadow_atlas_size(RID p_viewport,int p_size) { Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); viewport->shadow_atlas_size=p_size; VSG::scene_render->shadow_atlas_set_size( viewport->shadow_atlas, viewport->shadow_atlas_size); } void VisualServerViewport::viewport_set_shadow_atlas_quadrant_subdivision(RID p_viewport,int p_quadrant,int p_subdiv) { Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); VSG::scene_render->shadow_atlas_set_quadrant_subdivision( viewport->shadow_atlas, p_quadrant, p_subdiv); } void VisualServerViewport::viewport_set_msaa(RID p_viewport,VS::ViewportMSAA p_msaa) { Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); VSG::storage->render_target_set_msaa(viewport->render_target,p_msaa); } void VisualServerViewport::viewport_set_hdr(RID p_viewport,bool p_enabled) { Viewport * viewport = viewport_owner.getornull(p_viewport); ERR_FAIL_COND(!viewport); VSG::storage->render_target_set_flag(viewport->render_target,RasterizerStorage::RENDER_TARGET_HDR,p_enabled); } bool VisualServerViewport::free(RID p_rid) { if (viewport_owner.owns(p_rid)) { Viewport * viewport = viewport_owner.getornull(p_rid); VSG::storage->free( viewport->render_target ); VSG::scene_render->free( viewport->shadow_atlas ); while(viewport->canvas_map.front()) { viewport_remove_canvas(p_rid,viewport->canvas_map.front()->key()); } viewport_set_scenario(p_rid,RID()); active_viewports.erase(viewport); viewport_owner.free(p_rid); memdelete(viewport); return true; } return false; } VisualServerViewport::VisualServerViewport() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
core/os/memory.cpp
144
/*************************************************************************/ /* memory.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "memory.h" #include "error_macros.h" #include "copymem.h" #include <stdio.h> #include <stdlib.h> void * operator new(size_t p_size,const char *p_description) { return Memory::alloc_static( p_size, false ); } void * operator new(size_t p_size,void* (*p_allocfunc)(size_t p_size)) { return p_allocfunc(p_size); } #include <stdio.h> #ifdef DEBUG_ENABLED size_t Memory::mem_usage=0; size_t Memory::max_usage=0; #endif size_t Memory::alloc_count=0; void * Memory::alloc_static(size_t p_bytes,bool p_pad_align) { #ifdef DEBUG_ENABLED bool prepad=true; #else bool prepad=p_pad_align; #endif void * mem = malloc( p_bytes + (prepad?PAD_ALIGN:0)); alloc_count++; ERR_FAIL_COND_V(!mem,NULL); if (prepad) { uint64_t *s = (uint64_t*)mem; *s=p_bytes; uint8_t *s8 = (uint8_t*)mem; #ifdef DEBUG_ENABLED mem_usage+=p_bytes; if (mem_usage>max_usage) { max_usage=mem_usage; } #endif return s8 + PAD_ALIGN; } else { return mem; } } void * Memory::realloc_static(void *p_memory,size_t p_bytes,bool p_pad_align) { if (p_memory==NULL) { return alloc_static(p_bytes,p_pad_align); } uint8_t *mem = (uint8_t*)p_memory; #ifdef DEBUG_ENABLED bool prepad=true; #else bool prepad=p_pad_align; #endif if (prepad) { mem-=PAD_ALIGN; uint64_t *s = (uint64_t*)mem; #ifdef DEBUG_ENABLED mem_usage-=*s; mem_usage+=p_bytes; #endif if (p_bytes==0) { free(mem); return NULL; } else { *s=p_bytes; mem = (uint8_t*)realloc(mem,p_bytes+PAD_ALIGN); ERR_FAIL_COND_V(!mem,NULL); s = (uint64_t*)mem; *s=p_bytes; return mem+PAD_ALIGN; } } else { mem = (uint8_t*)realloc(mem,p_bytes); ERR_FAIL_COND_V(mem==NULL && p_bytes>0,NULL); return mem; } } void Memory::free_static(void *p_ptr,bool p_pad_align) { ERR_FAIL_COND(p_ptr==NULL); uint8_t *mem = (uint8_t*)p_ptr; #ifdef DEBUG_ENABLED bool prepad=true; #else bool prepad=p_pad_align; #endif alloc_count--; if (prepad) { mem-=PAD_ALIGN; uint64_t *s = (uint64_t*)mem; #ifdef DEBUG_ENABLED mem_usage-=*s; #endif free(mem); } else { free(mem); } } size_t Memory::get_mem_available() { return 0xFFFFFFFFFFFFF; } size_t Memory::get_mem_usage(){ #ifdef DEBUG_ENABLED return mem_usage; #else return 0; #endif } size_t Memory::get_mem_max_usage(){ #ifdef DEBUG_ENABLED return max_usage; #else return 0; #endif } _GlobalNil::_GlobalNil() { color=1; left=this; right=this; parent=this; } _GlobalNil _GlobalNilClass::_nil;
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/reverb.cpp
364
// // C++ Interface: reverb // // Description: // // // Author: Juan Linietsky <reduzio@gmail.com>, (C) 2006 // // Copyright: See COPYING file that comes with this distribution // // #include "reverb.h" #include <math.h> #include "math_funcs.h" const float Reverb::comb_tunings[MAX_COMBS]={ //freeverb comb tunings 0.025306122448979593, 0.026938775510204082, 0.028956916099773241, 0.03074829931972789, 0.032244897959183672, 0.03380952380952381, 0.035306122448979592, 0.036666666666666667 }; const float Reverb::allpass_tunings[MAX_ALLPASS]={ //freeverb allpass tunings 0.0051020408163265302, 0.007732426303854875, 0.01, 0.012607709750566893 }; void Reverb::process(float *p_src,float *p_dst,int p_frames) { if (p_frames>INPUT_BUFFER_MAX_SIZE) p_frames=INPUT_BUFFER_MAX_SIZE; int predelay_frames=lrint((params.predelay/1000.0)*params.mix_rate); if (predelay_frames<10) predelay_frames=10; if (predelay_frames>=echo_buffer_size) predelay_frames=echo_buffer_size-1; for (int i=0;i<p_frames;i++) { if (echo_buffer_pos>=echo_buffer_size) echo_buffer_pos=0; int read_pos=echo_buffer_pos-predelay_frames; while (read_pos<0) read_pos+=echo_buffer_size; float in=undenormalise(echo_buffer[read_pos]*params.predelay_fb+p_src[i]); echo_buffer[echo_buffer_pos]=in; input_buffer[i]=in; p_dst[i]=0; //take the chance and clear this echo_buffer_pos++; } if (params.hpf>0) { float hpaux=expf(-2.0*Math_PI*params.hpf*6000/params.mix_rate); float hp_a1=(1.0+hpaux)/2.0; float hp_a2=-(1.0+hpaux)/2.0; float hp_b1=hpaux; for (int i=0;i<p_frames;i++) { float in=input_buffer[i]; input_buffer[i]=in*hp_a1+hpf_h1*hp_a2+hpf_h2*hp_b1; hpf_h2=input_buffer[i]; hpf_h1=in; } } for (int i=0;i<MAX_COMBS;i++) { Comb &c=comb[i]; int size_limit=c.size-lrintf((float)c.extra_spread_frames*(1.0-params.extra_spread)); for (int j=0;j<p_frames;j++) { if (c.pos>=size_limit) //reset this now just in case c.pos=0; float out=undenormalise(c.buffer[c.pos]*c.feedback); out=out*(1.0-c.damp)+c.damp_h*c.damp; //lowpass c.damp_h=out; c.buffer[c.pos]=input_buffer[j]+out; p_dst[j]+=out; c.pos++; } } static const float allpass_feedback=0.7; /* this one works, but the other version is just nicer.... int ap_size_limit[MAX_ALLPASS]; for (int i=0;i<MAX_ALLPASS;i++) { AllPass &a=allpass[i]; ap_size_limit[i]=a.size-lrintf((float)a.extra_spread_frames*(1.0-params.extra_spread)); } for (int i=0;i<p_frames;i++) { float sample=p_dst[i]; float aux,in; float AllPass*ap; #define PROCESS_ALLPASS(m_ap) \ ap=&allpass[m_ap]; \ if (ap->pos>=ap_size_limit[m_ap]) \ ap->pos=0; \ aux=undenormalise(ap->buffer[ap->pos]); \ in=sample; \ sample=-in+aux; \ ap->pos++; PROCESS_ALLPASS(0); PROCESS_ALLPASS(1); PROCESS_ALLPASS(2); PROCESS_ALLPASS(3); p_dst[i]=sample; } */ for (int i=0;i<MAX_ALLPASS;i++) { AllPass &a=allpass[i]; int size_limit=a.size-lrintf((float)a.extra_spread_frames*(1.0-params.extra_spread)); for (int j=0;j<p_frames;j++) { if (a.pos>=size_limit) a.pos=0; float aux=a.buffer[a.pos]; a.buffer[a.pos]=undenormalise(allpass_feedback*aux+p_dst[j]); p_dst[j]=aux-allpass_feedback*a.buffer[a.pos]; a.pos++; } } static const float wet_scale=0.6; for (int i=0;i<p_frames;i++) { p_dst[i]=p_dst[i]*params.wet*wet_scale+p_src[i]*params.dry; } } void Reverb::set_room_size(float p_size) { params.room_size=p_size; update_parameters(); } void Reverb::set_damp(float p_damp) { params.damp=p_damp; update_parameters(); } void Reverb::set_wet(float p_wet) { params.wet=p_wet; } void Reverb::set_dry(float p_dry) { params.dry=p_dry; } void Reverb::set_predelay(float p_predelay) { params.predelay=p_predelay; } void Reverb::set_predelay_feedback(float p_predelay_fb) { params.predelay_fb=p_predelay_fb; } void Reverb::set_highpass(float p_frq) { if (p_frq>1) p_frq=1; if (p_frq<0) p_frq=0; params.hpf=p_frq; } void Reverb::set_extra_spread(float p_spread) { params.extra_spread=p_spread; } void Reverb::set_mix_rate(float p_mix_rate) { params.mix_rate=p_mix_rate; configure_buffers(); } void Reverb::set_extra_spread_base(float p_sec) { params.extra_spread_base=p_sec; configure_buffers(); } void Reverb::configure_buffers() { clear_buffers(); //clear if necesary for (int i=0;i<MAX_COMBS;i++) { Comb &c=comb[i]; c.extra_spread_frames=lrint(params.extra_spread_base*params.mix_rate); int len=lrint(comb_tunings[i]*params.mix_rate)+c.extra_spread_frames; if (len<5) len=5; //may this happen? c.buffer = memnew_arr(float,len); c.pos=0; for (int j=0;j<len;j++) c.buffer[j]=0; c.size=len; } for (int i=0;i<MAX_ALLPASS;i++) { AllPass &a=allpass[i]; a.extra_spread_frames=lrint(params.extra_spread_base*params.mix_rate); int len=lrint(allpass_tunings[i]*params.mix_rate)+a.extra_spread_frames; if (len<5) len=5; //may this happen? a.buffer = memnew_arr(float,len); a.pos=0; for (int j=0;j<len;j++) a.buffer[j]=0; a.size=len; } echo_buffer_size=(int)(((float)MAX_ECHO_MS/1000.0)*params.mix_rate+1.0); echo_buffer = memnew_arr(float,echo_buffer_size); for (int i=0;i<echo_buffer_size;i++) { echo_buffer[i]=0; } echo_buffer_pos=0; } void Reverb::update_parameters() { //more freeverb derived constants static const float room_scale = 0.28f; static const float room_offset = 0.7f; for (int i=0;i<MAX_COMBS;i++) { Comb &c=comb[i]; c.feedback=room_offset+params.room_size*room_scale; if (c.feedback<room_offset) c.feedback=room_offset; else if (c.feedback>(room_offset+room_scale)) c.feedback=(room_offset+room_scale); float auxdmp=params.damp/2.0+0.5; //only half the range (0.5 .. 1.0 is enough) auxdmp*=auxdmp; c.damp=expf(-2.0*Math_PI*auxdmp*10000/params.mix_rate); // 0 .. 10khz } } void Reverb::clear_buffers() { if (echo_buffer) memdelete_arr(echo_buffer); for (int i=0;i<MAX_COMBS;i++) { if (comb[i].buffer) memdelete_arr(comb[i].buffer); comb[i].buffer=0; } for (int i=0;i<MAX_ALLPASS;i++) { if (allpass[i].buffer) memdelete_arr(allpass[i].buffer); allpass[i].buffer=0; } } Reverb::Reverb() { params.room_size=0.8; params.damp=0.5; params.dry=1.0; params.wet=0.0; params.mix_rate=44100; params.extra_spread_base=0; params.extra_spread=1.0; params.predelay=150; params.predelay_fb=0.4; params.hpf=0; hpf_h1=0; hpf_h2=0; input_buffer=memnew_arr(float,INPUT_BUFFER_MAX_SIZE); echo_buffer=0; configure_buffers(); update_parameters(); } Reverb::~Reverb() { memdelete_arr(input_buffer); clear_buffers(); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
core/safe_refcount.cpp
65
/*************************************************************************/ /* safe_refcount.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "safe_refcount.h" // Atomic functions, these are used for multithread safe reference counters! #ifdef NO_THREADS uint32_t atomic_conditional_increment( register uint32_t * pw ) { if (*pw==0) return 0; (*pw)++; return *pw; } uint32_t atomic_decrement( register uint32_t * pw ) { (*pw)--; return *pw; } #else #ifdef _MSC_VER // don't pollute my namespace! #include <windows.h> uint32_t atomic_conditional_increment( register uint32_t * pw ) { /* try to increment until it actually works */ // taken from boost while (true) { uint32_t tmp = static_cast< uint32_t const volatile& >( *pw ); if( tmp == 0 ) return 0; // if zero, can't add to it anymore if( InterlockedCompareExchange( (LONG volatile*)pw, tmp + 1, tmp ) == tmp ) return tmp+1; } } uint32_t atomic_decrement( register uint32_t * pw ) { return InterlockedDecrement( (LONG volatile*)pw ); } uint32_t atomic_increment( register uint32_t * pw ) { return InterlockedIncrement( (LONG volatile*)pw ); } #elif defined(__GNUC__) uint32_t atomic_conditional_increment( register uint32_t * pw ) { while (true) { uint32_t tmp = static_cast< uint32_t const volatile& >( *pw ); if( tmp == 0 ) return 0; // if zero, can't add to it anymore if( __sync_val_compare_and_swap( pw, tmp, tmp + 1 ) == tmp ) return tmp+1; } } uint32_t atomic_decrement( register uint32_t * pw ) { return __sync_sub_and_fetch(pw,1); } uint32_t atomic_increment( register uint32_t * pw ) { return __sync_add_and_fetch(pw,1); } #else //no threads supported? #error Must provide atomic functions for this platform or compiler! #endif #endif
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
scene/3d/baked_light_instance.cpp
1,735
/*************************************************************************/ /* baked_light_instance.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "baked_light_instance.h" #include "scene/scene_string_names.h" #include "mesh_instance.h" #include "light.h" #include "math.h" #define FINDMINMAX(x0,x1,x2,min,max) \ min = max = x0; \ if(x1<min) min=x1;\ if(x1>max) max=x1;\ if(x2<min) min=x2;\ if(x2>max) max=x2; static bool planeBoxOverlap(Vector3 normal,float d, Vector3 maxbox) { int q; Vector3 vmin,vmax; for(q=0;q<=2;q++) { if(normal[q]>0.0f) { vmin[q]=-maxbox[q]; vmax[q]=maxbox[q]; } else { vmin[q]=maxbox[q]; vmax[q]=-maxbox[q]; } } if(normal.dot(vmin)+d>0.0f) return false; if(normal.dot(vmax)+d>=0.0f) return true; return false; } /*======================== X-tests ========================*/ #define AXISTEST_X01(a, b, fa, fb) \ p0 = a*v0.y - b*v0.z; \ p2 = a*v2.y - b*v2.z; \ if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \ rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \ if(min>rad || max<-rad) return false; #define AXISTEST_X2(a, b, fa, fb) \ p0 = a*v0.y - b*v0.z; \ p1 = a*v1.y - b*v1.z; \ if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \ rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \ if(min>rad || max<-rad) return false; /*======================== Y-tests ========================*/ #define AXISTEST_Y02(a, b, fa, fb) \ p0 = -a*v0.x + b*v0.z; \ p2 = -a*v2.x + b*v2.z; \ if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \ rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \ if(min>rad || max<-rad) return false; #define AXISTEST_Y1(a, b, fa, fb) \ p0 = -a*v0.x + b*v0.z; \ p1 = -a*v1.x + b*v1.z; \ if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \ rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \ if(min>rad || max<-rad) return false; /*======================== Z-tests ========================*/ #define AXISTEST_Z12(a, b, fa, fb) \ p1 = a*v1.x - b*v1.y; \ p2 = a*v2.x - b*v2.y; \ if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} \ rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \ if(min>rad || max<-rad) return false; #define AXISTEST_Z0(a, b, fa, fb) \ p0 = a*v0.x - b*v0.y; \ p1 = a*v1.x - b*v1.y; \ if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \ rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \ if(min>rad || max<-rad) return false; static bool fast_tri_box_overlap(const Vector3& boxcenter,const Vector3 boxhalfsize,const Vector3 *triverts) { /* use separating axis theorem to test overlap between triangle and box */ /* need to test for overlap in these directions: */ /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ /* we do not even need to test these) */ /* 2) normal of the triangle */ /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ /* this gives 3x3=9 more tests */ Vector3 v0,v1,v2; float min,max,d,p0,p1,p2,rad,fex,fey,fez; Vector3 normal,e0,e1,e2; /* This is the fastest branch on Sun */ /* move everything so that the boxcenter is in (0,0,0) */ v0=triverts[0]-boxcenter; v1=triverts[1]-boxcenter; v2=triverts[2]-boxcenter; /* compute triangle edges */ e0=v1-v0; /* tri edge 0 */ e1=v2-v1; /* tri edge 1 */ e2=v0-v2; /* tri edge 2 */ /* Bullet 3: */ /* test the 9 tests first (this was faster) */ fex = Math::abs(e0.x); fey = Math::abs(e0.y); fez = Math::abs(e0.z); AXISTEST_X01(e0.z, e0.y, fez, fey); AXISTEST_Y02(e0.z, e0.x, fez, fex); AXISTEST_Z12(e0.y, e0.x, fey, fex); fex = Math::abs(e1.x); fey = Math::abs(e1.y); fez = Math::abs(e1.z); AXISTEST_X01(e1.z, e1.y, fez, fey); AXISTEST_Y02(e1.z, e1.x, fez, fex); AXISTEST_Z0(e1.y, e1.x, fey, fex); fex = Math::abs(e2.x); fey = Math::abs(e2.y); fez = Math::abs(e2.z); AXISTEST_X2(e2.z, e2.y, fez, fey); AXISTEST_Y1(e2.z, e2.x, fez, fex); AXISTEST_Z12(e2.y, e2.x, fey, fex); /* Bullet 1: */ /* first test overlap in the {x,y,z}-directions */ /* find min, max of the triangle each direction, and test for overlap in */ /* that direction -- this is equivalent to testing a minimal AABB around */ /* the triangle against the AABB */ /* test in X-direction */ FINDMINMAX(v0.x,v1.x,v2.x,min,max); if(min>boxhalfsize.x || max<-boxhalfsize.x) return false; /* test in Y-direction */ FINDMINMAX(v0.y,v1.y,v2.y,min,max); if(min>boxhalfsize.y || max<-boxhalfsize.y) return false; /* test in Z-direction */ FINDMINMAX(v0.z,v1.z,v2.z,min,max); if(min>boxhalfsize.z || max<-boxhalfsize.z) return false; /* Bullet 2: */ /* test if the box intersects the plane of the triangle */ /* compute plane equation of triangle: normal*x+d=0 */ normal=e0.cross(e1); d=-normal.dot(v0); /* plane eq: normal.x+d=0 */ if(!planeBoxOverlap(normal,d,boxhalfsize)) return false; return true; /* box and triangle overlaps */ } Vector<Color> BakedLight::_get_bake_texture(Image &p_image,const Color& p_color) { Vector<Color> ret; if (p_image.empty()) { ret.resize(bake_texture_size*bake_texture_size); for(int i=0;i<bake_texture_size*bake_texture_size;i++) { ret[i]=p_color; } return ret; } p_image.convert(Image::FORMAT_RGBA8); p_image.resize(bake_texture_size,bake_texture_size,Image::INTERPOLATE_CUBIC); PoolVector<uint8_t>::Read r = p_image.get_data().read(); ret.resize(bake_texture_size*bake_texture_size); for(int i=0;i<bake_texture_size*bake_texture_size;i++) { Color c; c.r = r[i*4+0]/255.0; c.g = r[i*4+1]/255.0; c.b = r[i*4+2]/255.0; c.a = r[i*4+3]/255.0; ret[i]=c; } return ret; } BakedLight::MaterialCache BakedLight::_get_material_cache(Ref<Material> p_material) { //this way of obtaining materials is inaccurate and also does not support some compressed formats very well Ref<FixedSpatialMaterial> mat = p_material; Ref<Material> material = mat; //hack for now if (material_cache.has(material)) { return material_cache[material]; } MaterialCache mc; if (mat.is_valid()) { Ref<ImageTexture> albedo_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_ALBEDO); Image img_albedo; if (albedo_tex.is_valid()) { img_albedo = albedo_tex->get_data(); } mc.albedo=_get_bake_texture(img_albedo,mat->get_albedo()); Ref<ImageTexture> emission_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_EMISSION); Color emission_col = mat->get_emission(); emission_col.r*=mat->get_emission_energy(); emission_col.g*=mat->get_emission_energy(); emission_col.b*=mat->get_emission_energy(); Image img_emission; if (emission_tex.is_valid()) { img_emission = emission_tex->get_data(); } mc.emission=_get_bake_texture(img_emission,emission_col); } else { Image empty; mc.albedo=_get_bake_texture(empty,Color(0.7,0.7,0.7)); mc.emission=_get_bake_texture(empty,Color(0,0,0)); } material_cache[p_material]=mc; return mc; } static _FORCE_INLINE_ Vector2 get_uv(const Vector3& p_pos, const Vector3 *p_vtx, const Vector2* p_uv) { if (p_pos.distance_squared_to(p_vtx[0])<CMP_EPSILON2) return p_uv[0]; if (p_pos.distance_squared_to(p_vtx[1])<CMP_EPSILON2) return p_uv[1]; if (p_pos.distance_squared_to(p_vtx[2])<CMP_EPSILON2) return p_uv[2]; Vector3 v0 = p_vtx[1] - p_vtx[0]; Vector3 v1 = p_vtx[2] - p_vtx[0]; Vector3 v2 = p_pos - p_vtx[0]; float d00 = v0.dot( v0); float d01 = v0.dot( v1); float d11 = v1.dot( v1); float d20 = v2.dot( v0); float d21 = v2.dot( v1); float denom = (d00 * d11 - d01 * d01); if (denom==0) return p_uv[0]; float v = (d11 * d20 - d01 * d21) / denom; float w = (d00 * d21 - d01 * d20) / denom; float u = 1.0f - v - w; return p_uv[0]*u + p_uv[1]*v + p_uv[2]*w; } void BakedLight::_plot_face(int p_idx, int p_level, const Vector3 *p_vtx, const Vector2* p_uv, const MaterialCache& p_material, const Rect3 &p_aabb) { if (p_level==cell_subdiv-1) { //plot the face by guessing it's albedo and emission value //find best axis to map to, for scanning values int closest_axis; float closest_dot; Vector3 normal = Plane(p_vtx[0],p_vtx[1],p_vtx[2]).normal; for(int i=0;i<3;i++) { Vector3 axis; axis[i]=1.0; float dot=ABS(normal.dot(axis)); if (i==0 || dot>closest_dot) { closest_axis=i; closest_dot=dot; } } Vector3 axis; axis[closest_axis]=1.0; Vector3 t1; t1[(closest_axis+1)%3]=1.0; Vector3 t2; t2[(closest_axis+2)%3]=1.0; t1*=p_aabb.size[(closest_axis+1)%3]/float(color_scan_cell_width); t2*=p_aabb.size[(closest_axis+2)%3]/float(color_scan_cell_width); Color albedo_accum; Color emission_accum; float alpha=0.0; //map to a grid average in the best axis for this face for(int i=0;i<color_scan_cell_width;i++) { Vector3 ofs_i=float(i)*t1; for(int j=0;j<color_scan_cell_width;j++) { Vector3 ofs_j=float(j)*t2; Vector3 from = p_aabb.pos+ofs_i+ofs_j; Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis]; Vector3 half = (to-from)*0.5; //is in this cell? if (!fast_tri_box_overlap(from+half,half,p_vtx)) { continue; //face does not span this cell } //go from -size to +size*2 to avoid skipping collisions Vector3 ray_from = from + (t1+t2)*0.5 - axis * p_aabb.size[closest_axis]; Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis]*2; Vector3 intersection; if (!Geometry::ray_intersects_triangle(ray_from,ray_to,p_vtx[0],p_vtx[1],p_vtx[2],&intersection)) { //no intersect? look in edges float closest_dist=1e20; for(int j=0;j<3;j++) { Vector3 c; Vector3 inters; Geometry::get_closest_points_between_segments(p_vtx[j],p_vtx[(j+1)%3],ray_from,ray_to,inters,c); float d=c.distance_to(intersection); if (j==0 || d<closest_dist) { closest_dist=d; intersection=inters; } } } Vector2 uv = get_uv(intersection,p_vtx,p_uv); int uv_x = CLAMP(Math::fposmod(uv.x,1.0f)*bake_texture_size,0,bake_texture_size-1); int uv_y = CLAMP(Math::fposmod(uv.y,1.0f)*bake_texture_size,0,bake_texture_size-1); int ofs = uv_y*bake_texture_size+uv_x; albedo_accum.r+=p_material.albedo[ofs].r; albedo_accum.g+=p_material.albedo[ofs].g; albedo_accum.b+=p_material.albedo[ofs].b; albedo_accum.a+=p_material.albedo[ofs].a; emission_accum.r+=p_material.emission[ofs].r; emission_accum.g+=p_material.emission[ofs].g; emission_accum.b+=p_material.emission[ofs].b; alpha+=1.0; } } if (alpha==0) { //could not in any way get texture information.. so use closest point to center Face3 f( p_vtx[0],p_vtx[1],p_vtx[2]); Vector3 inters = f.get_closest_point_to(p_aabb.pos+p_aabb.size*0.5); Vector2 uv = get_uv(inters,p_vtx,p_uv); int uv_x = CLAMP(Math::fposmod(uv.x,1.0f)*bake_texture_size,0,bake_texture_size-1); int uv_y = CLAMP(Math::fposmod(uv.y,1.0f)*bake_texture_size,0,bake_texture_size-1); int ofs = uv_y*bake_texture_size+uv_x; alpha = 1.0/(color_scan_cell_width*color_scan_cell_width); albedo_accum.r=p_material.albedo[ofs].r*alpha; albedo_accum.g=p_material.albedo[ofs].g*alpha; albedo_accum.b=p_material.albedo[ofs].b*alpha; albedo_accum.a=p_material.albedo[ofs].a*alpha; emission_accum.r=p_material.emission[ofs].r*alpha; emission_accum.g=p_material.emission[ofs].g*alpha; emission_accum.b=p_material.emission[ofs].b*alpha; zero_alphas++; } else { float accdiv = 1.0/(color_scan_cell_width*color_scan_cell_width); alpha*=accdiv; albedo_accum.r*=accdiv; albedo_accum.g*=accdiv; albedo_accum.b*=accdiv; albedo_accum.a*=accdiv; emission_accum.r*=accdiv; emission_accum.g*=accdiv; emission_accum.b*=accdiv; } //put this temporarily here, corrected in a later step bake_cells_write[p_idx].albedo[0]+=albedo_accum.r; bake_cells_write[p_idx].albedo[1]+=albedo_accum.g; bake_cells_write[p_idx].albedo[2]+=albedo_accum.b; bake_cells_write[p_idx].light[0]+=emission_accum.r; bake_cells_write[p_idx].light[1]+=emission_accum.g; bake_cells_write[p_idx].light[2]+=emission_accum.b; bake_cells_write[p_idx].alpha+=alpha; static const Vector3 side_normals[6]={ Vector3(-1, 0, 0), Vector3( 1, 0, 0), Vector3( 0,-1, 0), Vector3( 0, 1, 0), Vector3( 0, 0,-1), Vector3( 0, 0, 1), }; for(int i=0;i<6;i++) { if (normal.dot(side_normals[i])>CMP_EPSILON) { bake_cells_write[p_idx].used_sides|=(1<<i); } } } else { //go down for(int i=0;i<8;i++) { Rect3 aabb=p_aabb; aabb.size*=0.5; if (i&1) aabb.pos.x+=aabb.size.x; if (i&2) aabb.pos.y+=aabb.size.y; if (i&4) aabb.pos.z+=aabb.size.z; { Rect3 test_aabb=aabb; //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time Vector3 qsize = test_aabb.size*0.5; //quarter size, for fast aabb test if (!fast_tri_box_overlap(test_aabb.pos+qsize,qsize,p_vtx)) { //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) { //does not fit in child, go on continue; } } if (bake_cells_write[p_idx].childs[i]==CHILD_EMPTY) { //sub cell must be created if (bake_cells_used==(1<<bake_cells_alloc)) { //exhausted cells, creating more space bake_cells_alloc++; bake_cells_write=PoolVector<BakeCell>::Write(); bake_cells.resize(1<<bake_cells_alloc); bake_cells_write=bake_cells.write(); } bake_cells_write[p_idx].childs[i]=bake_cells_used; bake_cells_level_used[p_level+1]++; bake_cells_used++; } _plot_face(bake_cells_write[p_idx].childs[i],p_level+1,p_vtx,p_uv,p_material,aabb); } } } void BakedLight::_fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z) { if (p_level==cell_subdiv-1) { float alpha = bake_cells_write[p_idx].alpha; bake_cells_write[p_idx].albedo[0]/=alpha; bake_cells_write[p_idx].albedo[1]/=alpha; bake_cells_write[p_idx].albedo[2]/=alpha; //transfer emission to light bake_cells_write[p_idx].light[0]/=alpha; bake_cells_write[p_idx].light[1]/=alpha; bake_cells_write[p_idx].light[2]/=alpha; bake_cells_write[p_idx].alpha=1.0; //remove neighbours from used sides for(int n=0;n<6;n++) { int ofs[3]={0,0,0}; ofs[n/2]=(n&1)?1:-1; //convert to x,y,z on this level int x=p_x; int y=p_y; int z=p_z; x+=ofs[0]; y+=ofs[1]; z+=ofs[2]; int ofs_x=0; int ofs_y=0; int ofs_z=0; int size = 1<<p_level; int half=size/2; if (x<0 || x>=size || y<0 || y>=size || z<0 || z>=size) { //neighbour is out, can't use it bake_cells_write[p_idx].used_sides&=~(1<<uint32_t(n)); continue; } uint32_t neighbour=0; for(int i=0;i<cell_subdiv-1;i++) { BakeCell *bc = &bake_cells_write[neighbour]; int child = 0; if (x >= ofs_x + half) { child|=1; ofs_x+=half; } if (y >= ofs_y + half) { child|=2; ofs_y+=half; } if (z >= ofs_z + half) { child|=4; ofs_z+=half; } neighbour = bc->childs[child]; if (neighbour==CHILD_EMPTY) { break; } half>>=1; } if (neighbour!=CHILD_EMPTY) { bake_cells_write[p_idx].used_sides&=~(1<<uint32_t(n)); } } } else { //go down float alpha_average=0; int half = cells_per_axis >> (p_level+1); for(int i=0;i<8;i++) { uint32_t child = bake_cells_write[p_idx].childs[i]; if (child==CHILD_EMPTY) continue; int nx=p_x; int ny=p_y; int nz=p_z; if (i&1) nx+=half; if (i&2) ny+=half; if (i&4) nz+=half; _fixup_plot(child,p_level+1,nx,ny,nz); alpha_average+=bake_cells_write[child].alpha; } bake_cells_write[p_idx].alpha=alpha_average/8.0; bake_cells_write[p_idx].light[0]=0; bake_cells_write[p_idx].light[1]=0; bake_cells_write[p_idx].light[2]=0; bake_cells_write[p_idx].albedo[0]=0; bake_cells_write[p_idx].albedo[1]=0; bake_cells_write[p_idx].albedo[2]=0; } //clean up light bake_cells_write[p_idx].light_pass=0; //find neighbours } void BakedLight::_bake_add_mesh(const Transform& p_xform,Ref<Mesh>& p_mesh) { for(int i=0;i<p_mesh->get_surface_count();i++) { if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES) continue; //only triangles MaterialCache material = _get_material_cache(p_mesh->surface_get_material(i)); Array a = p_mesh->surface_get_arrays(i); PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX]; PoolVector<Vector3>::Read vr=vertices.read(); PoolVector<Vector2> uv = a[Mesh::ARRAY_TEX_UV]; PoolVector<Vector2>::Read uvr; PoolVector<int> index = a[Mesh::ARRAY_INDEX]; bool read_uv=false; if (uv.size()) { uvr=uv.read(); read_uv=true; } if (index.size()) { int facecount = index.size()/3; PoolVector<int>::Read ir=index.read(); for(int j=0;j<facecount;j++) { Vector3 vtxs[3]; Vector2 uvs[3]; for(int k=0;k<3;k++) { vtxs[k]=p_xform.xform(vr[ir[j*3+k]]); } if (read_uv) { for(int k=0;k<3;k++) { uvs[k]=uvr[ir[j*3+k]]; } } //plot face _plot_face(0,0,vtxs,uvs,material,bounds); } } else { int facecount = vertices.size()/3; for(int j=0;j<facecount;j++) { Vector3 vtxs[3]; Vector2 uvs[3]; for(int k=0;k<3;k++) { vtxs[k]=p_xform.xform(vr[j*3+k]); } if (read_uv) { for(int k=0;k<3;k++) { uvs[k]=uvr[j*3+k]; } } //plot face _plot_face(0,0,vtxs,uvs,material,bounds); } } } } void BakedLight::_bake_add_to_aabb(const Transform& p_xform,Ref<Mesh>& p_mesh,bool &first) { for(int i=0;i<p_mesh->get_surface_count();i++) { if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES) continue; //only triangles Array a = p_mesh->surface_get_arrays(i); PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX]; int vc = vertices.size(); PoolVector<Vector3>::Read vr=vertices.read(); if (first) { bounds.pos=p_xform.xform(vr[0]); first=false; } for(int j=0;j<vc;j++) { bounds.expand_to(p_xform.xform(vr[j])); } } } void BakedLight::bake() { bake_cells_alloc=16; bake_cells.resize(1<<bake_cells_alloc); bake_cells_used=1; cells_per_axis=(1<<(cell_subdiv-1)); zero_alphas=0; bool aabb_first=true; print_line("Generating AABB"); bake_cells_level_used.resize(cell_subdiv); for(int i=0;i<cell_subdiv;i++) { bake_cells_level_used[i]=0; } int count=0; for (Set<GeometryInstance*>::Element *E=geometries.front();E;E=E->next()) { print_line("aabb geom "+itos(count)+"/"+itos(geometries.size())); GeometryInstance *geom = E->get(); if (geom->cast_to<MeshInstance>()) { MeshInstance *mesh_instance = geom->cast_to<MeshInstance>(); Ref<Mesh> mesh = mesh_instance->get_mesh(); if (mesh.is_valid()) { _bake_add_to_aabb(geom->get_relative_transform(this),mesh,aabb_first); } } count++; } print_line("AABB: "+bounds); ERR_FAIL_COND(aabb_first); bake_cells_write = bake_cells.write(); count=0; for (Set<GeometryInstance*>::Element *E=geometries.front();E;E=E->next()) { GeometryInstance *geom = E->get(); print_line("plot geom "+itos(count)+"/"+itos(geometries.size())); if (geom->cast_to<MeshInstance>()) { MeshInstance *mesh_instance = geom->cast_to<MeshInstance>(); Ref<Mesh> mesh = mesh_instance->get_mesh(); if (mesh.is_valid()) { _bake_add_mesh(geom->get_relative_transform(this),mesh); } } count++; } _fixup_plot(0, 0,0,0,0); bake_cells_write=PoolVector<BakeCell>::Write(); bake_cells.resize(bake_cells_used); print_line("total bake cells used: "+itos(bake_cells_used)); for(int i=0;i<cell_subdiv;i++) { print_line("level "+itos(i)+": "+itos(bake_cells_level_used[i])); } print_line("zero alphas: "+itos(zero_alphas)); } void BakedLight::_bake_directional(int p_idx, int p_level, int p_x,int p_y,int p_z,const Vector3& p_dir,const Color& p_color,int p_sign) { if (p_level==cell_subdiv-1) { Vector3 end; end.x = float(p_x+0.5) / cells_per_axis; end.y = float(p_y+0.5) / cells_per_axis; end.z = float(p_z+0.5) / cells_per_axis; end = bounds.pos + bounds.size*end; float max_ray_len = (bounds.size).length()*1.2; Vector3 begin = end + max_ray_len*-p_dir; //clip begin for(int i=0;i<3;i++) { if (ABS(p_dir[i])<CMP_EPSILON) { continue; // parallel to axis, don't clip } Plane p; p.normal[i]=1.0; p.d=bounds.pos[i]; if (p_dir[i]<0) { p.d+=bounds.size[i]; } Vector3 inters; if (p.intersects_segment(end,begin,&inters)) { begin=inters; } } int idx = _plot_ray(begin,end); if (idx>=0 && light_pass!=bake_cells_write[idx].light_pass) { //hit something, add or remove light to it Color albedo = Color(bake_cells_write[idx].albedo[0],bake_cells_write[idx].albedo[1],bake_cells_write[idx].albedo[2]); bake_cells_write[idx].light[0]+=albedo.r*p_color.r*p_sign; bake_cells_write[idx].light[1]+=albedo.g*p_color.g*p_sign; bake_cells_write[idx].light[2]+=albedo.b*p_color.b*p_sign; bake_cells_write[idx].light_pass=light_pass; } } else { int half = cells_per_axis >> (p_level+1); //go down for(int i=0;i<8;i++) { uint32_t child = bake_cells_write[p_idx].childs[i]; if (child==CHILD_EMPTY) continue; int nx=p_x; int ny=p_y; int nz=p_z; if (i&1) nx+=half; if (i&2) ny+=half; if (i&4) nz+=half; _bake_directional(child,p_level+1,nx,ny,nz,p_dir,p_color,p_sign); } } } void BakedLight::_bake_light(Light* p_light) { if (p_light->cast_to<DirectionalLight>()) { DirectionalLight * dl = p_light->cast_to<DirectionalLight>(); Transform rel_xf = dl->get_relative_transform(this); Vector3 light_dir = -rel_xf.basis.get_axis(2); Color color = dl->get_color(); float nrg = dl->get_param(Light::PARAM_ENERGY); color.r*=nrg; color.g*=nrg; color.b*=nrg; light_pass++; _bake_directional(0,0,0,0,0,light_dir,color,1); } } void BakedLight::_upscale_light(int p_idx,int p_level) { //go down float light_accum[3]={0,0,0}; float alpha_accum=0; bool check_children = p_level < (cell_subdiv -2); for(int i=0;i<8;i++) { uint32_t child = bake_cells_write[p_idx].childs[i]; if (child==CHILD_EMPTY) continue; if (check_children) { _upscale_light(child,p_level+1); } light_accum[0]+=bake_cells_write[child].light[0]; light_accum[1]+=bake_cells_write[child].light[1]; light_accum[2]+=bake_cells_write[child].light[2]; alpha_accum+=bake_cells_write[child].alpha; } bake_cells_write[p_idx].light[0]=light_accum[0]/8.0; bake_cells_write[p_idx].light[1]=light_accum[1]/8.0; bake_cells_write[p_idx].light[2]=light_accum[2]/8.0; bake_cells_write[p_idx].alpha=alpha_accum/8.0; } void BakedLight::bake_lights() { ERR_FAIL_COND(bake_cells.size()==0); bake_cells_write = bake_cells.write(); for(Set<Light*>::Element *E=lights.front();E;E=E->next()) { _bake_light(E->get()); } _upscale_light(0,0); bake_cells_write=PoolVector<BakeCell>::Write(); } Color BakedLight::_cone_trace(const Vector3& p_from, const Vector3& p_dir, float p_half_angle) { Color color(0,0,0,0); float tha = Math::tan(p_half_angle);//tan half angle Vector3 from =(p_from-bounds.pos)/bounds.size; //convert to 0..1 from/=cells_per_axis; //convert to voxels of size 1 Vector3 dir = (p_dir/bounds.size).normalized(); float max_dist = Vector3(cells_per_axis,cells_per_axis,cells_per_axis).length(); float dist = 1.0; // self occlusion in flat surfaces float alpha=0; while(dist < max_dist && alpha < 0.95) { #if 0 // smallest sample diameter possible is the voxel size float diameter = MAX(1.0, 2.0 * tha * dist); float lod = log2(diameter); Vector3 sample_pos = from + dist * dir; Color samples_base[2][8]={{Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0)}, {Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0),Color(0,0,0,0)}}; float levelf = Math::fposmod(lod,1.0); float fx = Math::fposmod(sample_pos.x,1.0); float fy = Math::fposmod(sample_pos.y,1.0); float fz = Math::fposmod(sample_pos.z,1.0); for(int l=0;l<2;l++){ int bx = Math::floor(sample_pos.x); int by = Math::floor(sample_pos.y); int bz = Math::floor(sample_pos.z); int lodn=int(Math::floor(lod))-l; bx>>=lodn; by>>=lodn; bz>>=lodn; int limit = MAX(0,cell_subdiv-lodn-1); for(int c=0;c<8;c++) { int x = bx; int y = by; int z = bz; if (c&1) { x+=1; } if (c&2) { y+=1; } if (c&4) { z+=1; } int ofs_x=0; int ofs_y=0; int ofs_z=0; int size = cells_per_axis>>lodn; int half=size/2; bool outside=x<0 || x>=size || y<0 || y>=size || z<0 || z>=size; if (outside) continue; uint32_t cell=0; for(int i=0;i<limit;i++) { BakeCell *bc = &bake_cells_write[cell]; int child = 0; if (x >= ofs_x + half) { child|=1; ofs_x+=half; } if (y >= ofs_y + half) { child|=2; ofs_y+=half; } if (z >= ofs_z + half) { child|=4; ofs_z+=half; } cell = bc->childs[child]; if (cell==CHILD_EMPTY) break; half>>=1; } if (cell!=CHILD_EMPTY) { samples_base[l][c].r=bake_cells_write[cell].light[0]; samples_base[l][c].g=bake_cells_write[cell].light[1]; samples_base[l][c].b=bake_cells_write[cell].light[2]; samples_base[l][c].a=bake_cells_write[cell].alpha; } } } Color m0x0 = samples_base[0][0].linear_interpolate(samples_base[0][1],fx); Color m0x1 = samples_base[0][2].linear_interpolate(samples_base[0][3],fx); Color m0y0 = m0x0.linear_interpolate(m0x1,fy); m0x0 = samples_base[0][4].linear_interpolate(samples_base[0][5],fx); m0x1 = samples_base[0][6].linear_interpolate(samples_base[0][7],fx); Color m0y1 = m0x0.linear_interpolate(m0x1,fy); Color m0z = m0y0.linear_interpolate(m0y1,fz); Color m1x0 = samples_base[1][0].linear_interpolate(samples_base[1][1],fx); Color m1x1 = samples_base[1][2].linear_interpolate(samples_base[1][3],fx); Color m1y0 = m1x0.linear_interpolate(m1x1,fy); m1x0 = samples_base[1][4].linear_interpolate(samples_base[1][5],fx); m1x1 = samples_base[1][6].linear_interpolate(samples_base[1][7],fx); Color m1y1 = m1x0.linear_interpolate(m1x1,fy); Color m1z = m1y0.linear_interpolate(m1y1,fz); Color m = m0z.linear_interpolate(m1z,levelf); #else float diameter = 1.0; Vector3 sample_pos = from + dist * dir; Color m(0,0,0,0); { int x = Math::floor(sample_pos.x); int y = Math::floor(sample_pos.y); int z = Math::floor(sample_pos.z); int ofs_x=0; int ofs_y=0; int ofs_z=0; int size = cells_per_axis; int half=size/2; bool outside=x<0 || x>=size || y<0 || y>=size || z<0 || z>=size; if (!outside) { uint32_t cell=0; for(int i=0;i<cell_subdiv-1;i++) { BakeCell *bc = &bake_cells_write[cell]; int child = 0; if (x >= ofs_x + half) { child|=1; ofs_x+=half; } if (y >= ofs_y + half) { child|=2; ofs_y+=half; } if (z >= ofs_z + half) { child|=4; ofs_z+=half; } cell = bc->childs[child]; if (cell==CHILD_EMPTY) break; half>>=1; } if (cell!=CHILD_EMPTY) { m.r=bake_cells_write[cell].light[0]; m.g=bake_cells_write[cell].light[1]; m.b=bake_cells_write[cell].light[2]; m.a=bake_cells_write[cell].alpha; } } } #endif // front-to-back compositing float a = (1.0 - alpha); color.r += a * m.r; color.g += a * m.g; color.b += a * m.b; alpha += a * m.a; //occlusion += a * voxelColor.a; //occlusion += (a * voxelColor.a) / (1.0 + 0.03 * diameter); dist += diameter * 0.5; // smoother //dist += diameter; // faster but misses more voxels } return color; } void BakedLight::_bake_radiance(int p_idx, int p_level, int p_x,int p_y,int p_z) { if (p_level==cell_subdiv-1) { const int NUM_CONES = 6; Vector3 cone_directions[6] = { Vector3(1, 0, 0), Vector3(0.5, 0.866025, 0), Vector3( 0.5, 0.267617, 0.823639), Vector3( 0.5, -0.700629, 0.509037), Vector3( 0.5, -0.700629, -0.509037), Vector3( 0.5, 0.267617, -0.823639) }; float coneWeights[6] = {0.25, 0.15, 0.15, 0.15, 0.15, 0.15}; Vector3 pos = (Vector3(p_x,p_y,p_z)/float(cells_per_axis))*bounds.size+bounds.pos; Vector3 voxel_size = bounds.size/float(cells_per_axis); pos+=voxel_size*0.5; Color accum; bake_cells_write[p_idx].light[0]=0; bake_cells_write[p_idx].light[1]=0; bake_cells_write[p_idx].light[2]=0; int freepix=0; for(int i=0;i<6;i++) { if (!(bake_cells_write[p_idx].used_sides&(1<<i))) continue; if ((i&1)==0) bake_cells_write[p_idx].light[i/2]=1.0; freepix++; continue; int ofs = i/2; Vector3 dir; if ((i&1)==0) dir[ofs]=1.0; else dir[ofs]=-1.0; for(int j=0;j<1;j++) { Vector3 cone_dir; cone_dir.x = cone_directions[j][(ofs+0)%3]; cone_dir.y = cone_directions[j][(ofs+1)%3]; cone_dir.z = cone_directions[j][(ofs+2)%3]; cone_dir[ofs]*=dir[ofs]; Color res = _cone_trace(pos+dir*voxel_size,cone_dir,Math::deg2rad(29.9849)); accum.r+=res.r;//*coneWeights[j]; accum.g+=res.g;//*coneWeights[j]; accum.b+=res.b;//*coneWeights[j]; } } #if 0 if (freepix==0) { bake_cells_write[p_idx].light[0]=0; bake_cells_write[p_idx].light[1]=0; bake_cells_write[p_idx].light[2]=0; } if (freepix==1) { bake_cells_write[p_idx].light[0]=1; bake_cells_write[p_idx].light[1]=0; bake_cells_write[p_idx].light[2]=0; } if (freepix==2) { bake_cells_write[p_idx].light[0]=0; bake_cells_write[p_idx].light[1]=1; bake_cells_write[p_idx].light[2]=0; } if (freepix==3) { bake_cells_write[p_idx].light[0]=1; bake_cells_write[p_idx].light[1]=1; bake_cells_write[p_idx].light[2]=0; } if (freepix==4) { bake_cells_write[p_idx].light[0]=0; bake_cells_write[p_idx].light[1]=0; bake_cells_write[p_idx].light[2]=1; } if (freepix==5) { bake_cells_write[p_idx].light[0]=1; bake_cells_write[p_idx].light[1]=0; bake_cells_write[p_idx].light[2]=1; } if (freepix==6) { bake_cells_write[p_idx].light[0]=0; bake_cells_write[p_idx].light[0]=1; bake_cells_write[p_idx].light[0]=1; } #endif //bake_cells_write[p_idx].radiance[0]=accum.r; //bake_cells_write[p_idx].radiance[1]=accum.g; //bake_cells_write[p_idx].radiance[2]=accum.b; } else { int half = cells_per_axis >> (p_level+1); //go down for(int i=0;i<8;i++) { uint32_t child = bake_cells_write[p_idx].childs[i]; if (child==CHILD_EMPTY) continue; int nx=p_x; int ny=p_y; int nz=p_z; if (i&1) nx+=half; if (i&2) ny+=half; if (i&4) nz+=half; _bake_radiance(child,p_level+1,nx,ny,nz); } } } void BakedLight::bake_radiance() { ERR_FAIL_COND(bake_cells.size()==0); bake_cells_write = bake_cells.write(); _bake_radiance(0,0,0,0,0); bake_cells_write=PoolVector<BakeCell>::Write(); } int BakedLight::_find_cell(int x,int y, int z) { uint32_t cell=0; int ofs_x=0; int ofs_y=0; int ofs_z=0; int size = cells_per_axis; int half=size/2; if (x<0 || x>=size) return -1; if (y<0 || y>=size) return -1; if (z<0 || z>=size) return -1; for(int i=0;i<cell_subdiv-1;i++) { BakeCell *bc = &bake_cells_write[cell]; int child = 0; if (x >= ofs_x + half) { child|=1; ofs_x+=half; } if (y >= ofs_y + half) { child|=2; ofs_y+=half; } if (z >= ofs_z + half) { child|=4; ofs_z+=half; } cell = bc->childs[child]; if (cell==CHILD_EMPTY) return -1; half>>=1; } return cell; } int BakedLight::_plot_ray(const Vector3& p_from, const Vector3& p_to) { Vector3 from = (p_from - bounds.pos) / bounds.size; Vector3 to = (p_to - bounds.pos) / bounds.size; int x1 = Math::floor(from.x*cells_per_axis); int y1 = Math::floor(from.y*cells_per_axis); int z1 = Math::floor(from.z*cells_per_axis); int x2 = Math::floor(to.x*cells_per_axis); int y2 = Math::floor(to.y*cells_per_axis); int z2 = Math::floor(to.z*cells_per_axis); int i, dx, dy, dz, l, m, n, x_inc, y_inc, z_inc, err_1, err_2, dx2, dy2, dz2; int point[3]; point[0] = x1; point[1] = y1; point[2] = z1; dx = x2 - x1; dy = y2 - y1; dz = z2 - z1; x_inc = (dx < 0) ? -1 : 1; l = ABS(dx); y_inc = (dy < 0) ? -1 : 1; m = ABS(dy); z_inc = (dz < 0) ? -1 : 1; n = ABS(dz); dx2 = l << 1; dy2 = m << 1; dz2 = n << 1; if ((l >= m) && (l >= n)) { err_1 = dy2 - l; err_2 = dz2 - l; for (i = 0; i < l; i++) { int cell = _find_cell(point[0],point[1],point[2]); if (cell>=0) return cell; if (err_1 > 0) { point[1] += y_inc; err_1 -= dx2; } if (err_2 > 0) { point[2] += z_inc; err_2 -= dx2; } err_1 += dy2; err_2 += dz2; point[0] += x_inc; } } else if ((m >= l) && (m >= n)) { err_1 = dx2 - m; err_2 = dz2 - m; for (i = 0; i < m; i++) { int cell = _find_cell(point[0],point[1],point[2]); if (cell>=0) return cell; if (err_1 > 0) { point[0] += x_inc; err_1 -= dy2; } if (err_2 > 0) { point[2] += z_inc; err_2 -= dy2; } err_1 += dx2; err_2 += dz2; point[1] += y_inc; } } else { err_1 = dy2 - n; err_2 = dx2 - n; for (i = 0; i < n; i++) { int cell = _find_cell(point[0],point[1],point[2]); if (cell>=0) return cell; if (err_1 > 0) { point[1] += y_inc; err_1 -= dz2; } if (err_2 > 0) { point[0] += x_inc; err_2 -= dz2; } err_1 += dy2; err_2 += dx2; point[2] += z_inc; } } return _find_cell(point[0],point[1],point[2]); } void BakedLight::set_cell_subdiv(int p_subdiv) { cell_subdiv=p_subdiv; //VS::get_singleton()->baked_light_set_subdivision(baked_light,p_subdiv); } int BakedLight::get_cell_subdiv() const { return cell_subdiv; } Rect3 BakedLight::get_aabb() const { return Rect3(Vector3(0,0,0),Vector3(1,1,1)); } PoolVector<Face3> BakedLight::get_faces(uint32_t p_usage_flags) const { return PoolVector<Face3>(); } String BakedLight::get_configuration_warning() const { return String(); } void BakedLight::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,DebugMode p_mode,Ref<MultiMesh> &p_multimesh,int &idx) { if (p_level==cell_subdiv-1) { Vector3 center = p_aabb.pos+p_aabb.size*0.5; Transform xform; xform.origin=center; xform.basis.scale(p_aabb.size*0.5); p_multimesh->set_instance_transform(idx,xform); Color col; switch(p_mode) { case DEBUG_ALBEDO: { col=Color(bake_cells_write[p_idx].albedo[0],bake_cells_write[p_idx].albedo[1],bake_cells_write[p_idx].albedo[2]); } break; case DEBUG_LIGHT: { col=Color(bake_cells_write[p_idx].light[0],bake_cells_write[p_idx].light[1],bake_cells_write[p_idx].light[2]); Color colr=Color(bake_cells_write[p_idx].radiance[0],bake_cells_write[p_idx].radiance[1],bake_cells_write[p_idx].radiance[2]); col.r+=colr.r; col.g+=colr.g; col.b+=colr.b; } break; } p_multimesh->set_instance_color(idx,col); idx++; } else { for(int i=0;i<8;i++) { if (bake_cells_write[p_idx].childs[i]==CHILD_EMPTY) continue; Rect3 aabb=p_aabb; aabb.size*=0.5; if (i&1) aabb.pos.x+=aabb.size.x; if (i&2) aabb.pos.y+=aabb.size.y; if (i&4) aabb.pos.z+=aabb.size.z; _debug_mesh(bake_cells_write[p_idx].childs[i],p_level+1,aabb,p_mode,p_multimesh,idx); } } } void BakedLight::create_debug_mesh(DebugMode p_mode) { Ref<MultiMesh> mm; mm.instance(); mm->set_transform_format(MultiMesh::TRANSFORM_3D); mm->set_color_format(MultiMesh::COLOR_8BIT); mm->set_instance_count(bake_cells_level_used[cell_subdiv-1]); Ref<Mesh> mesh; mesh.instance(); { Array arr; arr.resize(Mesh::ARRAY_MAX); PoolVector<Vector3> vertices; PoolVector<Color> colors; int vtx_idx=0; #define ADD_VTX(m_idx);\ vertices.push_back( face_points[m_idx] );\ colors.push_back( Color(1,1,1,1) );\ vtx_idx++;\ for (int i=0;i<6;i++) { Vector3 face_points[4]; for (int j=0;j<4;j++) { float v[3]; v[0]=1.0; v[1]=1-2*((j>>1)&1); v[2]=v[1]*(1-2*(j&1)); for (int k=0;k<3;k++) { if (i<3) face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1); else face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1); } } //tri 1 ADD_VTX(0); ADD_VTX(1); ADD_VTX(2); //tri 2 ADD_VTX(2); ADD_VTX(3); ADD_VTX(0); } arr[Mesh::ARRAY_VERTEX]=vertices; arr[Mesh::ARRAY_COLOR]=colors; mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr); } { Ref<FixedSpatialMaterial> fsm; fsm.instance(); fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true); fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true); fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true); fsm->set_albedo(Color(1,1,1,1)); mesh->surface_set_material(0,fsm); } mm->set_mesh(mesh); bake_cells_write = bake_cells.write(); int idx=0; _debug_mesh(0,0,bounds,p_mode,mm,idx); print_line("written: "+itos(idx)+" total: "+itos(bake_cells_level_used[cell_subdiv-1])); MultiMeshInstance *mmi = memnew( MultiMeshInstance ); mmi->set_multimesh(mm); add_child(mmi); #ifdef TOOLS_ENABLED if (get_tree()->get_edited_scene_root()==this){ mmi->set_owner(this); } else { mmi->set_owner(get_owner()); } #else mmi->set_owner(get_owner()); #endif } void BakedLight::_debug_mesh_albedo() { create_debug_mesh(DEBUG_ALBEDO); } void BakedLight::_debug_mesh_light() { create_debug_mesh(DEBUG_LIGHT); } void BakedLight::_bind_methods() { ClassDB::bind_method(_MD("set_cell_subdiv","steps"),&BakedLight::set_cell_subdiv); ClassDB::bind_method(_MD("get_cell_subdiv"),&BakedLight::get_cell_subdiv); ClassDB::bind_method(_MD("bake"),&BakedLight::bake); ClassDB::set_method_flags(get_class_static(),_SCS("bake"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); ClassDB::bind_method(_MD("bake_lights"),&BakedLight::bake_lights); ClassDB::set_method_flags(get_class_static(),_SCS("bake_lights"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); ClassDB::bind_method(_MD("bake_radiance"),&BakedLight::bake_radiance); ClassDB::set_method_flags(get_class_static(),_SCS("bake_radiance"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); ClassDB::bind_method(_MD("debug_mesh_albedo"),&BakedLight::_debug_mesh_albedo); ClassDB::set_method_flags(get_class_static(),_SCS("debug_mesh_albedo"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); ClassDB::bind_method(_MD("debug_mesh_light"),&BakedLight::_debug_mesh_light); ClassDB::set_method_flags(get_class_static(),_SCS("debug_mesh_light"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); ADD_PROPERTY(PropertyInfo(Variant::INT,"cell_subdiv"),_SCS("set_cell_subdiv"),_SCS("get_cell_subdiv")); ADD_SIGNAL( MethodInfo("baked_light_changed")); } BakedLight::BakedLight() { //baked_light=VisualServer::get_singleton()->baked_light_create(); VS::get_singleton()->instance_set_base(get_instance(),baked_light); cell_subdiv=8; bake_texture_size=128; color_scan_cell_width=8; light_pass=0; } BakedLight::~BakedLight() { VS::get_singleton()->free(baked_light); } ///////////////////////// #if 0 void BakedLightSampler::set_param(Param p_param,float p_value) { ERR_FAIL_INDEX(p_param,PARAM_MAX); params[p_param]=p_value; VS::get_singleton()->baked_light_sampler_set_param(base,VS::BakedLightSamplerParam(p_param),p_value); } float BakedLightSampler::get_param(Param p_param) const{ ERR_FAIL_INDEX_V(p_param,PARAM_MAX,0); return params[p_param]; } void BakedLightSampler::set_resolution(int p_resolution){ ERR_FAIL_COND(p_resolution<4 || p_resolution>32); resolution=p_resolution; VS::get_singleton()->baked_light_sampler_set_resolution(base,resolution); } int BakedLightSampler::get_resolution() const { return resolution; } AABB BakedLightSampler::get_aabb() const { float r = get_param(PARAM_RADIUS); return AABB( Vector3(-r,-r,-r),Vector3(r*2,r*2,r*2)); } DVector<Face3> BakedLightSampler::get_faces(uint32_t p_usage_flags) const { return DVector<Face3>(); } void BakedLightSampler::_bind_methods() { ClassDB::bind_method(_MD("set_param","param","value"),&BakedLightSampler::set_param); ClassDB::bind_method(_MD("get_param","param"),&BakedLightSampler::get_param); ClassDB::bind_method(_MD("set_resolution","resolution"),&BakedLightSampler::set_resolution); ClassDB::bind_method(_MD("get_resolution"),&BakedLightSampler::get_resolution); BIND_CONSTANT( PARAM_RADIUS ); BIND_CONSTANT( PARAM_STRENGTH ); BIND_CONSTANT( PARAM_ATTENUATION ); BIND_CONSTANT( PARAM_DETAIL_RATIO ); BIND_CONSTANT( PARAM_MAX ); ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/radius",PROPERTY_HINT_RANGE,"0.01,1024,0.01"),_SCS("set_param"),_SCS("get_param"),PARAM_RADIUS); ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/strength",PROPERTY_HINT_RANGE,"0.01,16,0.01"),_SCS("set_param"),_SCS("get_param"),PARAM_STRENGTH); ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/attenuation",PROPERTY_HINT_EXP_EASING),_SCS("set_param"),_SCS("get_param"),PARAM_ATTENUATION); ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/detail_ratio",PROPERTY_HINT_RANGE,"0.01,1.0,0.01"),_SCS("set_param"),_SCS("get_param"),PARAM_DETAIL_RATIO); //ADD_PROPERTYI( PropertyInfo(Variant::REAL,"params/detail_ratio",PROPERTY_HINT_RANGE,"0,20,1"),_SCS("set_param"),_SCS("get_param"),PARAM_DETAIL_RATIO); ADD_PROPERTY( PropertyInfo(Variant::REAL,"params/resolution",PROPERTY_HINT_RANGE,"4,32,1"),_SCS("set_resolution"),_SCS("get_resolution")); } BakedLightSampler::BakedLightSampler() { base = VS::get_singleton()->baked_light_sampler_create(); set_base(base); params[PARAM_RADIUS]=1.0; params[PARAM_STRENGTH]=1.0; params[PARAM_ATTENUATION]=1.0; params[PARAM_DETAIL_RATIO]=0.1; resolution=16; } BakedLightSampler::~BakedLightSampler(){ VS::get_singleton()->free(base); } #endif
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_phaser.cpp
148
#include "audio_effect_phaser.h" #include "servers/audio_server.h" #include "math_funcs.h" void AudioEffectPhaserInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { float sampling_rate = AudioServer::get_singleton()->get_mix_rate(); float dmin = base->range_min / (sampling_rate/2.0); float dmax = base->range_max / (sampling_rate/2.0); float increment = 2.f * Math_PI * (base->rate / sampling_rate); for(int i=0;i<p_frame_count;i++) { phase += increment; while ( phase >= Math_PI * 2.f ) { phase -= Math_PI * 2.f; } float d = dmin + (dmax-dmin) * ((sin( phase ) + 1.f)/2.f); //update filter coeffs for( int j=0; j<6; j++ ) { allpass[0][j].delay( d ); allpass[1][j].delay( d ); } //calculate output float y = allpass[0][0].update( allpass[0][1].update( allpass[0][2].update( allpass[0][3].update( allpass[0][4].update( allpass[0][5].update( p_src_frames[i].l + h.l * base->feedback )))))); h.l=y; p_dst_frames[i].l = p_src_frames[i].l + y * base->depth; y = allpass[1][0].update( allpass[1][1].update( allpass[1][2].update( allpass[1][3].update( allpass[1][4].update( allpass[1][5].update( p_src_frames[i].r + h.r * base->feedback )))))); h.r=y; p_dst_frames[i].r = p_src_frames[i].r + y * base->depth; } } Ref<AudioEffectInstance> AudioEffectPhaser::instance() { Ref<AudioEffectPhaserInstance> ins; ins.instance(); ins->base=Ref<AudioEffectPhaser>(this); ins->phase=0; ins->h=AudioFrame(0,0); return ins; } void AudioEffectPhaser::set_range_min_hz(float p_hz) { range_min=p_hz; } float AudioEffectPhaser::get_range_min_hz() const{ return range_min; } void AudioEffectPhaser::set_range_max_hz(float p_hz){ range_max=p_hz; } float AudioEffectPhaser::get_range_max_hz() const{ return range_max; } void AudioEffectPhaser::set_rate_hz(float p_hz){ rate=p_hz; } float AudioEffectPhaser::get_rate_hz() const{ return rate; } void AudioEffectPhaser::set_feedback(float p_fbk){ feedback=p_fbk; } float AudioEffectPhaser::get_feedback() const{ return feedback; } void AudioEffectPhaser::set_depth(float p_depth) { depth=p_depth; } float AudioEffectPhaser::get_depth() const { return depth; } void AudioEffectPhaser::_bind_methods() { ClassDB::bind_method(_MD("set_range_min_hz","hz"),&AudioEffectPhaser::set_range_min_hz); ClassDB::bind_method(_MD("get_range_min_hz"),&AudioEffectPhaser::get_range_min_hz); ClassDB::bind_method(_MD("set_range_max_hz","hz"),&AudioEffectPhaser::set_range_max_hz); ClassDB::bind_method(_MD("get_range_max_hz"),&AudioEffectPhaser::get_range_max_hz); ClassDB::bind_method(_MD("set_rate_hz","hz"),&AudioEffectPhaser::set_rate_hz); ClassDB::bind_method(_MD("get_rate_hz"),&AudioEffectPhaser::get_rate_hz); ClassDB::bind_method(_MD("set_feedback","fbk"),&AudioEffectPhaser::set_feedback); ClassDB::bind_method(_MD("get_feedback"),&AudioEffectPhaser::get_feedback); ClassDB::bind_method(_MD("set_depth","depth"),&AudioEffectPhaser::set_depth); ClassDB::bind_method(_MD("get_depth"),&AudioEffectPhaser::get_depth); ADD_PROPERTY(PropertyInfo(Variant::REAL,"range_min_hz",PROPERTY_HINT_RANGE,"10,10000"),_SCS("set_range_min_hz"),_SCS("get_range_min_hz")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"range_max_hz",PROPERTY_HINT_RANGE,"10,10000"),_SCS("set_range_max_hz"),_SCS("get_range_max_hz")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"rate_hz",PROPERTY_HINT_RANGE,"0.01,20"),_SCS("set_rate_hz"),_SCS("get_rate_hz")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"feedback",PROPERTY_HINT_RANGE,"0.1,0.9,0.1"),_SCS("set_feedback"),_SCS("get_feedback")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"depth",PROPERTY_HINT_RANGE,"0.1,4,0.1"),_SCS("set_depth"),_SCS("get_depth")); } AudioEffectPhaser::AudioEffectPhaser() { range_min=440; range_max=1600; rate=0.5; feedback=0.7; depth=1; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
drivers/gles3/rasterizer_gles3.cpp
366
#include "rasterizer_gles3.h" #include "os/os.h" #include "globals.h" #include "gl_context/context_gl.h" #include <string.h> RasterizerStorage *RasterizerGLES3::get_storage() { return storage; } RasterizerCanvas *RasterizerGLES3::get_canvas() { return canvas; } RasterizerScene *RasterizerGLES3::get_scene() { return scene; } #define _EXT_DEBUG_OUTPUT_SYNCHRONOUS_ARB 0x8242 #define _EXT_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB 0x8243 #define _EXT_DEBUG_CALLBACK_FUNCTION_ARB 0x8244 #define _EXT_DEBUG_CALLBACK_USER_PARAM_ARB 0x8245 #define _EXT_DEBUG_SOURCE_API_ARB 0x8246 #define _EXT_DEBUG_SOURCE_WINDOW_SYSTEM_ARB 0x8247 #define _EXT_DEBUG_SOURCE_SHADER_COMPILER_ARB 0x8248 #define _EXT_DEBUG_SOURCE_THIRD_PARTY_ARB 0x8249 #define _EXT_DEBUG_SOURCE_APPLICATION_ARB 0x824A #define _EXT_DEBUG_SOURCE_OTHER_ARB 0x824B #define _EXT_DEBUG_TYPE_ERROR_ARB 0x824C #define _EXT_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB 0x824D #define _EXT_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB 0x824E #define _EXT_DEBUG_TYPE_PORTABILITY_ARB 0x824F #define _EXT_DEBUG_TYPE_PERFORMANCE_ARB 0x8250 #define _EXT_DEBUG_TYPE_OTHER_ARB 0x8251 #define _EXT_MAX_DEBUG_MESSAGE_LENGTH_ARB 0x9143 #define _EXT_MAX_DEBUG_LOGGED_MESSAGES_ARB 0x9144 #define _EXT_DEBUG_LOGGED_MESSAGES_ARB 0x9145 #define _EXT_DEBUG_SEVERITY_HIGH_ARB 0x9146 #define _EXT_DEBUG_SEVERITY_MEDIUM_ARB 0x9147 #define _EXT_DEBUG_SEVERITY_LOW_ARB 0x9148 #define _EXT_DEBUG_OUTPUT 0x92E0 #ifdef WINDOWS_ENABLED #define GLAPIENTRY APIENTRY #else #define GLAPIENTRY #endif static void GLAPIENTRY _gl_debug_print(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const GLvoid *userParam) { if (type==_EXT_DEBUG_TYPE_OTHER_ARB) return; print_line("mesege"); char debSource[256], debType[256], debSev[256]; if(source == _EXT_DEBUG_SOURCE_API_ARB) strcpy(debSource, "OpenGL"); else if(source == _EXT_DEBUG_SOURCE_WINDOW_SYSTEM_ARB) strcpy(debSource, "Windows"); else if(source == _EXT_DEBUG_SOURCE_SHADER_COMPILER_ARB) strcpy(debSource, "Shader Compiler"); else if(source == _EXT_DEBUG_SOURCE_THIRD_PARTY_ARB) strcpy(debSource, "Third Party"); else if(source == _EXT_DEBUG_SOURCE_APPLICATION_ARB) strcpy(debSource, "Application"); else if(source == _EXT_DEBUG_SOURCE_OTHER_ARB) strcpy(debSource, "Other"); if(type == _EXT_DEBUG_TYPE_ERROR_ARB) strcpy(debType, "Error"); else if(type == _EXT_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB) strcpy(debType, "Deprecated behavior"); else if(type == _EXT_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB) strcpy(debType, "Undefined behavior"); else if(type == _EXT_DEBUG_TYPE_PORTABILITY_ARB) strcpy(debType, "Portability"); else if(type == _EXT_DEBUG_TYPE_PERFORMANCE_ARB) strcpy(debType, "Performance"); else if(type == _EXT_DEBUG_TYPE_OTHER_ARB) strcpy(debType, "Other"); if(severity == _EXT_DEBUG_SEVERITY_HIGH_ARB) strcpy(debSev, "High"); else if(severity == _EXT_DEBUG_SEVERITY_MEDIUM_ARB) strcpy(debSev, "Medium"); else if(severity == _EXT_DEBUG_SEVERITY_LOW_ARB) strcpy(debSev, "Low"); String output = String()+ "GL ERROR: Source: " + debSource + "\tType: " + debType + "\tID: " + itos(id) + "\tSeverity: " + debSev + "\tMessage: " + message; ERR_PRINTS(output); } typedef void (*DEBUGPROCARB)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char* message, const void* userParam); typedef void (* DebugMessageCallbackARB) (DEBUGPROCARB callback, const void *userParam); void RasterizerGLES3::initialize() { if (OS::get_singleton()->is_stdout_verbose()) { print_line("Using GLES3 video driver"); } #ifdef GLEW_ENABLED GLuint res = glewInit(); ERR_FAIL_COND(res!=GLEW_OK); if (OS::get_singleton()->is_stdout_verbose()) { print_line(String("GLES2: Using GLEW ") + (const char*) glewGetString(GLEW_VERSION)); } // Check for GL 2.1 compatibility, if not bail out if (!glewIsSupported("GL_VERSION_3_0")) { ERR_PRINT("Your system's graphic drivers seem not to support OpenGL 3.0+ / GLES 3.0, sorry :(\n" "Try a drivers update, buy a new GPU or try software rendering on Linux; Godot will now crash with a segmentation fault."); OS::get_singleton()->alert("Your system's graphic drivers seem not to support OpenGL 3.0+ / GLES 3.0, sorry :(\n" "Godot Engine will self-destruct as soon as you acknowledge this error message.", "Fatal error: Insufficient OpenGL / GLES drivers"); // TODO: If it's even possible, we should stop the execution without segfault and memory leaks :) } #endif #ifdef GLAD_ENABLED if(!gladLoadGL()) { ERR_PRINT("Error initializing GLAD"); } #ifdef __APPLE__ // FIXME glDebugMessageCallbackARB does not seem to work on Mac OS X and opengl 3, this may be an issue with our opengl canvas.. #else glEnable(_EXT_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageCallbackARB(_gl_debug_print, NULL); glEnable(_EXT_DEBUG_OUTPUT); #endif #endif /* glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_ERROR_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE); glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE); glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE); glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_PORTABILITY_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE); glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_PERFORMANCE_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE); glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB,GL_DEBUG_TYPE_OTHER_ARB,GL_DEBUG_SEVERITY_HIGH_ARB,0,NULL,GL_TRUE); glDebugMessageInsertARB( GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_OTHER_ARB, 1, GL_DEBUG_SEVERITY_HIGH_ARB,5, "hello"); */ storage->initialize(); canvas->initialize(); scene->initialize(); } void RasterizerGLES3::begin_frame(){ uint64_t tick = OS::get_singleton()->get_ticks_usec(); double time_total = double(tick)/1000000.0; storage->frame.time[0]=time_total; storage->frame.time[1]=Math::fmod(time_total,3600); storage->frame.time[2]=Math::fmod(time_total,900); storage->frame.time[3]=Math::fmod(time_total,60); storage->frame.count++; storage->frame.delta = double(tick-storage->frame.prev_tick)/1000000.0; if (storage->frame.prev_tick==0) { //to avoid hiccups storage->frame.delta=0.001; } storage->frame.prev_tick=tick; storage->update_dirty_multimeshes(); storage->update_dirty_skeletons(); storage->update_dirty_shaders(); storage->update_dirty_materials(); storage->update_particles(); storage->info.render_object_count=0; storage->info.render_material_switch_count=0; storage->info.render_surface_switch_count=0; storage->info.render_shader_rebind_count=0; storage->info.render_vertices_count=0; scene->iteration(); } void RasterizerGLES3::set_current_render_target(RID p_render_target){ if (!p_render_target.is_valid() && storage->frame.current_rt && storage->frame.clear_request) { //handle pending clear request, if the framebuffer was not cleared glBindFramebuffer(GL_FRAMEBUFFER,storage->frame.current_rt->fbo); print_line("unbind clear of: "+storage->frame.clear_request_color); glClearColor( storage->frame.clear_request_color.r, storage->frame.clear_request_color.g, storage->frame.clear_request_color.b, storage->frame.clear_request_color.a ); glClear(GL_COLOR_BUFFER_BIT); } if (p_render_target.is_valid()) { RasterizerStorageGLES3::RenderTarget * rt = storage->render_target_owner.getornull(p_render_target); if (!rt) { storage->frame.current_rt=NULL; } ERR_FAIL_COND(!rt); storage->frame.current_rt=rt; storage->frame.clear_request=false; glViewport(0,0,rt->width,rt->height); } else { storage->frame.current_rt=NULL; storage->frame.clear_request=false; glViewport(0,0,OS::get_singleton()->get_window_size().width,OS::get_singleton()->get_window_size().height); glBindFramebuffer(GL_FRAMEBUFFER,RasterizerStorageGLES3::system_fbo); } } void RasterizerGLES3::restore_render_target() { ERR_FAIL_COND(storage->frame.current_rt==NULL); RasterizerStorageGLES3::RenderTarget * rt = storage->frame.current_rt; glBindFramebuffer(GL_FRAMEBUFFER,rt->fbo); glViewport(0,0,rt->width,rt->height); } void RasterizerGLES3::clear_render_target(const Color& p_color) { ERR_FAIL_COND(!storage->frame.current_rt); storage->frame.clear_request=true; storage->frame.clear_request_color=p_color; } void RasterizerGLES3::blit_render_target_to_screen(RID p_render_target,const Rect2& p_screen_rect,int p_screen){ ERR_FAIL_COND( storage->frame.current_rt ); RasterizerStorageGLES3::RenderTarget *rt = storage->render_target_owner.getornull(p_render_target); ERR_FAIL_COND(!rt); canvas->canvas_begin(); glDisable(GL_BLEND); glBindFramebuffer(GL_FRAMEBUFFER,RasterizerStorageGLES3::system_fbo); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,rt->color); canvas->draw_generic_textured_rect(p_screen_rect,Rect2(0,0,1,-1)); glBindTexture(GL_TEXTURE_2D,0); canvas->canvas_end(); } void RasterizerGLES3::end_frame(){ #if 0 canvas->canvas_begin(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); float vtx[8]={0,0, 0,1, 1,1, 1,0 }; glBindBuffer(GL_ARRAY_BUFFER,0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, 0, vtx ); //glBindBuffer(GL_ARRAY_BUFFER,canvas->data.canvas_quad_vertices); //glEnableVertexAttribArray(VS::ARRAY_VERTEX); //glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, 0, 0 ); glBindVertexArray(canvas->data.canvas_quad_array); canvas->draw_generic_textured_rect(Rect2(0,0,15,15),Rect2(0,0,1,1)); #endif OS::get_singleton()->swap_buffers(); /* print_line("objects: "+itos(storage->info.render_object_count)); print_line("material chages: "+itos(storage->info.render_material_switch_count)); print_line("surface changes: "+itos(storage->info.render_surface_switch_count)); print_line("shader changes: "+itos(storage->info.render_shader_rebind_count)); print_line("vertices: "+itos(storage->info.render_vertices_count)); */ } void RasterizerGLES3::finalize(){ storage->finalize(); canvas->finalize(); } Rasterizer *RasterizerGLES3::_create_current() { return memnew( RasterizerGLES3 ); } void RasterizerGLES3::make_current() { _create_func=_create_current; } void RasterizerGLES3::register_config() { GLOBAL_DEF("rendering/gles3/render_architecture",0); GlobalConfig::get_singleton()->set_custom_property_info("rendering/gles3/render_architecture",PropertyInfo(Variant::INT,"",PROPERTY_HINT_ENUM,"Desktop,Mobile")); GLOBAL_DEF("rendering/quality/use_nearest_mipmap_filter",false); GLOBAL_DEF("rendering/quality/anisotropic_filter_level",4.0); } RasterizerGLES3::RasterizerGLES3() { storage = memnew( RasterizerStorageGLES3 ); canvas = memnew( RasterizerCanvasGLES3 ); scene = memnew( RasterizerSceneGLES3 ); canvas->storage=storage; storage->canvas=canvas; scene->storage=storage; storage->scene=scene; } RasterizerGLES3::~RasterizerGLES3() { memdelete(storage); memdelete(canvas); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/visual/shader_language.cpp
3,296
/*************************************************************************/ /* shader_language.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "shader_language.h" #include "print_string.h" #include "os/os.h" static bool _is_text_char(CharType c) { return (c>='a' && c<='z') || (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='_'; } static bool _is_number(CharType c) { return (c>='0' && c<='9'); } static bool _is_hex(CharType c) { return (c>='0' && c<='9') || (c>='a' && c<='f') || (c>='A' && c<='F'); } String ShaderLanguage::get_operator_text(Operator p_op) { static const char* op_names[OP_MAX]={"==", "!=", "<", "<=", ">", ">=", "&&", "||", "!", "-", "+", "-", "*", "/", "%", "<<", ">>", "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", "&=", "|=", "^=", "&", "|", "^", "~", "++" "--", "()", "construct"}; return op_names[p_op]; } const char * ShaderLanguage::token_names[TK_MAX]={ "EMPTY", "IDENTIFIER", "TRUE", "FALSE", "REAL_CONSTANT", "INT_CONSTANT", "TYPE_VOID", "TYPE_BOOL", "TYPE_BVEC2", "TYPE_BVEC3", "TYPE_BVEC4", "TYPE_INT", "TYPE_IVEC2", "TYPE_IVEC3", "TYPE_IVEC4", "TYPE_UINT", "TYPE_UVEC2", "TYPE_UVEC3", "TYPE_UVEC4", "TYPE_FLOAT", "TYPE_VEC2", "TYPE_VEC3", "TYPE_VEC4", "TYPE_MAT2", "TYPE_MAT3", "TYPE_MAT4", "TYPE_SAMPLER2D", "TYPE_ISAMPLER2D", "TYPE_USAMPLER2D", "TYPE_SAMPLERCUBE", "PRECISION_LOW", "PRECISION_MID", "PRECISION_HIGH", "OP_EQUAL", "OP_NOT_EQUAL", "OP_LESS", "OP_LESS_EQUAL", "OP_GREATER", "OP_GREATER_EQUAL", "OP_AND", "OP_OR", "OP_NOT", "OP_ADD", "OP_SUB", "OP_MUL", "OP_DIV", "OP_MOD", "OP_SHIFT_LEFT", "OP_SHIFT_RIGHT", "OP_ASSIGN", "OP_ASSIGN_ADD", "OP_ASSIGN_SUB", "OP_ASSIGN_MUL", "OP_ASSIGN_DIV", "OP_ASSIGN_MOD", "OP_ASSIGN_SHIFT_LEFT", "OP_ASSIGN_SHIFT_RIGHT", "OP_ASSIGN_BIT_AND", "OP_ASSIGN_BIT_OR", "OP_ASSIGN_BIT_XOR", "OP_BIT_AND", "OP_BIT_OR", "OP_BIT_XOR", "OP_BIT_INVERT", "OP_INCREMENT", "OP_DECREMENT", "CF_IF", "CF_ELSE", "CF_FOR", "CF_WHILE", "CF_DO", "CF_SWITCH", "CF_CASE", "CF_BREAK", "CF_CONTINUE", "CF_RETURN", "BRACKET_OPEN", "BRACKET_CLOSE", "CURLY_BRACKET_OPEN", "CURLY_BRACKET_CLOSE", "PARENTHESIS_OPEN", "PARENTHESIS_CLOSE", "QUESTION", "COMMA", "COLON", "SEMICOLON", "PERIOD", "UNIFORM", "VARYING", "RENDER_MODE", "HINT_WHITE_TEXTURE", "HINT_BLACK_TEXTURE", "HINT_NORMAL_TEXTURE", "HINT_ANISO_TEXTURE", "HINT_ALBEDO_TEXTURE", "HINT_BLACK_ALBEDO_TEXTURE", "HINT_COLOR", "HINT_RANGE", "CURSOR", "ERROR", "EOF", }; String ShaderLanguage::get_token_text(Token p_token) { String name=token_names[p_token.type]; if (p_token.type==TK_INT_CONSTANT || p_token.type==TK_REAL_CONSTANT) { name+="("+rtos(p_token.constant)+")"; } else if (p_token.type==TK_IDENTIFIER) { name+="("+String(p_token.text)+")"; } else if (p_token.type==TK_ERROR) { name+="("+String(p_token.text)+")"; } return name; } ShaderLanguage::Token ShaderLanguage::_make_token(TokenType p_type,const StringName& p_text) { Token tk; tk.type=p_type; tk.text=p_text; tk.line=tk_line; if (tk.type==TK_ERROR) { _set_error(p_text); } return tk; } const ShaderLanguage::KeyWord ShaderLanguage::keyword_list[]={ {TK_TRUE,"true"}, {TK_FALSE,"false"}, {TK_TYPE_VOID,"void"}, {TK_TYPE_BOOL,"bool"}, {TK_TYPE_BVEC2,"bvec2"}, {TK_TYPE_BVEC3,"bvec3"}, {TK_TYPE_BVEC4,"bvec4"}, {TK_TYPE_INT,"int"}, {TK_TYPE_IVEC2,"ivec2"}, {TK_TYPE_IVEC3,"ivec3"}, {TK_TYPE_IVEC4,"ivec4"}, {TK_TYPE_UINT,"uint"}, {TK_TYPE_UVEC2,"uvec2"}, {TK_TYPE_UVEC3,"uvec3"}, {TK_TYPE_UVEC4,"uvec4"}, {TK_TYPE_FLOAT,"float"}, {TK_TYPE_VEC2,"vec2"}, {TK_TYPE_VEC3,"vec3"}, {TK_TYPE_VEC4,"vec4"}, {TK_TYPE_MAT2,"mat2"}, {TK_TYPE_MAT3,"mat3"}, {TK_TYPE_MAT4,"mat4"}, {TK_TYPE_SAMPLER2D,"sampler2D"}, {TK_TYPE_ISAMPLER2D,"isampler2D"}, {TK_TYPE_USAMPLER2D,"usampler2D"}, {TK_TYPE_SAMPLERCUBE,"samplerCube"}, {TK_PRECISION_LOW,"lowp"}, {TK_PRECISION_MID,"mediump"}, {TK_PRECISION_HIGH,"highp"}, {TK_CF_IF,"if"}, {TK_CF_ELSE,"else"}, {TK_CF_FOR,"for"}, {TK_CF_WHILE,"while"}, {TK_CF_DO,"do"}, {TK_CF_SWITCH,"switch"}, {TK_CF_CASE,"case"}, {TK_CF_BREAK,"break"}, {TK_CF_CONTINUE,"continue"}, {TK_CF_RETURN,"return"}, {TK_UNIFORM,"uniform"}, {TK_VARYING,"varying"}, {TK_RENDER_MODE,"render_mode"}, {TK_HINT_WHITE_TEXTURE,"hint_white"}, {TK_HINT_BLACK_TEXTURE,"hint_black"}, {TK_HINT_NORMAL_TEXTURE,"hint_normal"}, {TK_HINT_ANISO_TEXTURE,"hint_aniso"}, {TK_HINT_ALBEDO_TEXTURE,"hint_albedo"}, {TK_HINT_BLACK_ALBEDO_TEXTURE,"hint_black_albedo"}, {TK_HINT_COLOR,"hint_color"}, {TK_HINT_RANGE,"hint_range"}, {TK_ERROR,NULL} }; ShaderLanguage::Token ShaderLanguage::_get_token() { #define GETCHAR(m_idx) (((char_idx+m_idx)<code.length())?code[char_idx+m_idx]:CharType(0)) while(true) { char_idx++; switch(GETCHAR(-1)) { case 0: return _make_token(TK_EOF); case 0xFFFF: return _make_token(TK_CURSOR); //for completion case '\t': case '\r': case ' ': continue; case '\n': tk_line++; continue; case '/': { switch(GETCHAR(0)) { case '*': { // block comment char_idx++; while(true) { if (GETCHAR(0)==0) { return _make_token(TK_EOF); } if (GETCHAR(0)=='*' && GETCHAR(1)=='/') { char_idx+=2; break; } if (GETCHAR(0)=='\n') { tk_line++; } char_idx++; } } break; case '/': { // line comment skip while(true) { if (GETCHAR(0)=='\n') { char_idx++; break; } if (GETCHAR(0)==0) { return _make_token(TK_EOF); } char_idx++; } } break; case '=': { // diveq char_idx++; return _make_token(TK_OP_ASSIGN_DIV); } break; default: return _make_token(TK_OP_DIV); } continue; //a comment, continue to next token } break; case '=': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_EQUAL); } return _make_token(TK_OP_ASSIGN); } break; case '<': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_LESS_EQUAL); } else if (GETCHAR(0)=='<') { char_idx++; if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_ASSIGN_SHIFT_LEFT); } return _make_token(TK_OP_SHIFT_LEFT); } return _make_token(TK_OP_LESS); } break; case '>': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_GREATER_EQUAL); } else if (GETCHAR(0)=='<') { char_idx++; if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_ASSIGN_SHIFT_RIGHT); } return _make_token(TK_OP_SHIFT_RIGHT); } return _make_token(TK_OP_GREATER); } break; case '!': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_NOT_EQUAL); } return _make_token(TK_OP_NOT); } break; //case '"' //string - no strings in shader //case '\'' //string - no strings in shader case '{': return _make_token(TK_CURLY_BRACKET_OPEN); case '}': return _make_token(TK_CURLY_BRACKET_CLOSE); case '[': return _make_token(TK_BRACKET_OPEN); case ']': return _make_token(TK_BRACKET_CLOSE); case '(': return _make_token(TK_PARENTHESIS_OPEN); case ')': return _make_token(TK_PARENTHESIS_CLOSE); case ',': return _make_token(TK_COMMA); case ';': return _make_token(TK_SEMICOLON); case '?': return _make_token(TK_QUESTION); case ':': return _make_token(TK_COLON); case '^': return _make_token(TK_OP_BIT_XOR); case '~': return _make_token(TK_OP_BIT_INVERT); case '&': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_ASSIGN_BIT_AND); } else if (GETCHAR(0)=='&') { char_idx++; return _make_token(TK_OP_AND); } return _make_token(TK_OP_BIT_AND); } break; case '|': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_ASSIGN_BIT_OR); } else if (GETCHAR(0)=='|') { char_idx++; return _make_token(TK_OP_OR); } return _make_token(TK_OP_BIT_OR); } break; case '*': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_ASSIGN_MUL); } return _make_token(TK_OP_MUL); } break; case '+': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_ASSIGN_ADD); } else if (GETCHAR(0)=='+') { char_idx++; return _make_token(TK_OP_INCREMENT); } return _make_token(TK_OP_ADD); } break; case '-': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_ASSIGN_SUB); }else if (GETCHAR(0)=='-') { char_idx++; return _make_token(TK_OP_DECREMENT); } return _make_token(TK_OP_SUB); } break; case '%': { if (GETCHAR(0)=='=') { char_idx++; return _make_token(TK_OP_ASSIGN_MOD); } return _make_token(TK_OP_MOD); } break; default: { char_idx--; //go back one, since we have no idea what this is if (_is_number(GETCHAR(0)) || (GETCHAR(0)=='.' && _is_number(GETCHAR(1)))) { // parse number bool period_found=false; bool exponent_found=false; bool hexa_found=false; bool sign_found=false; bool minus_exponent_found=false; String str; int i=0; while(true) { if (GETCHAR(i)=='.') { if (period_found || exponent_found) return _make_token(TK_ERROR,"Invalid numeric constant"); period_found=true; } else if (GETCHAR(i)=='x') { if (hexa_found || str.length()!=1 || str[0]!='0') return _make_token(TK_ERROR,"Invalid numeric constant"); hexa_found=true; } else if (GETCHAR(i)=='e') { if (hexa_found || exponent_found) return _make_token(TK_ERROR,"Invalid numeric constant"); exponent_found=true; } else if (_is_number(GETCHAR(i))) { //all ok } else if (hexa_found && _is_hex(GETCHAR(i))) { } else if ((GETCHAR(i)=='-' || GETCHAR(i)=='+') && exponent_found) { if (sign_found) return _make_token(TK_ERROR,"Invalid numeric constant"); sign_found=true; if (GETCHAR(i)=='-') minus_exponent_found=true; } else break; str+=CharType(GETCHAR(i)); i++; } if (!_is_number(str[str.length()-1])) return _make_token(TK_ERROR,"Invalid numeric constant"); char_idx+=str.length(); Token tk; if (period_found || minus_exponent_found) tk.type=TK_REAL_CONSTANT; else tk.type=TK_INT_CONSTANT; if (!str.is_valid_float()) { return _make_token(TK_ERROR,"Invalid numeric constant"); } tk.constant=str.to_double(); tk.line=tk_line; return tk; } if (GETCHAR(0)=='.') { //parse period char_idx++; return _make_token(TK_PERIOD); } if (_is_text_char(GETCHAR(0))) { // parse identifier String str; while(_is_text_char(GETCHAR(0))) { str+=CharType(GETCHAR(0)); char_idx++; } //see if keyword //should be converted to a static map int idx=0; while(keyword_list[idx].text) { if (str==keyword_list[idx].text) { return _make_token(keyword_list[idx].token); } idx++; } return _make_token(TK_IDENTIFIER,str); } if (GETCHAR(0)>32) return _make_token(TK_ERROR,"Tokenizer: Unknown character #"+itos(GETCHAR(0))+": '"+String::chr(GETCHAR(0))+"'"); else return _make_token(TK_ERROR,"Tokenizer: Unknown character #"+itos(GETCHAR(0))); } break; } } ERR_PRINT("BUG"); return Token(); } String ShaderLanguage::token_debug(const String& p_code) { clear(); code=p_code; String output; Token tk = _get_token(); while(tk.type!=TK_EOF && tk.type!=TK_ERROR) { output+=itos(tk_line)+": "+get_token_text(tk)+"\n"; tk = _get_token(); } return output; } bool ShaderLanguage::is_token_datatype(TokenType p_type) { return ( p_type==TK_TYPE_VOID || p_type==TK_TYPE_BOOL || p_type==TK_TYPE_BVEC2 || p_type==TK_TYPE_BVEC3 || p_type==TK_TYPE_BVEC4 || p_type==TK_TYPE_INT || p_type==TK_TYPE_IVEC2 || p_type==TK_TYPE_IVEC3 || p_type==TK_TYPE_IVEC4 || p_type==TK_TYPE_UINT || p_type==TK_TYPE_UVEC2 || p_type==TK_TYPE_UVEC3 || p_type==TK_TYPE_UVEC4 || p_type==TK_TYPE_FLOAT || p_type==TK_TYPE_VEC2 || p_type==TK_TYPE_VEC3 || p_type==TK_TYPE_VEC4 || p_type==TK_TYPE_MAT2 || p_type==TK_TYPE_MAT3 || p_type==TK_TYPE_MAT4 || p_type==TK_TYPE_SAMPLER2D || p_type==TK_TYPE_ISAMPLER2D || p_type==TK_TYPE_USAMPLER2D || p_type==TK_TYPE_SAMPLERCUBE ); } ShaderLanguage::DataType ShaderLanguage::get_token_datatype(TokenType p_type) { return DataType(p_type-TK_TYPE_VOID); } bool ShaderLanguage::is_token_precision(TokenType p_type) { return ( p_type==TK_PRECISION_LOW || p_type==TK_PRECISION_MID || p_type==TK_PRECISION_HIGH ); } ShaderLanguage::DataPrecision ShaderLanguage::get_token_precision(TokenType p_type) { if (p_type==TK_PRECISION_LOW) return PRECISION_LOWP; else if (p_type==TK_PRECISION_HIGH) return PRECISION_HIGHP; else return PRECISION_MEDIUMP; } String ShaderLanguage::get_datatype_name(DataType p_type) { switch(p_type) { case TYPE_VOID: return "void"; case TYPE_BOOL: return "bool"; case TYPE_BVEC2: return "bvec2"; case TYPE_BVEC3: return "bvec3"; case TYPE_BVEC4: return "bvec4"; case TYPE_INT: return "int"; case TYPE_IVEC2: return "ivec2"; case TYPE_IVEC3: return "ivec3"; case TYPE_IVEC4: return "ivec4"; case TYPE_UINT: return "uint"; case TYPE_UVEC2: return "uvec2"; case TYPE_UVEC3: return "uvec3"; case TYPE_UVEC4: return "uvec4"; case TYPE_FLOAT: return "float"; case TYPE_VEC2: return "vec2"; case TYPE_VEC3: return "vec3"; case TYPE_VEC4: return "vec4"; case TYPE_MAT2: return "mat2"; case TYPE_MAT3: return "mat3"; case TYPE_MAT4: return "mat4"; case TYPE_SAMPLER2D: return "sampler2D"; case TYPE_ISAMPLER2D: return "isampler2D"; case TYPE_USAMPLER2D: return "usampler2D"; case TYPE_SAMPLERCUBE: return "samplerCube"; } return ""; } bool ShaderLanguage::is_token_nonvoid_datatype(TokenType p_type) { return is_token_datatype(p_type) && p_type!=TK_TYPE_VOID; } void ShaderLanguage::clear() { current_function=StringName(); completion_type=COMPLETION_NONE; completion_block=NULL; completion_function=StringName(); error_line=0; tk_line=1; char_idx=0; error_set=false; error_str=""; while(nodes) { Node *n = nodes; nodes=nodes->next; memdelete(n); } } bool ShaderLanguage::_find_identifier(const BlockNode* p_block,const Map<StringName, DataType> &p_builtin_types,const StringName& p_identifier, DataType *r_data_type, IdentifierType *r_type) { if (p_builtin_types.has(p_identifier)) { if (r_data_type) { *r_data_type=p_builtin_types[p_identifier]; } if (r_type) { *r_type=IDENTIFIER_BUILTIN_VAR; } return true; } FunctionNode *function=NULL; while(p_block) { if (p_block->variables.has(p_identifier)) { if (r_data_type) { *r_data_type=p_block->variables[p_identifier].type; } if (r_type) { *r_type=IDENTIFIER_LOCAL_VAR; } return true; } if (p_block->parent_function) { function=p_block->parent_function; break; } else { ERR_FAIL_COND_V(!p_block->parent_block,false); p_block=p_block->parent_block; } } if (function) { for(int i=0;i<function->arguments.size();i++) { if (function->arguments[i].name==p_identifier) { if (r_data_type) { *r_data_type=function->arguments[i].type; } if (r_type) { *r_type=IDENTIFIER_FUNCTION_ARGUMENT; } return true; } } } if (shader->varyings.has(p_identifier)) { if (r_data_type) { *r_data_type=shader->varyings[p_identifier].type; } if (r_type) { *r_type=IDENTIFIER_VARYING; } return true; } if (shader->uniforms.has(p_identifier)) { if (r_data_type) { *r_data_type=shader->uniforms[p_identifier].type; } if (r_type) { *r_type=IDENTIFIER_UNIFORM; } return true; } for(int i=0;i<shader->functions.size();i++) { if (!shader->functions[i].callable) continue; if (shader->functions[i].name==p_identifier) { if (r_data_type) { *r_data_type=shader->functions[i].function->return_type; } if (r_type) { *r_type=IDENTIFIER_FUNCTION; } } } return false; } bool ShaderLanguage::_validate_operator(OperatorNode *p_op,DataType *r_ret_type) { bool valid=false; DataType ret_type; switch(p_op->op) { case OP_EQUAL: case OP_NOT_EQUAL: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); valid=na==nb; ret_type=TYPE_BOOL; } break; case OP_LESS: case OP_LESS_EQUAL: case OP_GREATER: case OP_GREATER_EQUAL: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); valid = na==nb && (na==TYPE_UINT || na==TYPE_INT || na==TYPE_FLOAT); ret_type=TYPE_BOOL; } break; case OP_AND: case OP_OR: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); valid = na==nb && na==TYPE_BOOL; ret_type=TYPE_BOOL; } break; case OP_NOT: { DataType na = p_op->arguments[0]->get_datatype(); valid = na==TYPE_BOOL; ret_type=TYPE_BOOL; } break; case OP_INCREMENT: case OP_DECREMENT: case OP_POST_INCREMENT: case OP_POST_DECREMENT: case OP_NEGATE: { DataType na = p_op->arguments[0]->get_datatype(); valid = na>TYPE_BOOL && na<TYPE_MAT2; ret_type=na; } break; case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); if (na>nb) { //make things easier; SWAP(na,nb); } if (na==nb) { valid = (na>TYPE_BOOL && na<TYPE_MAT2) || (p_op->op==OP_MUL && na>=TYPE_MAT2 && na<=TYPE_MAT4); ret_type=na; } else if (na==TYPE_INT && nb==TYPE_IVEC2) { valid=true; ret_type=TYPE_IVEC2; } else if (na==TYPE_INT && nb==TYPE_IVEC3) { valid=true; ret_type=TYPE_IVEC3; } else if (na==TYPE_INT && nb==TYPE_IVEC4) { valid=true; ret_type=TYPE_IVEC4; } else if (na==TYPE_UINT && nb==TYPE_UVEC2) { valid=true; ret_type=TYPE_UVEC2; } else if (na==TYPE_UINT && nb==TYPE_UVEC3) { valid=true; ret_type=TYPE_UVEC3; } else if (na==TYPE_UINT && nb==TYPE_UVEC4) { valid=true; ret_type=TYPE_UVEC4; } else if (na==TYPE_FLOAT && nb==TYPE_VEC2) { valid=true; ret_type=TYPE_VEC2; } else if (na==TYPE_FLOAT && nb==TYPE_VEC3) { valid=true; ret_type=TYPE_VEC3; } else if (na==TYPE_FLOAT && nb==TYPE_VEC4) { valid=true; ret_type=TYPE_VEC4; } else if (p_op->op==OP_MUL && na==TYPE_VEC2 && nb==TYPE_MAT2) { valid=true; ret_type=TYPE_MAT2; } else if (p_op->op==OP_MUL && na==TYPE_VEC3 && nb==TYPE_MAT3) { valid=true; ret_type=TYPE_MAT3; } else if (p_op->op==OP_MUL && na==TYPE_VEC4 && nb==TYPE_MAT4) { valid=true; ret_type=TYPE_MAT4; } } break; case OP_ASSIGN_MOD: case OP_MOD: { /* * The operator modulus (%) operates on signed or unsigned integers or integer vectors. The operand * types must both be signed or both be unsigned. The operands cannot be vectors of differing size. If * one operand is a scalar and the other vector, then the scalar is applied component-wise to the vector, * resulting in the same type as the vector. If both are vectors of the same size, the result is computed * component-wise. */ DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); if (na==TYPE_INT && nb==TYPE_INT) { valid=true; ret_type=TYPE_INT; } else if (na==TYPE_IVEC2 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC2; } else if (na==TYPE_IVEC3 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC3; } else if (na==TYPE_IVEC4 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC4; } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) { valid=true; ret_type=TYPE_IVEC2; } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) { valid=true; ret_type=TYPE_IVEC3; } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) { valid=true; ret_type=TYPE_IVEC4; ///// } else if (na==TYPE_UINT && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UINT; } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC2; } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC3; } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC4; } else if (na==TYPE_UVEC2 && nb==TYPE_UVEC2) { valid=true; ret_type=TYPE_UVEC2; } else if (na==TYPE_UVEC3 && nb==TYPE_UVEC3) { valid=true; ret_type=TYPE_UVEC3; } else if (na==TYPE_UVEC4 && nb==TYPE_UVEC4) { valid=true; ret_type=TYPE_UVEC4; } } break; case OP_ASSIGN_SHIFT_LEFT: case OP_ASSIGN_SHIFT_RIGHT: case OP_SHIFT_LEFT: case OP_SHIFT_RIGHT: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); if (na>=TYPE_UINT && na<=TYPE_UVEC4) { na=DataType(na-4); } if (nb>=TYPE_UINT && nb<=TYPE_UVEC4) { nb=DataType(nb-4); } if (na==TYPE_INT && nb==TYPE_INT) { valid=true; ret_type=TYPE_INT; } else if (na==TYPE_IVEC2 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC2; } else if (na==TYPE_IVEC3 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC3; } else if (na==TYPE_IVEC4 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC4; } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) { valid=true; ret_type=TYPE_IVEC2; } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) { valid=true; ret_type=TYPE_IVEC3; } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) { valid=true; ret_type=TYPE_IVEC4; } } break; case OP_ASSIGN: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); valid=na==nb; ret_type=na; } break; case OP_ASSIGN_ADD: case OP_ASSIGN_SUB: case OP_ASSIGN_MUL: case OP_ASSIGN_DIV: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); if (na==nb) { valid = (na>TYPE_BOOL && na<TYPE_MAT2) || (p_op->op==OP_ASSIGN_MUL && na>=TYPE_MAT2 && na<=TYPE_MAT4); ret_type=na; } else if (na==TYPE_IVEC2 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC2; } else if (na==TYPE_IVEC3 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC3; } else if (na==TYPE_IVEC4 && nb==TYPE_INT ) { valid=true; ret_type=TYPE_IVEC4; } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC2; } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC3; } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC4; } else if (na==TYPE_VEC2 && nb==TYPE_FLOAT ) { valid=true; ret_type=TYPE_VEC2; } else if (na==TYPE_VEC3 && nb==TYPE_FLOAT) { valid=true; ret_type=TYPE_VEC3; } else if (na==TYPE_VEC4 && nb==TYPE_FLOAT) { valid=true; ret_type=TYPE_VEC4; } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT2 && nb==TYPE_VEC2) { valid=true; ret_type=TYPE_MAT2; } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT3 && nb==TYPE_VEC3) { valid=true; ret_type=TYPE_MAT3; } else if (p_op->op==OP_ASSIGN_MUL && na==TYPE_MAT4 && nb==TYPE_VEC4) { valid=true; ret_type=TYPE_MAT4; } } break; case OP_ASSIGN_BIT_AND: case OP_ASSIGN_BIT_OR: case OP_ASSIGN_BIT_XOR: case OP_BIT_AND: case OP_BIT_OR: case OP_BIT_XOR: { /* * The bitwise operators and (&), exclusive-or (^), and inclusive-or (|). The operands must be of type * signed or unsigned integers or integer vectors. The operands cannot be vectors of differing size. If * one operand is a scalar and the other a vector, the scalar is applied component-wise to the vector, * resulting in the same type as the vector. The fundamental types of the operands (signed or unsigned) * must match. */ DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); if (na>nb && p_op->op>=OP_BIT_AND) { //can swap for non assign SWAP(na,nb); } if (na==TYPE_INT && nb==TYPE_INT) { valid=true; ret_type=TYPE_INT; } else if (na==TYPE_IVEC2 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC2; } else if (na==TYPE_IVEC3 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC3; } else if (na==TYPE_IVEC4 && nb==TYPE_INT) { valid=true; ret_type=TYPE_IVEC4; } else if (na==TYPE_IVEC2 && nb==TYPE_IVEC2) { valid=true; ret_type=TYPE_IVEC2; } else if (na==TYPE_IVEC3 && nb==TYPE_IVEC3) { valid=true; ret_type=TYPE_IVEC3; } else if (na==TYPE_IVEC4 && nb==TYPE_IVEC4) { valid=true; ret_type=TYPE_IVEC4; ///// } else if (na==TYPE_UINT && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UINT; } else if (na==TYPE_UVEC2 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC2; } else if (na==TYPE_UVEC3 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC3; } else if (na==TYPE_UVEC4 && nb==TYPE_UINT) { valid=true; ret_type=TYPE_UVEC4; } else if (na==TYPE_UVEC2 && nb==TYPE_UVEC2) { valid=true; ret_type=TYPE_UVEC2; } else if (na==TYPE_UVEC3 && nb==TYPE_UVEC3) { valid=true; ret_type=TYPE_UVEC3; } else if (na==TYPE_UVEC4 && nb==TYPE_UVEC4) { valid=true; ret_type=TYPE_UVEC4; } } break; case OP_BIT_INVERT: { //unaries DataType na = p_op->arguments[0]->get_datatype(); valid = na>=TYPE_INT && na<TYPE_FLOAT; ret_type=na; } break; case OP_SELECT_IF: { DataType na = p_op->arguments[0]->get_datatype(); DataType nb = p_op->arguments[1]->get_datatype(); DataType nc = p_op->arguments[2]->get_datatype(); valid = na==TYPE_BOOL && (nb==nc); ret_type=nb; } break; default: { ERR_FAIL_V(false); } } if (r_ret_type) *r_ret_type=ret_type; return valid; } const ShaderLanguage::BuiltinFuncDef ShaderLanguage::builtin_func_defs[]={ //constructors {"bool",TYPE_BOOL,{TYPE_BOOL,TYPE_VOID}}, {"bvec2",TYPE_BVEC2,{TYPE_BOOL,TYPE_VOID}}, {"bvec2",TYPE_BVEC2,{TYPE_BOOL,TYPE_BOOL,TYPE_VOID}}, {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_VOID}}, {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}}, {"bvec3",TYPE_BVEC3,{TYPE_BVEC2,TYPE_BOOL,TYPE_VOID}}, {"bvec3",TYPE_BVEC3,{TYPE_BOOL,TYPE_BVEC2,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BVEC2,TYPE_BOOL,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BVEC2,TYPE_BOOL,TYPE_BOOL,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BOOL,TYPE_BVEC2,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BOOL,TYPE_BVEC3,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BVEC3,TYPE_BOOL,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}}, {"float",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"vec2",TYPE_VEC2,{TYPE_FLOAT,TYPE_VOID}}, {"vec2",TYPE_VEC2,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_VOID}}, {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"vec3",TYPE_VEC3,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, {"vec3",TYPE_VEC3,{TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_VEC2,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"int",TYPE_INT,{TYPE_INT,TYPE_VOID}}, {"ivec2",TYPE_IVEC2,{TYPE_INT,TYPE_VOID}}, {"ivec2",TYPE_IVEC2,{TYPE_INT,TYPE_INT,TYPE_VOID}}, {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_VOID}}, {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}}, {"ivec3",TYPE_IVEC3,{TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, {"ivec3",TYPE_IVEC3,{TYPE_INT,TYPE_IVEC2,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_IVEC2,TYPE_INT,TYPE_INT,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_INT,TYPE_IVEC2,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_INT,TYPE_IVEC3,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_IVEC3,TYPE_INT,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"uint",TYPE_UINT,{TYPE_UINT,TYPE_VOID}}, {"uvec2",TYPE_UVEC2,{TYPE_UINT,TYPE_VOID}}, {"uvec2",TYPE_UVEC2,{TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_VOID}}, {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"uvec3",TYPE_UVEC3,{TYPE_UVEC2,TYPE_UINT,TYPE_VOID}}, {"uvec3",TYPE_UVEC3,{TYPE_UINT,TYPE_UVEC2,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UVEC2,TYPE_UINT,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UVEC2,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UINT,TYPE_UVEC2,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UINT,TYPE_UVEC3,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UVEC3,TYPE_UINT,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"mat2",TYPE_MAT2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"mat3",TYPE_MAT3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"mat4",TYPE_MAT4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"mat2",TYPE_MAT2,{TYPE_FLOAT,TYPE_VOID}}, {"mat3",TYPE_MAT3,{TYPE_FLOAT,TYPE_VOID}}, {"mat4",TYPE_MAT4,{TYPE_FLOAT,TYPE_VOID}}, //conversion scalars {"int",TYPE_INT,{TYPE_BOOL,TYPE_VOID}}, {"int",TYPE_INT,{TYPE_INT,TYPE_VOID}}, {"int",TYPE_INT,{TYPE_UINT,TYPE_VOID}}, {"int",TYPE_INT,{TYPE_FLOAT,TYPE_VOID}}, {"float",TYPE_FLOAT,{TYPE_BOOL,TYPE_VOID}}, {"float",TYPE_FLOAT,{TYPE_INT,TYPE_VOID}}, {"float",TYPE_FLOAT,{TYPE_UINT,TYPE_VOID}}, {"float",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"uint",TYPE_UINT,{TYPE_BOOL,TYPE_VOID}}, {"uint",TYPE_UINT,{TYPE_INT,TYPE_VOID}}, {"uint",TYPE_UINT,{TYPE_UINT,TYPE_VOID}}, {"uint",TYPE_UINT,{TYPE_FLOAT,TYPE_VOID}}, {"bool",TYPE_BOOL,{TYPE_BOOL,TYPE_VOID}}, {"bool",TYPE_BOOL,{TYPE_INT,TYPE_VOID}}, {"bool",TYPE_BOOL,{TYPE_UINT,TYPE_VOID}}, {"bool",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}}, //conversion vectors {"ivec2",TYPE_IVEC2,{TYPE_BVEC2,TYPE_VOID}}, {"ivec2",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}}, {"ivec2",TYPE_IVEC2,{TYPE_UVEC2,TYPE_VOID}}, {"ivec2",TYPE_IVEC2,{TYPE_VEC2,TYPE_VOID}}, {"vec2",TYPE_VEC2,{TYPE_BVEC2,TYPE_VOID}}, {"vec2",TYPE_VEC2,{TYPE_IVEC2,TYPE_VOID}}, {"vec2",TYPE_VEC2,{TYPE_UVEC2,TYPE_VOID}}, {"vec2",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"uvec2",TYPE_UVEC2,{TYPE_BVEC2,TYPE_VOID}}, {"uvec2",TYPE_UVEC2,{TYPE_IVEC2,TYPE_VOID}}, {"uvec2",TYPE_UVEC2,{TYPE_UVEC2,TYPE_VOID}}, {"uvec2",TYPE_UVEC2,{TYPE_VEC2,TYPE_VOID}}, {"bvec2",TYPE_BVEC2,{TYPE_BVEC2,TYPE_VOID}}, {"bvec2",TYPE_BVEC2,{TYPE_IVEC2,TYPE_VOID}}, {"bvec2",TYPE_BVEC2,{TYPE_UVEC2,TYPE_VOID}}, {"bvec2",TYPE_BVEC2,{TYPE_VEC2,TYPE_VOID}}, {"ivec3",TYPE_IVEC3,{TYPE_BVEC3,TYPE_VOID}}, {"ivec3",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}}, {"ivec3",TYPE_IVEC3,{TYPE_UVEC3,TYPE_VOID}}, {"ivec3",TYPE_IVEC3,{TYPE_VEC3,TYPE_VOID}}, {"vec3",TYPE_VEC3,{TYPE_BVEC3,TYPE_VOID}}, {"vec3",TYPE_VEC3,{TYPE_IVEC3,TYPE_VOID}}, {"vec3",TYPE_VEC3,{TYPE_UVEC3,TYPE_VOID}}, {"vec3",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"uvec3",TYPE_UVEC3,{TYPE_BVEC3,TYPE_VOID}}, {"uvec3",TYPE_UVEC3,{TYPE_IVEC3,TYPE_VOID}}, {"uvec3",TYPE_UVEC3,{TYPE_UVEC3,TYPE_VOID}}, {"uvec3",TYPE_UVEC3,{TYPE_VEC3,TYPE_VOID}}, {"bvec3",TYPE_BVEC3,{TYPE_BVEC3,TYPE_VOID}}, {"bvec3",TYPE_BVEC3,{TYPE_IVEC3,TYPE_VOID}}, {"bvec3",TYPE_BVEC3,{TYPE_UVEC3,TYPE_VOID}}, {"bvec3",TYPE_BVEC3,{TYPE_VEC3,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_BVEC4,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_UVEC4,TYPE_VOID}}, {"ivec4",TYPE_IVEC4,{TYPE_VEC4,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_BVEC4,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_IVEC4,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_UVEC4,TYPE_VOID}}, {"vec4",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_BVEC4,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_IVEC4,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_UVEC4,TYPE_VOID}}, {"uvec4",TYPE_UVEC4,{TYPE_VEC4,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_BVEC4,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_IVEC4,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_UVEC4,TYPE_VOID}}, {"bvec4",TYPE_BVEC4,{TYPE_VEC4,TYPE_VOID}}, //builtins - trigonometry {"sin",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"cos",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"tan",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"asin",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"acos",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"atan",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"atan2",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"sinh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"cosh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"tanh",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, //builtins - exponential {"pow",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"pow",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, {"pow",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"pow",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"pow",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"pow",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"pow",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"exp",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"exp",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"exp",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"exp",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"log",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"log",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"log",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"log",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"sqrt",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"sqrt",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"sqrt",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"sqrt",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, //builtins - common {"abs",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"abs",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"abs",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"abs",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"abs",TYPE_INT,{TYPE_INT,TYPE_VOID}}, {"abs",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}}, {"abs",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}}, {"abs",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}}, {"abs",TYPE_UINT,{TYPE_UINT,TYPE_VOID}}, {"abs",TYPE_UVEC2,{TYPE_UVEC2,TYPE_VOID}}, {"abs",TYPE_UVEC3,{TYPE_UVEC3,TYPE_VOID}}, {"abs",TYPE_UVEC4,{TYPE_UVEC4,TYPE_VOID}}, {"sign",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"sign",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"sign",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"sign",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"sign",TYPE_INT,{TYPE_INT,TYPE_VOID}}, {"sign",TYPE_IVEC2,{TYPE_IVEC2,TYPE_VOID}}, {"sign",TYPE_IVEC3,{TYPE_IVEC3,TYPE_VOID}}, {"sign",TYPE_IVEC4,{TYPE_IVEC4,TYPE_VOID}}, {"floor",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"floor",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"floor",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"floor",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"trunc",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"trunc",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"trunc",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"trunc",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"round",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"round",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"round",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"round",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"ceil",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"ceil",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"ceil",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"ceil",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"fract",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"fract",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"fract",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"fract",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"mod",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"mod",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"mod",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, {"mod",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"mod",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"mod",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"mod",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"modf",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"modf",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"modf",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"modf",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"min",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"min",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"min",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"min",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"min",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_VOID}}, {"min",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"min",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"min",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"min",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"min",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"min",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"min",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"max",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"max",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"max",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"max",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"max",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_VOID}}, {"max",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"max",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"max",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"max",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"max",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"max",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"max",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"clamp",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"clamp",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"clamp",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"clamp",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"clamp",TYPE_VEC2,{TYPE_VEC2,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"clamp",TYPE_VEC3,{TYPE_VEC3,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"clamp",TYPE_VEC4,{TYPE_VEC4,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"clamp",TYPE_INT,{TYPE_INT,TYPE_INT,TYPE_INT,TYPE_VOID}}, {"clamp",TYPE_IVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"clamp",TYPE_IVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"clamp",TYPE_IVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"clamp",TYPE_IVEC2,{TYPE_IVEC2,TYPE_INT,TYPE_INT,TYPE_VOID}}, {"clamp",TYPE_IVEC3,{TYPE_IVEC3,TYPE_INT,TYPE_INT,TYPE_VOID}}, {"clamp",TYPE_IVEC4,{TYPE_IVEC4,TYPE_INT,TYPE_INT,TYPE_VOID}}, {"clamp",TYPE_UINT,{TYPE_UINT,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"clamp",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"clamp",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"clamp",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"clamp",TYPE_UVEC2,{TYPE_UVEC2,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"clamp",TYPE_UVEC3,{TYPE_UVEC3,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"clamp",TYPE_UVEC4,{TYPE_UVEC4,TYPE_UINT,TYPE_UINT,TYPE_VOID}}, {"mix",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"mix",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_BOOL,TYPE_VOID}}, {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_BOOL,TYPE_VOID}}, {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_BVEC2,TYPE_VOID}}, {"mix",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_BOOL,TYPE_VOID}}, {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_BVEC3,TYPE_VOID}}, {"mix",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_BOOL,TYPE_VOID}}, {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_BVEC3,TYPE_VOID}}, {"mix",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"step",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"step",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"step",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"step",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"step",TYPE_VEC2,{TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}}, {"step",TYPE_VEC3,{TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}}, {"step",TYPE_VEC4,{TYPE_FLOAT,TYPE_VEC4,TYPE_VOID}}, {"smoothstep",TYPE_FLOAT,{TYPE_FLOAT,TYPE_FLOAT,TYPE_FLOAT,TYPE_VOID}}, {"smoothstep",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"smoothstep",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"smoothstep",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"smoothstep",TYPE_VEC2,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC2,TYPE_VOID}}, {"smoothstep",TYPE_VEC3,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC3,TYPE_VOID}}, {"smoothstep",TYPE_VEC4,{TYPE_FLOAT,TYPE_FLOAT,TYPE_VEC4,TYPE_VOID}}, {"isnan",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}}, {"isnan",TYPE_BOOL,{TYPE_VEC2,TYPE_VOID}}, {"isnan",TYPE_BOOL,{TYPE_VEC3,TYPE_VOID}}, {"isnan",TYPE_BOOL,{TYPE_VEC4,TYPE_VOID}}, {"isinf",TYPE_BOOL,{TYPE_FLOAT,TYPE_VOID}}, {"isinf",TYPE_BOOL,{TYPE_VEC2,TYPE_VOID}}, {"isinf",TYPE_BOOL,{TYPE_VEC3,TYPE_VOID}}, {"isinf",TYPE_BOOL,{TYPE_VEC4,TYPE_VOID}}, {"floatBitsToInt",TYPE_INT,{TYPE_FLOAT,TYPE_VOID}}, {"floatBitsToInt",TYPE_IVEC2,{TYPE_VEC2,TYPE_VOID}}, {"floatBitsToInt",TYPE_IVEC3,{TYPE_VEC3,TYPE_VOID}}, {"floatBitsToInt",TYPE_IVEC4,{TYPE_VEC4,TYPE_VOID}}, {"floatBitsToUInt",TYPE_UINT,{TYPE_FLOAT,TYPE_VOID}}, {"floatBitsToUInt",TYPE_UVEC2,{TYPE_VEC2,TYPE_VOID}}, {"floatBitsToUInt",TYPE_UVEC3,{TYPE_VEC3,TYPE_VOID}}, {"floatBitsToUInt",TYPE_UVEC4,{TYPE_VEC4,TYPE_VOID}}, {"intBitsToFloat",TYPE_FLOAT,{TYPE_INT,TYPE_VOID}}, {"intBitsToFloat",TYPE_VEC2,{TYPE_IVEC2,TYPE_VOID}}, {"intBitsToFloat",TYPE_VEC3,{TYPE_IVEC3,TYPE_VOID}}, {"intBitsToFloat",TYPE_VEC4,{TYPE_IVEC4,TYPE_VOID}}, {"uintBitsToFloat",TYPE_FLOAT,{TYPE_UINT,TYPE_VOID}}, {"uintBitsToFloat",TYPE_VEC2,{TYPE_UVEC2,TYPE_VOID}}, {"uintBitsToFloat",TYPE_VEC3,{TYPE_UVEC3,TYPE_VOID}}, {"uintBitsToFloat",TYPE_VEC4,{TYPE_UVEC4,TYPE_VOID}}, //builtins - geometric {"length",TYPE_FLOAT,{TYPE_VEC2,TYPE_VOID}}, {"length",TYPE_FLOAT,{TYPE_VEC3,TYPE_VOID}}, {"length",TYPE_FLOAT,{TYPE_VEC4,TYPE_VOID}}, {"distance",TYPE_FLOAT,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"distance",TYPE_FLOAT,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"distance",TYPE_FLOAT,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"dot",TYPE_FLOAT,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"dot",TYPE_FLOAT,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"dot",TYPE_FLOAT,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"cross",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"normalize",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"normalize",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"normalize",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"reflect",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"refract",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"facefordward",TYPE_VEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"facefordward",TYPE_VEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"facefordward",TYPE_VEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"matrixCompMult",TYPE_MAT2,{TYPE_MAT2,TYPE_MAT2,TYPE_VOID}}, {"matrixCompMult",TYPE_MAT3,{TYPE_MAT3,TYPE_MAT3,TYPE_VOID}}, {"matrixCompMult",TYPE_MAT4,{TYPE_MAT4,TYPE_MAT4,TYPE_VOID}}, {"outerProduct",TYPE_MAT2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"outerProduct",TYPE_MAT3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"outerProduct",TYPE_MAT4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"transpose",TYPE_MAT2,{TYPE_MAT2,TYPE_VOID}}, {"transpose",TYPE_MAT3,{TYPE_MAT3,TYPE_VOID}}, {"transpose",TYPE_MAT4,{TYPE_MAT4,TYPE_VOID}}, {"determinant",TYPE_FLOAT,{TYPE_MAT2,TYPE_VOID}}, {"determinant",TYPE_FLOAT,{TYPE_MAT3,TYPE_VOID}}, {"determinant",TYPE_FLOAT,{TYPE_MAT4,TYPE_VOID}}, {"inverse",TYPE_MAT2,{TYPE_MAT2,TYPE_VOID}}, {"inverse",TYPE_MAT3,{TYPE_MAT3,TYPE_VOID}}, {"inverse",TYPE_MAT4,{TYPE_MAT4,TYPE_VOID}}, {"lessThan",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"lessThan",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"lessThan",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"lessThan",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"lessThan",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"lessThan",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"lessThan",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"lessThan",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"lessThan",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"greaterThan",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"greaterThan",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"greaterThan",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"greaterThan",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"greaterThan",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"greaterThan",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"greaterThan",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"greaterThan",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"greaterThan",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"lessThanEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"greaterThanEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"equal",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"equal",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"equal",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"equal",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"equal",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"equal",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"equal",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"equal",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"equal",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"equal",TYPE_BVEC2,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}}, {"equal",TYPE_BVEC3,{TYPE_BVEC3,TYPE_BVEC3,TYPE_VOID}}, {"equal",TYPE_BVEC4,{TYPE_BVEC4,TYPE_BVEC4,TYPE_VOID}}, {"notEqual",TYPE_BVEC2,{TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"notEqual",TYPE_BVEC3,{TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"notEqual",TYPE_BVEC4,{TYPE_VEC4,TYPE_VEC4,TYPE_VOID}}, {"notEqual",TYPE_BVEC2,{TYPE_IVEC2,TYPE_IVEC2,TYPE_VOID}}, {"notEqual",TYPE_BVEC3,{TYPE_IVEC3,TYPE_IVEC3,TYPE_VOID}}, {"notEqual",TYPE_BVEC4,{TYPE_IVEC4,TYPE_IVEC4,TYPE_VOID}}, {"notEqual",TYPE_BVEC2,{TYPE_UVEC2,TYPE_UVEC2,TYPE_VOID}}, {"notEqual",TYPE_BVEC3,{TYPE_UVEC3,TYPE_UVEC3,TYPE_VOID}}, {"notEqual",TYPE_BVEC4,{TYPE_UVEC4,TYPE_UVEC4,TYPE_VOID}}, {"notEqual",TYPE_BVEC2,{TYPE_BVEC2,TYPE_BVEC2,TYPE_VOID}}, {"notEqual",TYPE_BVEC3,{TYPE_BVEC3,TYPE_BVEC3,TYPE_VOID}}, {"notEqual",TYPE_BVEC4,{TYPE_BVEC4,TYPE_BVEC4,TYPE_VOID}}, {"any",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}}, {"any",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}}, {"any",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}}, {"all",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}}, {"all",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}}, {"all",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}}, {"not",TYPE_BOOL,{TYPE_BVEC2,TYPE_VOID}}, {"not",TYPE_BOOL,{TYPE_BVEC3,TYPE_VOID}}, {"not",TYPE_BOOL,{TYPE_BVEC4,TYPE_VOID}}, //builtins - texture {"textureSize",TYPE_VEC2,{TYPE_SAMPLER2D,TYPE_INT,TYPE_VOID}}, {"textureSize",TYPE_VEC2,{TYPE_ISAMPLER2D,TYPE_INT,TYPE_VOID}}, {"textureSize",TYPE_VEC2,{TYPE_USAMPLER2D,TYPE_INT,TYPE_VOID}}, {"textureSize",TYPE_VEC2,{TYPE_SAMPLERCUBE,TYPE_INT,TYPE_VOID}}, {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_VOID}}, {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_VOID}}, {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, {"texture",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_VOID}}, {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_VOID}}, {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, {"texture",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_VOID}}, {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_VOID}}, {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_FLOAT,TYPE_VOID}}, {"texture",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"texture",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_VOID}}, {"texture",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_VOID}}, {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_VOID}}, {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureProj",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_VOID}}, {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_VOID}}, {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureProj",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_VOID}}, {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_VOID}}, {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureProj",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"textureLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureLod",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"texelFetch",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, {"texelFetch",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, {"texelFetch",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_IVEC2,TYPE_INT,TYPE_VOID}}, {"textureProjLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureProjLod",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"textureProjLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureProjLod",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"textureProjLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC3,TYPE_FLOAT,TYPE_VOID}}, {"textureProjLod",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC4,TYPE_FLOAT,TYPE_VOID}}, {"textureGrad",TYPE_VEC4,{TYPE_SAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"textureGrad",TYPE_IVEC4,{TYPE_ISAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"textureGrad",TYPE_UVEC4,{TYPE_USAMPLER2D,TYPE_VEC2,TYPE_VEC2,TYPE_VEC2,TYPE_VOID}}, {"textureGrad",TYPE_VEC4,{TYPE_SAMPLERCUBE,TYPE_VEC3,TYPE_VEC3,TYPE_VEC3,TYPE_VOID}}, {"textureScreen",TYPE_VEC4,{TYPE_VEC2,TYPE_VOID}}, {"dFdx",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"dFdx",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"dFdx",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"dFdx",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"dFdy",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"dFdy",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"dFdy",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"dFdy",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {"fwidth",TYPE_FLOAT,{TYPE_FLOAT,TYPE_VOID}}, {"fwidth",TYPE_VEC2,{TYPE_VEC2,TYPE_VOID}}, {"fwidth",TYPE_VEC3,{TYPE_VEC3,TYPE_VOID}}, {"fwidth",TYPE_VEC4,{TYPE_VEC4,TYPE_VOID}}, {NULL,TYPE_VOID,{TYPE_VOID}} }; bool ShaderLanguage::_validate_function_call(BlockNode* p_block, OperatorNode *p_func,DataType *r_ret_type) { ERR_FAIL_COND_V(p_func->op!=OP_CALL && p_func->op!=OP_CONSTRUCT,NULL); Vector<DataType> args; ERR_FAIL_COND_V( p_func->arguments[0]->type!=Node::TYPE_VARIABLE, NULL ); StringName name = static_cast<VariableNode*>(p_func->arguments[0])->name.operator String(); bool all_const=true; for(int i=1;i<p_func->arguments.size();i++) { if (p_func->arguments[i]->type!=Node::TYPE_CONSTANT) all_const=false; args.push_back(p_func->arguments[i]->get_datatype()); } int argcount=args.size(); bool failed_builtin=false; if (argcount<=4) { // test builtins int idx=0; while (builtin_func_defs[idx].name) { if (name==builtin_func_defs[idx].name) { failed_builtin=true; bool fail=false; for(int i=0;i<argcount;i++) { if (get_scalar_type(args[i])==args[i] && p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode*>(p_func->arguments[i+1]),builtin_func_defs[idx].args[i])) { //all good } else if (args[i]!=builtin_func_defs[idx].args[i]) { fail=true; break; } } if (!fail && argcount<4 && builtin_func_defs[idx].args[argcount]!=TYPE_VOID) fail=true; //make sure the number of arguments matches if (!fail) { if (r_ret_type) *r_ret_type=builtin_func_defs[idx].rettype; return true; } } idx++; } } if (failed_builtin) { String err ="Invalid arguments for built-in function: "+String(name)+"("; for(int i=0;i<argcount;i++) { if (i>0) err+=","; if (p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && p_func->arguments[i+1]->get_datatype()==TYPE_INT && static_cast<ConstantNode*>(p_func->arguments[i+1])->values[0].sint<0) { err+="-"; } err+=get_datatype_name(args[i]); } err+=")"; _set_error(err); return false; } #if 0 if (found_builtin) { if (p_func->op==OP_CONSTRUCT && all_const) { Vector<float> cdata; for(int i=0;i<argcount;i++) { Variant v = static_cast<ConstantNode*>(p_func->arguments[i+1])->value; switch(v.get_type()) { case Variant::REAL: cdata.push_back(v); break; case Variant::INT: cdata.push_back(v); break; case Variant::VECTOR2: { Vector2 v2=v; cdata.push_back(v2.x); cdata.push_back(v2.y); } break; case Variant::VECTOR3: { Vector3 v3=v; cdata.push_back(v3.x); cdata.push_back(v3.y); cdata.push_back(v3.z);} break; case Variant::PLANE: { Plane v4=v; cdata.push_back(v4.normal.x); cdata.push_back(v4.normal.y); cdata.push_back(v4.normal.z); cdata.push_back(v4.d); } break; default: ERR_FAIL_V(NULL); } } ConstantNode *cn = parser.create_node<ConstantNode>(p_func->parent); Variant data; switch(p_func->return_cache) { case TYPE_FLOAT: data = cdata[0]; break; case TYPE_VEC2: if (cdata.size()==1) data = Vector2(cdata[0],cdata[0]); else data = Vector2(cdata[0],cdata[1]); break; case TYPE_VEC3: if (cdata.size()==1) data = Vector3(cdata[0],cdata[0],cdata[0]); else data = Vector3(cdata[0],cdata[1],cdata[2]); break; case TYPE_VEC4: if (cdata.size()==1) data = Plane(cdata[0],cdata[0],cdata[0],cdata[0]); else data = Plane(cdata[0],cdata[1],cdata[2],cdata[3]); break; } cn->datatype=p_func->return_cache; cn->value=data; return cn; } return p_func; } #endif // try existing functions.. StringName exclude_function; BlockNode *block = p_block; while(block) { if (block->parent_function) { exclude_function=block->parent_function->name; } block=block->parent_block; } if (name==exclude_function) { _set_error("Recursion is not allowed"); return false; } for(int i=0;i<shader->functions.size();i++) { if (name != shader->functions[i].name) continue; if (!shader->functions[i].callable) { _set_error("Function '"+String(name)+" can't be called from source code."); return false; } FunctionNode *pfunc = shader->functions[i].function; if (pfunc->arguments.size()!=args.size()) continue; bool fail=false; for(int i=0;i<args.size();i++) { if (get_scalar_type(args[i])==args[i] && p_func->arguments[i+1]->type==Node::TYPE_CONSTANT && convert_constant(static_cast<ConstantNode*>(p_func->arguments[i+1]),pfunc->arguments[i].type)) { //all good } else if (args[i]!=pfunc->arguments[i].type) { fail=true; break; } } if (!fail) { p_func->return_cache=pfunc->return_type; return true; } } return false; } bool ShaderLanguage::_parse_function_arguments(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types,OperatorNode* p_func,int *r_complete_arg) { TkPos pos = _get_tkpos(); Token tk = _get_token(); if (tk.type==TK_PARENTHESIS_CLOSE) { return true; } _set_tkpos(pos); while(true) { if (r_complete_arg) { pos = _get_tkpos(); tk = _get_token(); if (tk.type==TK_CURSOR) { *r_complete_arg=p_func->arguments.size()-1; } else { _set_tkpos(pos); } } Node *arg= _parse_and_reduce_expression(p_block,p_builtin_types); if (!arg) { return false; } p_func->arguments.push_back(arg); tk = _get_token(); if (tk.type==TK_PARENTHESIS_CLOSE) { return true; } else if (tk.type!=TK_COMMA) { // something is broken _set_error("Expected ',' or ')' after argument"); return false; } } return true; } bool ShaderLanguage::is_token_operator(TokenType p_type) { return (p_type==TK_OP_EQUAL || p_type==TK_OP_NOT_EQUAL || p_type==TK_OP_LESS || p_type==TK_OP_LESS_EQUAL || p_type==TK_OP_GREATER || p_type==TK_OP_GREATER_EQUAL || p_type==TK_OP_AND || p_type==TK_OP_OR || p_type==TK_OP_NOT || p_type==TK_OP_ADD || p_type==TK_OP_SUB || p_type==TK_OP_MUL || p_type==TK_OP_DIV || p_type==TK_OP_MOD || p_type==TK_OP_SHIFT_LEFT || p_type==TK_OP_SHIFT_RIGHT || p_type==TK_OP_ASSIGN || p_type==TK_OP_ASSIGN_ADD || p_type==TK_OP_ASSIGN_SUB || p_type==TK_OP_ASSIGN_MUL || p_type==TK_OP_ASSIGN_DIV || p_type==TK_OP_ASSIGN_MOD || p_type==TK_OP_ASSIGN_SHIFT_LEFT || p_type==TK_OP_ASSIGN_SHIFT_RIGHT || p_type==TK_OP_ASSIGN_BIT_AND || p_type==TK_OP_ASSIGN_BIT_OR || p_type==TK_OP_ASSIGN_BIT_XOR || p_type==TK_OP_BIT_AND || p_type==TK_OP_BIT_OR || p_type==TK_OP_BIT_XOR || p_type==TK_OP_BIT_INVERT || p_type==TK_OP_INCREMENT || p_type==TK_OP_DECREMENT || p_type==TK_QUESTION || p_type==TK_COLON ); } bool ShaderLanguage::convert_constant(ConstantNode* p_constant, DataType p_to_type,ConstantNode::Value *p_value) { if (p_constant->datatype==p_to_type) { if (p_value) { for(int i=0;i<p_constant->values.size();i++) { p_value[i]=p_constant->values[i]; } } return true; } else if (p_constant->datatype==TYPE_INT && p_to_type==TYPE_FLOAT) { if (p_value) { p_value->real=p_constant->values[0].sint; } return true; } else if (p_constant->datatype==TYPE_UINT && p_to_type==TYPE_FLOAT) { if (p_value) { p_value->real=p_constant->values[0].uint; } return true; } else if (p_constant->datatype==TYPE_INT && p_to_type==TYPE_UINT) { if (p_constant->values[0].sint<0) { return false; } if (p_value) { p_value->uint=p_constant->values[0].sint; } return true; } else if (p_constant->datatype==TYPE_UINT && p_to_type==TYPE_INT) { if (p_constant->values[0].uint>0x7FFFFFFF) { return false; } if (p_value) { p_value->sint=p_constant->values[0].uint; } return true; } else return false; } bool ShaderLanguage::is_scalar_type(DataType p_type) { return p_type==TYPE_BOOL || p_type==TYPE_INT || p_type==TYPE_UINT || p_type==TYPE_FLOAT; } bool ShaderLanguage::is_sampler_type(DataType p_type) { return p_type==TYPE_SAMPLER2D || p_type==TYPE_ISAMPLER2D || p_type==TYPE_USAMPLER2D || p_type==TYPE_SAMPLERCUBE; } void ShaderLanguage::get_keyword_list(List<String> *r_keywords) { Set<String> kws; int idx=0; while(keyword_list[idx].text) { kws.insert(keyword_list[idx].text); idx++; } idx=0; while (builtin_func_defs[idx].name) { kws.insert(builtin_func_defs[idx].name); idx++; } for(Set<String>::Element *E=kws.front();E;E=E->next()) { r_keywords->push_back(E->get()); } } void ShaderLanguage::get_builtin_funcs(List<String> *r_keywords) { Set<String> kws; int idx=0; while (builtin_func_defs[idx].name) { kws.insert(builtin_func_defs[idx].name); idx++; } for(Set<String>::Element *E=kws.front();E;E=E->next()) { r_keywords->push_back(E->get()); } } ShaderLanguage::DataType ShaderLanguage::get_scalar_type(DataType p_type) { static const DataType scalar_types[]={ TYPE_VOID, TYPE_BOOL, TYPE_BOOL, TYPE_BOOL, TYPE_BOOL, TYPE_INT, TYPE_INT, TYPE_INT, TYPE_INT, TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_UINT, TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_FLOAT, TYPE_INT, TYPE_UINT, TYPE_FLOAT, }; return scalar_types[p_type]; } bool ShaderLanguage::_get_completable_identifier(BlockNode *p_block,CompletionType p_type,StringName& identifier) { identifier=StringName(); TkPos pos; Token tk = _get_token(); if (tk.type==TK_IDENTIFIER) { identifier=tk.text; pos = _get_tkpos(); tk = _get_token(); } if (tk.type==TK_CURSOR) { completion_type=p_type; completion_line=tk_line; completion_block=p_block; pos = _get_tkpos(); tk = _get_token(); if (tk.type==TK_IDENTIFIER) { identifier=identifier.operator String() + tk.text.operator String(); } else { _set_tkpos(pos); } return true; } else if (identifier!=StringName()){ _set_tkpos(pos); } return false; } ShaderLanguage::Node* ShaderLanguage::_parse_expression(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types) { Vector<Expression> expression; //Vector<TokenType> operators; while(true) { Node *expr=NULL; TkPos prepos = _get_tkpos(); Token tk = _get_token(); TkPos pos = _get_tkpos(); if (tk.type==TK_PARENTHESIS_OPEN) { //handle subexpression expr = _parse_and_reduce_expression(p_block,p_builtin_types); if (!expr) return NULL; tk = _get_token(); if (tk.type!=TK_PARENTHESIS_CLOSE) { _set_error("Expected ')' in expression"); return NULL; } } else if (tk.type==TK_REAL_CONSTANT) { ConstantNode *constant = alloc_node<ConstantNode>(); ConstantNode::Value v; v.real=tk.constant; constant->values.push_back(v); constant->datatype=TYPE_FLOAT; expr=constant; } else if (tk.type==TK_INT_CONSTANT) { ConstantNode *constant = alloc_node<ConstantNode>(); ConstantNode::Value v; v.sint=tk.constant; constant->values.push_back(v); constant->datatype=TYPE_INT; expr=constant; } else if (tk.type==TK_TRUE) { //print_line("found true"); //handle true constant ConstantNode *constant = alloc_node<ConstantNode>(); ConstantNode::Value v; v.boolean=true; constant->values.push_back(v); constant->datatype=TYPE_BOOL; expr=constant; } else if (tk.type==TK_FALSE) { //handle false constant ConstantNode *constant = alloc_node<ConstantNode>(); ConstantNode::Value v; v.boolean=false; constant->values.push_back(v); constant->datatype=TYPE_BOOL; expr=constant; } else if (tk.type==TK_TYPE_VOID) { //make sure void is not used in expression _set_error("Void value not allowed in Expression"); return NULL; } else if (is_token_nonvoid_datatype(tk.type)) { //basic type constructor OperatorNode *func = alloc_node<OperatorNode>(); func->op=OP_CONSTRUCT; if (is_token_precision(tk.type)) { func->return_precision_cache=get_token_precision(tk.type); tk=_get_token(); } VariableNode *funcname = alloc_node<VariableNode>(); funcname->name=get_datatype_name(get_token_datatype(tk.type)); func->arguments.push_back(funcname); tk=_get_token(); if (tk.type!=TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after type name"); return NULL; } int carg=-1; bool ok = _parse_function_arguments(p_block,p_builtin_types,func,&carg); if (carg>=0) { completion_type=COMPLETION_CALL_ARGUMENTS; completion_line=tk_line; completion_block=p_block; completion_function=funcname->name; completion_argument=carg; } if (!ok) return NULL; if (!_validate_function_call(p_block,func,&func->return_cache)) { _set_error("No matching constructor found for: '"+String(funcname->name)+"'"); return NULL; } //validate_Function_call() expr=_reduce_expression(p_block,func); } else if (tk.type==TK_IDENTIFIER) { _set_tkpos(prepos); StringName identifier; _get_completable_identifier(p_block,COMPLETION_IDENTIFIER,identifier); tk=_get_token(); if (tk.type==TK_PARENTHESIS_OPEN) { //a function StringName name = identifier; OperatorNode *func = alloc_node<OperatorNode>(); func->op=OP_CALL; VariableNode *funcname = alloc_node<VariableNode>(); funcname->name=name; func->arguments.push_back(funcname); int carg=-1; bool ok =_parse_function_arguments(p_block,p_builtin_types,func,&carg); for(int i=0;i<shader->functions.size();i++) { if (shader->functions[i].name==name) { shader->functions[i].uses_function.insert(name); } } if (carg>=0) { completion_type=COMPLETION_CALL_ARGUMENTS; completion_line=tk_line; completion_block=p_block; completion_function=funcname->name; completion_argument=carg; } if (!ok) return NULL; if (!_validate_function_call(p_block,func,&func->return_cache)) { _set_error("No matching function found for: '"+String(funcname->name)+"'"); return NULL; } expr=func; } else { //an identifier _set_tkpos(pos); DataType data_type; IdentifierType ident_type; if (!_find_identifier(p_block,p_builtin_types,identifier,&data_type,&ident_type)) { _set_error("Unknown identifier in expression: "+String(identifier)); return NULL; } if (ident_type==IDENTIFIER_FUNCTION) { _set_error("Can't use function as identifier: "+String(identifier)); return NULL; } VariableNode *varname = alloc_node<VariableNode>(); varname->name=identifier; varname->datatype_cache=data_type; expr=varname; } } else if (tk.type==TK_OP_ADD) { continue; //this one does nothing } else if (tk.type==TK_OP_SUB || tk.type==TK_OP_NOT || tk.type==TK_OP_BIT_INVERT || tk.type==TK_OP_INCREMENT || tk.type==TK_OP_DECREMENT) { Expression e; e.is_op=true; switch(tk.type) { case TK_OP_SUB: e.op=OP_NEGATE; break; case TK_OP_NOT: e.op=OP_NOT; break; case TK_OP_BIT_INVERT: e.op=OP_BIT_INVERT; break; case TK_OP_INCREMENT: e.op=OP_INCREMENT; break; case TK_OP_DECREMENT: e.op=OP_DECREMENT; break; default: ERR_FAIL_V(NULL); } expression.push_back(e); continue; } else { _set_error("Expected expression, found: "+get_token_text(tk)); return NULL; //nothing } ERR_FAIL_COND_V(!expr,NULL); /* OK now see what's NEXT to the operator.. */ /* OK now see what's NEXT to the operator.. */ /* OK now see what's NEXT to the operator.. */ while(true) { TkPos pos = _get_tkpos(); tk=_get_token(); if (tk.type==TK_PERIOD) { StringName identifier; if (_get_completable_identifier(p_block,COMPLETION_INDEX,identifier)) { completion_base=expr->get_datatype(); } if (identifier==StringName()) { _set_error("Expected identifier as member"); return NULL; } DataType dt = expr->get_datatype(); String ident = identifier; bool ok=true; DataType member_type; switch(dt) { case TYPE_BVEC2: case TYPE_IVEC2: case TYPE_UVEC2: case TYPE_VEC2: { int l = ident.length(); if (l==1) { member_type=DataType(dt-1); } else if (l==2) { member_type=dt; } else { ok=false; break; } const CharType *c=ident.ptr(); for(int i=0;i<l;i++) { switch(c[i]) { case 'r': case 'g': case 'x': case 'y': break; default: ok=false; break; } } } break; case TYPE_BVEC3: case TYPE_IVEC3: case TYPE_UVEC3: case TYPE_VEC3: { int l = ident.length(); if (l==1) { member_type=DataType(dt-2); } else if (l==2) { member_type=DataType(dt-1); } else if (l==3) { member_type=dt; } else { ok=false; break; } const CharType *c=ident.ptr(); for(int i=0;i<l;i++) { switch(c[i]) { case 'r': case 'g': case 'b': case 'x': case 'y': case 'z': break; default: ok=false; break; } } } break; case TYPE_BVEC4: case TYPE_IVEC4: case TYPE_UVEC4: case TYPE_VEC4: { int l = ident.length(); if (l==1) { member_type=DataType(dt-3); } else if (l==2) { member_type=DataType(dt-2); } else if (l==3) { member_type=DataType(dt-1); } else if (l==4) { member_type=dt; } else { ok=false; break; } const CharType *c=ident.ptr(); for(int i=0;i<l;i++) { switch(c[i]) { case 'r': case 'g': case 'b': case 'a': case 'x': case 'y': case 'z': case 'w': break; default: ok=false; break; } } } break; case TYPE_MAT2: ok=(ident=="x" || ident=="y"); member_type=TYPE_VEC2; break; case TYPE_MAT3: ok=(ident=="x" || ident=="y" || ident=="z" ); member_type=TYPE_VEC3; break; case TYPE_MAT4: ok=(ident=="x" || ident=="y" || ident=="z" || ident=="w"); member_type=TYPE_VEC4; break; default: {} } if (!ok) { _set_error("Invalid member for expression: ."+ident); return NULL; } MemberNode *mn = alloc_node<MemberNode>(); mn->basetype=dt; mn->datatype=member_type; mn->name=ident; mn->owner=expr; expr=mn; //todo //member (period) has priority over any operator //creates a subindexing expression in place /*} else if (tk.type==TK_BRACKET_OPEN) { //todo //subindexing has priority over any operator //creates a subindexing expression in place */ } else if (tk.type==TK_OP_INCREMENT || tk.type==TK_OP_DECREMENT) { OperatorNode *op = alloc_node<OperatorNode>(); op->op=tk.type==TK_OP_DECREMENT ? OP_POST_DECREMENT : OP_POST_INCREMENT; op->arguments.push_back(expr); if (!_validate_operator(op,&op->return_cache)) { _set_error("Invalid base type for increment/decrement operator"); return NULL; } expr=op; } else { _set_tkpos(pos); break; } } Expression e; e.is_op=false; e.node=expr; expression.push_back(e); pos = _get_tkpos(); tk = _get_token(); if (is_token_operator(tk.type)) { Expression o; o.is_op=true; switch(tk.type) { case TK_OP_EQUAL: o.op = OP_EQUAL; break; case TK_OP_NOT_EQUAL: o.op = OP_NOT_EQUAL; break; case TK_OP_LESS: o.op = OP_LESS; break; case TK_OP_LESS_EQUAL: o.op = OP_LESS_EQUAL; break; case TK_OP_GREATER: o.op = OP_GREATER; break; case TK_OP_GREATER_EQUAL: o.op = OP_GREATER_EQUAL; break; case TK_OP_AND: o.op = OP_AND; break; case TK_OP_OR: o.op = OP_OR; break; case TK_OP_ADD: o.op = OP_ADD; break; case TK_OP_SUB: o.op = OP_SUB; break; case TK_OP_MUL: o.op = OP_MUL; break; case TK_OP_DIV: o.op = OP_DIV; break; case TK_OP_MOD: o.op = OP_MOD; break; case TK_OP_SHIFT_LEFT: o.op = OP_SHIFT_LEFT; break; case TK_OP_SHIFT_RIGHT: o.op = OP_SHIFT_RIGHT; break; case TK_OP_ASSIGN: o.op = OP_ASSIGN; break; case TK_OP_ASSIGN_ADD: o.op = OP_ASSIGN_ADD; break; case TK_OP_ASSIGN_SUB: o.op = OP_ASSIGN_SUB; break; case TK_OP_ASSIGN_MUL: o.op = OP_ASSIGN_MUL; break; case TK_OP_ASSIGN_DIV: o.op = OP_ASSIGN_DIV; break; case TK_OP_ASSIGN_MOD: o.op = OP_ASSIGN_MOD; break; case TK_OP_ASSIGN_SHIFT_LEFT: o.op = OP_ASSIGN_SHIFT_LEFT; break; case TK_OP_ASSIGN_SHIFT_RIGHT: o.op = OP_ASSIGN_SHIFT_RIGHT; break; case TK_OP_ASSIGN_BIT_AND: o.op = OP_ASSIGN_BIT_AND; break; case TK_OP_ASSIGN_BIT_OR: o.op = OP_ASSIGN_BIT_OR; break; case TK_OP_ASSIGN_BIT_XOR: o.op = OP_ASSIGN_BIT_XOR; break; case TK_OP_BIT_AND: o.op = OP_BIT_AND; break; case TK_OP_BIT_OR: o.op = OP_BIT_OR ; break; case TK_OP_BIT_XOR: o.op = OP_BIT_XOR; break; case TK_QUESTION: o.op = OP_SELECT_IF; break; case TK_COLON: o.op = OP_SELECT_ELSE; break; default: { _set_error("Invalid token for operator: "+get_token_text(tk)); return NULL; } } expression.push_back(o); } else { _set_tkpos(pos); //something else, so rollback and end break; } } /* Reduce the set set of expressions and place them in an operator tree, respecting precedence */ while(expression.size()>1) { int next_op=-1; int min_priority=0xFFFFF; bool is_unary=false; bool is_ternary=false; for(int i=0;i<expression.size();i++) { if (!expression[i].is_op) { continue; } bool unary=false; bool ternary=false; int priority; switch(expression[i].op) { case OP_EQUAL: priority=8; break; case OP_NOT_EQUAL: priority=8; break; case OP_LESS: priority=7; break; case OP_LESS_EQUAL: priority=7; break; case OP_GREATER: priority=7; break; case OP_GREATER_EQUAL: priority=7; break; case OP_AND: priority=12; break; case OP_OR: priority=14; break; case OP_NOT: priority=3; unary=true; break; case OP_NEGATE: priority=3; unary=true; break; case OP_ADD: priority=5; break; case OP_SUB: priority=5; break; case OP_MUL: priority=4; break; case OP_DIV: priority=4; break; case OP_MOD: priority=4; break; case OP_SHIFT_LEFT: priority=6; break; case OP_SHIFT_RIGHT: priority=6; break; case OP_ASSIGN: priority=16; break; case OP_ASSIGN_ADD: priority=16; break; case OP_ASSIGN_SUB: priority=16; break; case OP_ASSIGN_MUL: priority=16; break; case OP_ASSIGN_DIV: priority=16; break; case OP_ASSIGN_MOD: priority=16; break; case OP_ASSIGN_SHIFT_LEFT: priority=16; break; case OP_ASSIGN_SHIFT_RIGHT: priority=16; break; case OP_ASSIGN_BIT_AND: priority=16; break; case OP_ASSIGN_BIT_OR: priority=16; break; case OP_ASSIGN_BIT_XOR: priority=16; break; case OP_BIT_AND: priority=9; break; case OP_BIT_OR: priority=11; break; case OP_BIT_XOR: priority=10; break; case OP_BIT_INVERT: priority=3; unary=true; break; case OP_INCREMENT: priority=3; unary=true; break; case OP_DECREMENT: priority=3; unary=true; break; case OP_SELECT_IF: priority=15; ternary=true; break; case OP_SELECT_ELSE: priority=15; ternary=true; break; default: ERR_FAIL_V(NULL); //unexpected operator } if (priority<min_priority) { // < is used for left to right (default) // <= is used for right to left next_op=i; min_priority=priority; is_unary=unary; is_ternary=ternary; } } ERR_FAIL_COND_V(next_op==-1,NULL); // OK! create operator.. // OK! create operator.. if (is_unary) { int expr_pos=next_op; while(expression[expr_pos].is_op) { expr_pos++; if (expr_pos==expression.size()) { //can happen.. _set_error("Unexpected end of expression.."); return NULL; } } //consecutively do unary opeators for(int i=expr_pos-1;i>=next_op;i--) { OperatorNode *op = alloc_node<OperatorNode>(); op->op=expression[i].op; op->arguments.push_back(expression[i+1].node); expression[i].is_op=false; expression[i].node=op; if (!_validate_operator(op,&op->return_cache)) { String at; for(int i=0;i<op->arguments.size();i++) { if (i>0) at+=" and "; at+=get_datatype_name(op->arguments[i]->get_datatype()); } _set_error("Invalid arguments to unary operator '"+get_operator_text(op->op)+"' :" +at); return NULL; } expression.remove(i+1); } } else if (is_ternary) { if (next_op <1 || next_op>=(expression.size()-1)) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } if (next_op+2 >= expression.size() || !expression[next_op+2].is_op || expression[next_op+2].op!=OP_SELECT_ELSE) { _set_error("Mising matching ':' for select operator"); return NULL; } OperatorNode *op = alloc_node<OperatorNode>(); op->op=expression[next_op].op; op->arguments.push_back(expression[next_op-1].node); op->arguments.push_back(expression[next_op+1].node); op->arguments.push_back(expression[next_op+3].node); expression[next_op-1].is_op=false; expression[next_op-1].node=op; if (!_validate_operator(op,&op->return_cache)) { String at; for(int i=0;i<op->arguments.size();i++) { if (i>0) at+=" and "; at+=get_datatype_name(op->arguments[i]->get_datatype()); } _set_error("Invalid argument to ternary ?: operator: "+at); return NULL; } for(int i=0;i<4;i++) { expression.remove(next_op); } } else { if (next_op <1 || next_op>=(expression.size()-1)) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } OperatorNode *op = alloc_node<OperatorNode>(); op->op=expression[next_op].op; if (expression[next_op-1].is_op) { _set_error("Parser bug.."); ERR_FAIL_V(NULL); } if (expression[next_op+1].is_op) { // this is not invalid and can really appear // but it becomes invalid anyway because no binary op // can be followed by an unary op in a valid combination, // due to how precedence works, unaries will always dissapear first _set_error("Parser bug.."); } op->arguments.push_back(expression[next_op-1].node); //expression goes as left op->arguments.push_back(expression[next_op+1].node); //next expression goes as right expression[next_op-1].node=op; //replace all 3 nodes by this operator and make it an expression if (!_validate_operator(op,&op->return_cache)) { String at; for(int i=0;i<op->arguments.size();i++) { if (i>0) at+=" and "; at+=get_datatype_name(op->arguments[i]->get_datatype()); } _set_error("Invalid arguments to operator '"+get_operator_text(op->op)+"' :" +at); return NULL; } expression.remove(next_op); expression.remove(next_op); } } return expression[0].node; } ShaderLanguage::Node* ShaderLanguage::_reduce_expression(BlockNode *p_block, ShaderLanguage::Node *p_node) { if (p_node->type!=Node::TYPE_OPERATOR) return p_node; //for now only reduce simple constructors OperatorNode *op=static_cast<OperatorNode*>(p_node); if (op->op==OP_CONSTRUCT) { ERR_FAIL_COND_V(op->arguments[0]->type!=Node::TYPE_VARIABLE,p_node); VariableNode *vn = static_cast<VariableNode*>(op->arguments[0]); //StringName name=vn->name; DataType base=get_scalar_type(op->get_datatype()); Vector<ConstantNode::Value> values; for(int i=1;i<op->arguments.size();i++) { op->arguments[i]=_reduce_expression(p_block,op->arguments[i]); if (op->arguments[i]->type==Node::TYPE_CONSTANT) { ConstantNode *cn = static_cast<ConstantNode*>(op->arguments[i]); if (get_scalar_type(cn->datatype)==base) { for(int j=0;j<cn->values.size();j++) { values.push_back(cn->values[j]); } } else if (get_scalar_type(cn->datatype)==cn->datatype) { ConstantNode::Value v; if (!convert_constant(cn,base,&v)) { return p_node; } values.push_back(v); } else { return p_node; } } else { return p_node; } } ConstantNode *cn=alloc_node<ConstantNode>(); cn->datatype=op->get_datatype(); cn->values=values; return cn; } else if (op->op==OP_NEGATE) { op->arguments[0]=_reduce_expression(p_block,op->arguments[0]); if (op->arguments[0]->type==Node::TYPE_CONSTANT) { ConstantNode *cn = static_cast<ConstantNode*>(op->arguments[0]); DataType base=get_scalar_type(cn->datatype); Vector<ConstantNode::Value> values; for(int i=0;i<cn->values.size();i++) { ConstantNode::Value nv; switch(base) { case TYPE_BOOL: { nv.boolean=!cn->values[i].boolean; } break; case TYPE_INT: { nv.sint=-cn->values[i].sint; } break; case TYPE_UINT: { nv.uint=-cn->values[i].uint; } break; case TYPE_FLOAT: { nv.real=-cn->values[i].real; } break; default: {} } values.push_back(nv); } cn->values=values; return cn; } } return p_node; } ShaderLanguage::Node* ShaderLanguage::_parse_and_reduce_expression(BlockNode *p_block, const Map<StringName,DataType> &p_builtin_types) { ShaderLanguage::Node* expr = _parse_expression(p_block,p_builtin_types); if (!expr) //errored return NULL; expr = _reduce_expression(p_block,expr); return expr; } Error ShaderLanguage::_parse_block(BlockNode* p_block,const Map<StringName,DataType> &p_builtin_types,bool p_just_one,bool p_can_break,bool p_can_continue) { while(true) { TkPos pos = _get_tkpos(); Token tk = _get_token(); if (tk.type==TK_CURLY_BRACKET_CLOSE) { //end of block if (p_just_one) { _set_error("Unexpected '}'"); return ERR_PARSE_ERROR; } return OK; } else if (is_token_precision(tk.type) || is_token_nonvoid_datatype(tk.type)) { DataPrecision precision=PRECISION_DEFAULT; if (is_token_precision(tk.type)) { precision=get_token_precision(tk.type); tk = _get_token(); if (!is_token_nonvoid_datatype(tk.type)) { _set_error("Expected datatype after precission"); return ERR_PARSE_ERROR; } } DataType type = get_token_datatype(tk.type); tk = _get_token(); while(true) { if (tk.type!=TK_IDENTIFIER) { _set_error("Expected identifier after type"); return ERR_PARSE_ERROR; } StringName name = tk.text; if (_find_identifier(p_block,p_builtin_types,name)) { _set_error("Redefinition of '"+String(name)+"'"); return ERR_PARSE_ERROR; } BlockNode::Variable var; var.type=type; var.precision=precision; var.line=tk_line; p_block->variables[name]=var; tk = _get_token(); if (tk.type==TK_OP_ASSIGN) { //variable creted with assignment! must parse an expression Node* n = _parse_and_reduce_expression(p_block,p_builtin_types); if (!n) return ERR_PARSE_ERROR; OperatorNode *assign = alloc_node<OperatorNode>(); VariableNode *vnode = alloc_node<VariableNode>(); vnode->name=name; vnode->datatype_cache=type; assign->arguments.push_back(vnode); assign->arguments.push_back(n); assign->op=OP_ASSIGN; p_block->statements.push_back(assign); tk = _get_token(); } if (tk.type==TK_COMMA) { tk = _get_token(); //another variable } else if (tk.type==TK_SEMICOLON) { break; } else { _set_error("Expected ',' or ';' after variable"); return ERR_PARSE_ERROR; } } } else if (tk.type==TK_CURLY_BRACKET_OPEN) { //a sub block, just because.. BlockNode* block = alloc_node<BlockNode>(); block->parent_block=p_block; _parse_block(block,p_builtin_types,false,p_can_break,p_can_continue); p_block->statements.push_back(block); } else if (tk.type==TK_CF_IF) { //if () {} tk = _get_token(); if (tk.type!=TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after if"); return ERR_PARSE_ERROR; } ControlFlowNode *cf = alloc_node<ControlFlowNode>(); cf->flow_op=FLOW_OP_IF; Node* n = _parse_and_reduce_expression(p_block,p_builtin_types); if (!n) return ERR_PARSE_ERROR; tk = _get_token(); if (tk.type!=TK_PARENTHESIS_CLOSE) { _set_error("Expected '(' after expression"); return ERR_PARSE_ERROR; } BlockNode* block = alloc_node<BlockNode>(); block->parent_block=p_block; cf->expressions.push_back(n); cf->blocks.push_back(block); p_block->statements.push_back(cf); Error err=_parse_block(block,p_builtin_types,true,p_can_break,p_can_continue); pos=_get_tkpos(); tk = _get_token(); if (tk.type==TK_CF_ELSE) { block = alloc_node<BlockNode>(); block->parent_block=p_block; cf->blocks.push_back(block); err=_parse_block(block,p_builtin_types,true,p_can_break,p_can_continue); } else { _set_tkpos(pos); //rollback } } else { //nothng else, so expression _set_tkpos(pos); //rollback Node*expr = _parse_and_reduce_expression(p_block,p_builtin_types); if (!expr) return ERR_PARSE_ERROR; p_block->statements.push_back(expr); tk = _get_token(); if (tk.type!=TK_SEMICOLON) { _set_error("Expected ';' after statement"); return ERR_PARSE_ERROR; } } if (p_just_one) break; } return OK; } Error ShaderLanguage::_parse_shader(const Map< StringName, Map<StringName,DataType> > &p_functions, const Set<String> &p_render_modes) { Token tk = _get_token(); int texture_uniforms = 0; int uniforms =0; while(tk.type!=TK_EOF) { switch(tk.type) { case TK_RENDER_MODE: { while(true) { StringName mode; _get_completable_identifier(NULL,COMPLETION_RENDER_MODE,mode); if (mode==StringName()) { _set_error("Expected identifier for render mode"); return ERR_PARSE_ERROR; } if (!p_render_modes.has(mode)) { _set_error("Invalid render mode: '"+String(mode)+"'"); return ERR_PARSE_ERROR; } if (shader->render_modes.find(mode)!=-1) { _set_error("Duplicate render mode: '"+String(mode)+"'"); return ERR_PARSE_ERROR; } shader->render_modes.push_back(mode); tk = _get_token(); if (tk.type==TK_COMMA) { //all good, do nothing } else if (tk.type==TK_SEMICOLON) { break; //done } else { _set_error("Unexpected token: "+get_token_text(tk)); return ERR_PARSE_ERROR; } } } break; case TK_UNIFORM: case TK_VARYING: { bool uniform = tk.type==TK_UNIFORM; DataPrecision precision = PRECISION_DEFAULT; DataType type; StringName name; tk = _get_token(); if (is_token_precision(tk.type)) { precision=get_token_precision(tk.type); tk = _get_token(); } if (!is_token_datatype(tk.type)) { _set_error("Expected datatype. "); return ERR_PARSE_ERROR; } type = get_token_datatype(tk.type); if (type==TYPE_VOID) { _set_error("void datatype not allowed here"); return ERR_PARSE_ERROR; } if (!uniform && type<TYPE_FLOAT && type>TYPE_VEC4) { _set_error("Invalid type for varying, only float,vec2,vec3,vec4 allowed."); return ERR_PARSE_ERROR; } tk = _get_token(); if (tk.type!=TK_IDENTIFIER) { _set_error("Expected identifier!"); return ERR_PARSE_ERROR; } name=tk.text; if (_find_identifier(NULL,Map<StringName,DataType>(),name)) { _set_error("Redefinition of '"+String(name)+"'"); return ERR_PARSE_ERROR; } if (uniform) { ShaderNode::Uniform uniform; if (is_sampler_type(type)) { uniform.texture_order=texture_uniforms++; uniform.order=-1; } else { uniform.texture_order=-1; uniform.order=uniforms++; } uniform.type=type; uniform.precission=precision; //todo parse default value tk = _get_token(); if (tk.type==TK_OP_ASSIGN) { Node* expr = _parse_and_reduce_expression(NULL,Map<StringName,DataType>()); if (!expr) return ERR_PARSE_ERROR; if (expr->type!=Node::TYPE_CONSTANT) { _set_error("Expected constant expression after '='"); return ERR_PARSE_ERROR; } ConstantNode* cn = static_cast<ConstantNode*>(expr); uniform.default_value.resize(cn->values.size()); if (!convert_constant(cn,uniform.type,uniform.default_value.ptr())) { _set_error("Can't convert constant to "+get_datatype_name(uniform.type)); return ERR_PARSE_ERROR; } tk = _get_token(); } if (tk.type==TK_COLON) { //hint tk = _get_token(); if (tk.type==TK_HINT_WHITE_TEXTURE) { uniform.hint=ShaderNode::Uniform::HINT_WHITE; } else if (tk.type==TK_HINT_BLACK_TEXTURE) { uniform.hint=ShaderNode::Uniform::HINT_BLACK; } else if (tk.type==TK_HINT_NORMAL_TEXTURE) { uniform.hint=ShaderNode::Uniform::HINT_NORMAL; } else if (tk.type==TK_HINT_ANISO_TEXTURE) { uniform.hint=ShaderNode::Uniform::HINT_ANISO; } else if (tk.type==TK_HINT_ALBEDO_TEXTURE) { uniform.hint=ShaderNode::Uniform::HINT_ALBEDO; } else if (tk.type==TK_HINT_BLACK_ALBEDO_TEXTURE) { uniform.hint=ShaderNode::Uniform::HINT_BLACK_ALBEDO; } else if (tk.type==TK_HINT_COLOR) { if (type!=TYPE_VEC4) { _set_error("Color hint is for vec4 only"); return ERR_PARSE_ERROR; } uniform.hint=ShaderNode::Uniform::HINT_COLOR; } else if (tk.type==TK_HINT_RANGE) { uniform.hint=ShaderNode::Uniform::HINT_RANGE; if (type!=TYPE_FLOAT && type!=TYPE_INT) { _set_error("Range hint is for float and int only"); return ERR_PARSE_ERROR; } tk = _get_token(); if (tk.type!=TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after hint_range"); return ERR_PARSE_ERROR; } tk = _get_token(); float sign=1.0; if (tk.type==TK_OP_SUB) { sign=-1.0; tk = _get_token(); } if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) { _set_error("Expected integer constant"); return ERR_PARSE_ERROR; } uniform.hint_range[0]=tk.constant; uniform.hint_range[0]*=sign; tk = _get_token(); if (tk.type!=TK_COMMA) { _set_error("Expected ',' after integer constant"); return ERR_PARSE_ERROR; } tk = _get_token(); sign=1.0; if (tk.type==TK_OP_SUB) { sign=-1.0; tk = _get_token(); } if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) { _set_error("Expected integer constant after ','"); return ERR_PARSE_ERROR; } uniform.hint_range[1]=tk.constant; uniform.hint_range[1]*=sign; tk = _get_token(); if (tk.type==TK_COMMA) { tk = _get_token(); if (tk.type!=TK_REAL_CONSTANT && tk.type!=TK_INT_CONSTANT) { _set_error("Expected integer constant after ','"); return ERR_PARSE_ERROR; } uniform.hint_range[2]=tk.constant; tk = _get_token(); } else { if (type==TYPE_INT) { uniform.hint_range[2]=1; } else { uniform.hint_range[2]=0.001; } } if (tk.type!=TK_PARENTHESIS_CLOSE) { _set_error("Expected ','"); return ERR_PARSE_ERROR; } } else { _set_error("Expected valid type hint after ':'."); } if (uniform.hint!=ShaderNode::Uniform::HINT_RANGE && uniform.hint!=ShaderNode::Uniform::HINT_NONE && uniform.hint!=ShaderNode::Uniform::HINT_COLOR && type <=TYPE_MAT4) { _set_error("This hint is only for sampler types"); return ERR_PARSE_ERROR; } tk = _get_token(); } shader->uniforms[name]=uniform; if (tk.type!=TK_SEMICOLON) { _set_error("Expected ';'"); return ERR_PARSE_ERROR; } } else { ShaderNode::Varying varying; varying.type=type; varying.precission=precision; shader->varyings[name]=varying; tk = _get_token(); if (tk.type!=TK_SEMICOLON) { _set_error("Expected ';'"); return ERR_PARSE_ERROR; } } } break; default: { //function DataPrecision precision = PRECISION_DEFAULT; DataType type; StringName name; if (is_token_precision(tk.type)) { precision=get_token_precision(tk.type); tk = _get_token(); } if (!is_token_datatype(tk.type)) { _set_error("Expected funtion, uniform or varying "); return ERR_PARSE_ERROR; } type = get_token_datatype(tk.type); _get_completable_identifier(NULL,COMPLETION_MAIN_FUNCTION,name); if (name==StringName()) { _set_error("Expected function name after datatype"); return ERR_PARSE_ERROR; } if (_find_identifier(NULL,Map<StringName,DataType>(),name)) { _set_error("Redefinition of '"+String(name)+"'"); return ERR_PARSE_ERROR; } tk = _get_token(); if (tk.type!=TK_PARENTHESIS_OPEN) { _set_error("Expected '(' after identifier"); return ERR_PARSE_ERROR; } Map<StringName,DataType> builtin_types; if (p_functions.has(name)) { builtin_types=p_functions[name]; } ShaderNode::Function function; function.callable=!p_functions.has(name); function.name=name; FunctionNode* func_node=alloc_node<FunctionNode>(); function.function=func_node; shader->functions.push_back(function); func_node->name=name; func_node->return_type=type; func_node->return_precision=precision; func_node->body = alloc_node<BlockNode>(); func_node->body->parent_function=func_node; tk = _get_token(); while(true) { if (tk.type==TK_PARENTHESIS_CLOSE) { break; } DataType ptype; StringName pname; DataPrecision pprecision = PRECISION_DEFAULT; if (is_token_precision(tk.type)) { pprecision=get_token_precision(tk.type); tk = _get_token(); } if (!is_token_datatype(tk.type)) { _set_error("Expected a valid datatype for argument"); return ERR_PARSE_ERROR; } ptype=get_token_datatype(tk.type); if (ptype==TYPE_VOID) { _set_error("void not allowed in argument"); return ERR_PARSE_ERROR; } tk = _get_token(); if (tk.type!=TK_IDENTIFIER) { _set_error("Expected identifier for argument name"); return ERR_PARSE_ERROR; } pname = tk.text; if (_find_identifier(func_node->body,builtin_types,pname)) { _set_error("Redefinition of '"+String(pname)+"'"); return ERR_PARSE_ERROR; } FunctionNode::Argument arg; arg.type=ptype; arg.name=pname; arg.precision=pprecision; func_node->arguments.push_back(arg); tk = _get_token(); if (tk.type==TK_COMMA) { tk = _get_token(); //do none and go on } else if (tk.type!=TK_PARENTHESIS_CLOSE) { _set_error("Expected ',' or ')' after identifier"); return ERR_PARSE_ERROR; } } if (p_functions.has(name)) { //if one of the core functions, make sure they are of the correct form if (func_node->arguments.size() > 0) { _set_error("Function '"+String(name)+"' expects no arguments."); return ERR_PARSE_ERROR; } if (func_node->return_type!=TYPE_VOID) { _set_error("Function '"+String(name)+"' must be of void return type."); return ERR_PARSE_ERROR; } } //all good let's parse inside the fucntion! tk = _get_token(); if (tk.type!=TK_CURLY_BRACKET_OPEN) { _set_error("Expected '{' to begin function"); return ERR_PARSE_ERROR; } current_function = name; Error err = _parse_block(func_node->body,builtin_types); if (err) return err; current_function=StringName(); } } tk = _get_token(); } return OK; } Error ShaderLanguage::compile(const String& p_code, const Map< StringName, Map<StringName,DataType> > &p_functions, const Set<String> &p_render_modes) { clear(); code=p_code; nodes=NULL; shader = alloc_node<ShaderNode>(); Error err = _parse_shader(p_functions,p_render_modes); if (err!=OK) { return err; } return OK; } Error ShaderLanguage::complete(const String& p_code,const Map< StringName, Map<StringName,DataType> > &p_functions,const Set<String>& p_render_modes,List<String>* r_options,String& r_call_hint) { clear(); code=p_code; nodes=NULL; shader = alloc_node<ShaderNode>(); Error err = _parse_shader(p_functions,p_render_modes); switch(completion_type) { case COMPLETION_NONE: { //do none return ERR_PARSE_ERROR; } break; case COMPLETION_RENDER_MODE: { for(const Set<String>::Element *E=p_render_modes.front();E;E=E->next()) { r_options->push_back(E->get()); } return OK; } break; case COMPLETION_MAIN_FUNCTION: { for(const Map< StringName, Map<StringName,DataType> >::Element *E=p_functions.front();E;E=E->next()) { r_options->push_back(E->key()); } return OK; } break; case COMPLETION_IDENTIFIER: case COMPLETION_FUNCTION_CALL: { bool comp_ident=completion_type==COMPLETION_IDENTIFIER; Set<String> matches; StringName skip_function; BlockNode *block=completion_block; while(block) { if (comp_ident) { for (const Map<StringName,BlockNode::Variable>::Element *E=block->variables.front();E;E=E->next()) { if (E->get().line<completion_line) { matches.insert(E->key()); } } } if (block->parent_function) { if (comp_ident) { for(int i=0;i<block->parent_function->arguments.size();i++) { matches.insert(block->parent_function->arguments[i].name); } } skip_function=block->parent_function->name; } block=block->parent_block; } if (comp_ident && skip_function!=StringName() && p_functions.has(skip_function)) { for (Map<StringName,DataType>::Element *E=p_functions[skip_function].front();E;E=E->next()) { matches.insert(E->key()); } } if (comp_ident) { for (const Map<StringName,ShaderNode::Varying>::Element *E=shader->varyings.front();E;E=E->next()) { matches.insert(E->key()); } for (const Map<StringName,ShaderNode::Uniform>::Element *E=shader->uniforms.front();E;E=E->next()) { matches.insert(E->key()); } } for(int i=0;i<shader->functions.size();i++) { if (!shader->functions[i].callable || shader->functions[i].name==skip_function) continue; matches.insert(String(shader->functions[i].name)+"("); } int idx=0; while (builtin_func_defs[idx].name) { matches.insert(String(builtin_func_defs[idx].name)+"("); idx++; } for(Set<String>::Element *E=matches.front();E;E=E->next()) { r_options->push_back(E->get()); } return OK; } break; case COMPLETION_CALL_ARGUMENTS: { for(int i=0;i<shader->functions.size();i++) { if (!shader->functions[i].callable) continue; if (shader->functions[i].name==completion_function) { String calltip; calltip+=get_datatype_name( shader->functions[i].function->return_type ); calltip+=" "; calltip+=shader->functions[i].name; calltip+="("; for(int j=0;j<shader->functions[i].function->arguments.size();j++) { if (j>0) calltip+=", "; else calltip+=" "; if (j==completion_argument) { calltip+=CharType(0xFFFF); } calltip+=get_datatype_name(shader->functions[i].function->arguments[j].type); calltip+=" "; calltip+=shader->functions[i].function->arguments[j].name; if (j==completion_argument) { calltip+=CharType(0xFFFF); } } if (shader->functions[i].function->arguments.size()) calltip+=" "; calltip+=")"; r_call_hint=calltip; return OK; } } int idx=0; String calltip; while (builtin_func_defs[idx].name) { if (completion_function==builtin_func_defs[idx].name) { if (calltip.length()) calltip+="\n"; calltip+=get_datatype_name( builtin_func_defs[idx].rettype ); calltip+=" "; calltip+=builtin_func_defs[idx].name; calltip+="("; bool found_arg=false; for(int i=0;i<4;i++) { if (builtin_func_defs[idx].args[i]==TYPE_VOID) break; if (i>0) calltip+=", "; else calltip+=" "; if (i==completion_argument) { calltip+=CharType(0xFFFF); } calltip+=get_datatype_name(builtin_func_defs[idx].args[i]); if (i==completion_argument) { calltip+=CharType(0xFFFF); } found_arg=true; } if (found_arg) calltip+=" "; calltip+=")"; } idx++; } r_call_hint=calltip; return OK; } break; case COMPLETION_INDEX: { const char colv[4]={'r','g','b','a'}; const char coordv[4]={'x','y','z','w'}; int limit=0; switch(completion_base) { case TYPE_BVEC2: case TYPE_IVEC2: case TYPE_UVEC2: case TYPE_VEC2: { limit=2; } break; case TYPE_BVEC3: case TYPE_IVEC3: case TYPE_UVEC3: case TYPE_VEC3: { limit=3; } break; case TYPE_BVEC4: case TYPE_IVEC4: case TYPE_UVEC4: case TYPE_VEC4: { limit=4; } break; case TYPE_MAT2: limit=2; break; case TYPE_MAT3: limit=3; break; case TYPE_MAT4: limit=4; break; default: {} } for(int i=0;i<limit;i++) { r_options->push_back(String::chr(colv[i])); r_options->push_back(String::chr(coordv[i])); } } break; } return ERR_PARSE_ERROR; } String ShaderLanguage::get_error_text() { return error_str; } int ShaderLanguage::get_error_line() { return error_line; } ShaderLanguage::ShaderNode *ShaderLanguage::get_shader() { return shader; } ShaderLanguage::ShaderLanguage() { nodes=NULL; } ShaderLanguage::~ShaderLanguage() { clear(); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
drivers/gles3/rasterizer_canvas_gles3.cpp
1,533
#include "rasterizer_canvas_gles3.h" #include "os/os.h" #ifdef IPHONE_ENABLED // for some reason glClearDepth seems to have been removed in iOS ES3.h #define glClearDepth glClearDepthf #endif static _FORCE_INLINE_ void store_transform2d(const Transform2D& p_mtx, float* p_array) { p_array[ 0]=p_mtx.elements[0][0]; p_array[ 1]=p_mtx.elements[0][1]; p_array[ 2]=0; p_array[ 3]=0; p_array[ 4]=p_mtx.elements[1][0]; p_array[ 5]=p_mtx.elements[1][1]; p_array[ 6]=0; p_array[ 7]=0; p_array[ 8]=0; p_array[ 9]=0; p_array[10]=1; p_array[11]=0; p_array[12]=p_mtx.elements[2][0]; p_array[13]=p_mtx.elements[2][1]; p_array[14]=0; p_array[15]=1; } static _FORCE_INLINE_ void store_transform(const Transform& p_mtx, float* p_array) { p_array[ 0]=p_mtx.basis.elements[0][0]; p_array[ 1]=p_mtx.basis.elements[1][0]; p_array[ 2]=p_mtx.basis.elements[2][0]; p_array[ 3]=0; p_array[ 4]=p_mtx.basis.elements[0][1]; p_array[ 5]=p_mtx.basis.elements[1][1]; p_array[ 6]=p_mtx.basis.elements[2][1]; p_array[ 7]=0; p_array[ 8]=p_mtx.basis.elements[0][2]; p_array[ 9]=p_mtx.basis.elements[1][2]; p_array[10]=p_mtx.basis.elements[2][2]; p_array[11]=0; p_array[12]=p_mtx.origin.x; p_array[13]=p_mtx.origin.y; p_array[14]=p_mtx.origin.z; p_array[15]=1; } static _FORCE_INLINE_ void store_camera(const CameraMatrix& p_mtx, float* p_array) { for (int i=0;i<4;i++) { for (int j=0;j<4;j++) { p_array[i*4+j]=p_mtx.matrix[i][j]; } } } RID RasterizerCanvasGLES3::light_internal_create() { LightInternal * li = memnew( LightInternal ); glGenBuffers(1, &li->ubo); glBindBuffer(GL_UNIFORM_BUFFER, li->ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(LightInternal::UBOData), &state.canvas_item_ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); return light_internal_owner.make_rid(li); } void RasterizerCanvasGLES3::light_internal_update(RID p_rid, Light* p_light) { LightInternal * li = light_internal_owner.getornull(p_rid); ERR_FAIL_COND(!li); store_transform2d(p_light->light_shader_xform,li->ubo_data.light_matrix); store_transform2d(p_light->xform_cache.affine_inverse(),li->ubo_data.local_matrix); store_camera(p_light->shadow_matrix_cache,li->ubo_data.shadow_matrix); for(int i=0;i<4;i++) { li->ubo_data.color[i]=p_light->color[i]*p_light->energy; li->ubo_data.shadow_color[i]=p_light->shadow_color[i]; } li->ubo_data.light_pos[0]=p_light->light_shader_pos.x; li->ubo_data.light_pos[1]=p_light->light_shader_pos.y; li->ubo_data.shadowpixel_size=1.0/p_light->shadow_buffer_size; li->ubo_data.light_outside_alpha=p_light->mode==VS::CANVAS_LIGHT_MODE_MASK?1.0:0.0; li->ubo_data.light_height=p_light->height; if (p_light->radius_cache==0) li->ubo_data.shadow_gradient=0; else li->ubo_data.shadow_gradient=p_light->shadow_gradient_length/(p_light->radius_cache*1.1); li->ubo_data.shadow_distance_mult=(p_light->radius_cache*1.1); glBindBuffer(GL_UNIFORM_BUFFER, li->ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0,sizeof(LightInternal::UBOData), &li->ubo_data); glBindBuffer(GL_UNIFORM_BUFFER, 0); } void RasterizerCanvasGLES3::light_internal_free(RID p_rid) { LightInternal * li = light_internal_owner.getornull(p_rid); ERR_FAIL_COND(!li); glDeleteBuffers(1,&li->ubo); light_internal_owner.free(p_rid); memdelete(li); } void RasterizerCanvasGLES3::canvas_begin(){ if (storage->frame.current_rt && storage->frame.clear_request) { // a clear request may be pending, so do it glClearColor( storage->frame.clear_request_color.r, storage->frame.clear_request_color.g, storage->frame.clear_request_color.b, storage->frame.clear_request_color.a ); glClear(GL_COLOR_BUFFER_BIT); storage->frame.clear_request=false; } /*canvas_shader.unbind(); canvas_shader.set_custom_shader(0); canvas_shader.set_conditional(CanvasShaderGLES2::USE_MODULATE,false); canvas_shader.bind(); canvas_shader.set_uniform(CanvasShaderGLES2::TEXTURE, 0); canvas_use_modulate=false;*/ reset_canvas(); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_TEXTURE_RECT,true); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD,false); state.canvas_shader.set_custom_shader(0); state.canvas_shader.bind(); state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,Color(1,1,1,1)); state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,Transform2D()); state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,Transform2D()); //state.canvas_shader.set_uniform(CanvasShaderGLES3::PROJECTION_MATRIX,state.vp); //state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,Transform()); //state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,Transform()); glBindBufferBase(GL_UNIFORM_BUFFER,0,state.canvas_item_ubo); glBindVertexArray(data.canvas_quad_array); state.using_texture_rect=true; } void RasterizerCanvasGLES3::canvas_end(){ glBindVertexArray(0); glBindBufferBase(GL_UNIFORM_BUFFER,0,0); state.using_texture_rect=false; } RasterizerStorageGLES3::Texture* RasterizerCanvasGLES3::_bind_canvas_texture(const RID& p_texture) { if (p_texture==state.current_tex) { return state.current_tex_ptr; } if (p_texture.is_valid()) { RasterizerStorageGLES3::Texture*texture=storage->texture_owner.getornull(p_texture); if (!texture) { state.current_tex=RID(); state.current_tex_ptr=NULL; glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex); return NULL; } if (texture->render_target) texture->render_target->used_in_frame=true; glBindTexture(GL_TEXTURE_2D,texture->tex_id); state.current_tex=p_texture; state.current_tex_ptr=texture; return texture; } else { glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex); state.current_tex=RID(); state.current_tex_ptr=NULL; } return NULL; } void RasterizerCanvasGLES3::_set_texture_rect_mode(bool p_enable) { if (state.using_texture_rect==p_enable) return; if (p_enable) { glBindVertexArray(data.canvas_quad_array); } else { glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); } state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_TEXTURE_RECT,p_enable); state.canvas_shader.bind(); state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,state.canvas_item_modulate); state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,state.final_transform); state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,state.extra_matrix); state.using_texture_rect=p_enable; } void RasterizerCanvasGLES3::_draw_polygon(int p_vertex_count, const int* p_indices, const Vector2* p_vertices, const Vector2* p_uvs, const Color* p_colors,const RID& p_texture,bool p_singlecolor) { bool do_colors=false; Color m; if (p_singlecolor) { m = *p_colors; glVertexAttrib4f(VS::ARRAY_COLOR,m.r,m.g,m.b,m.a); } else if (!p_colors) { glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1); } else do_colors=true; RasterizerStorageGLES3::Texture *texture = _bind_canvas_texture(p_texture); #ifndef GLES_NO_CLIENT_ARRAYS glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(Vector2), p_vertices ); if (do_colors) { glEnableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(Color), p_colors ); } else { glDisableVertexAttribArray(VS::ARRAY_COLOR); } if (texture && p_uvs) { glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(Vector2), p_uvs ); } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV); } if (p_indices) { glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_INT, p_indices ); } else { glDrawArrays(GL_TRIANGLES,0,p_vertex_count); } #else //WebGL specific impl. glBindBuffer(GL_ARRAY_BUFFER, gui_quad_buffer); float *b = GlobalVertexBuffer; int ofs = 0; if(p_vertex_count > MAX_POLYGON_VERTICES){ print_line("Too many vertices to render"); return; } glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer( VS::ARRAY_VERTEX, 2 ,GL_FLOAT, false, sizeof(float)*2, ((float*)0)+ofs ); for(int i=0;i<p_vertex_count;i++) { b[ofs++]=p_vertices[i].x; b[ofs++]=p_vertices[i].y; } if (p_colors && do_colors) { glEnableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttribPointer( VS::ARRAY_COLOR, 4 ,GL_FLOAT, false, sizeof(float)*4, ((float*)0)+ofs ); for(int i=0;i<p_vertex_count;i++) { b[ofs++]=p_colors[i].r; b[ofs++]=p_colors[i].g; b[ofs++]=p_colors[i].b; b[ofs++]=p_colors[i].a; } } else { glDisableVertexAttribArray(VS::ARRAY_COLOR); } if (p_uvs) { glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glVertexAttribPointer( VS::ARRAY_TEX_UV, 2 ,GL_FLOAT, false, sizeof(float)*2, ((float*)0)+ofs ); for(int i=0;i<p_vertex_count;i++) { b[ofs++]=p_uvs[i].x; b[ofs++]=p_uvs[i].y; } } else { glDisableVertexAttribArray(VS::ARRAY_TEX_UV); } glBufferSubData(GL_ARRAY_BUFFER,0,ofs*4,&b[0]); //bind the indices buffer. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices_buffer); static const int _max_draw_poly_indices = 16*1024; // change this size if needed!!! ERR_FAIL_COND(p_vertex_count > _max_draw_poly_indices); static uint16_t _draw_poly_indices[_max_draw_poly_indices]; for (int i=0; i<p_vertex_count; i++) { _draw_poly_indices[i] = p_indices[i]; //OS::get_singleton()->print("ind: %d ", p_indices[i]); }; //copy the data to GPU. glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, p_vertex_count * sizeof(uint16_t), &_draw_poly_indices[0]); //draw the triangles. glDrawElements(GL_TRIANGLES, p_vertex_count, GL_UNSIGNED_SHORT, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); #endif storage->frame.canvas_draw_commands++; } void RasterizerCanvasGLES3::_draw_gui_primitive(int p_points, const Vector2 *p_vertices, const Color* p_colors, const Vector2 *p_uvs) { static const GLenum prim[5]={GL_POINTS,GL_POINTS,GL_LINES,GL_TRIANGLES,GL_TRIANGLE_FAN}; //#define GLES_USE_PRIMITIVE_BUFFER int version=0; int color_ofs=0; int uv_ofs=0; int stride=2; if (p_colors) { //color version|=1; color_ofs=stride; stride+=4; } if (p_uvs) { //uv version|=2; uv_ofs=stride; stride+=2; } float b[(2+2+4)]; for(int i=0;i<p_points;i++) { b[stride*i+0]=p_vertices[i].x; b[stride*i+1]=p_vertices[i].y; } if (p_colors) { for(int i=0;i<p_points;i++) { b[stride*i+color_ofs+0]=p_colors[i].r; b[stride*i+color_ofs+1]=p_colors[i].g; b[stride*i+color_ofs+2]=p_colors[i].b; b[stride*i+color_ofs+3]=p_colors[i].a; } } if (p_uvs) { for(int i=0;i<p_points;i++) { b[stride*i+uv_ofs+0]=p_uvs[i].x; b[stride*i+uv_ofs+1]=p_uvs[i].y; } } glBindBuffer(GL_ARRAY_BUFFER,data.primitive_quad_buffer); glBufferSubData(GL_ARRAY_BUFFER,0,p_points*stride*4,&b[0]); glBindVertexArray(data.primitive_quad_buffer_arrays[version]); glDrawArrays(prim[p_points],0,p_points); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); storage->frame.canvas_draw_commands++; } void RasterizerCanvasGLES3::_canvas_item_render_commands(Item *p_item,Item *current_clip,bool &reclip) { int cc=p_item->commands.size(); Item::Command **commands = p_item->commands.ptr(); for(int i=0;i<cc;i++) { Item::Command *c=commands[i]; switch(c->type) { case Item::Command::TYPE_LINE: { Item::CommandLine* line = static_cast<Item::CommandLine*>(c); _set_texture_rect_mode(false); _bind_canvas_texture(RID()); glVertexAttrib4f(VS::ARRAY_COLOR,line->color.r,line->color.g,line->color.b,line->color.a); Vector2 verts[2]={ Vector2(line->from.x,line->from.y), Vector2(line->to.x,line->to.y) }; #ifdef GLES_OVER_GL if (line->antialiased) glEnable(GL_LINE_SMOOTH); #endif //glLineWidth(line->width); _draw_gui_primitive(2,verts,NULL,NULL); #ifdef GLES_OVER_GL if (line->antialiased) glDisable(GL_LINE_SMOOTH); #endif } break; case Item::Command::TYPE_RECT: { Item::CommandRect* rect = static_cast<Item::CommandRect*>(c); _set_texture_rect_mode(true); //set color glVertexAttrib4f(VS::ARRAY_COLOR,rect->modulate.r,rect->modulate.g,rect->modulate.b,rect->modulate.a); RasterizerStorageGLES3::Texture* texture = _bind_canvas_texture(rect->texture); if ( texture ) { bool untile=false; if (rect->flags&CANVAS_RECT_TILE && !(texture->flags&VS::TEXTURE_FLAG_REPEAT)) { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); untile=true; } Size2 texpixel_size( 1.0/texture->width, 1.0/texture->height ); Rect2 src_rect = (rect->flags&CANVAS_RECT_REGION) ? Rect2( rect->source.pos * texpixel_size, rect->source.size * texpixel_size ) : Rect2(0,0,1,1); if (rect->flags&CANVAS_RECT_FLIP_H) { src_rect.size.x*=-1; } if (rect->flags&CANVAS_RECT_FLIP_V) { src_rect.size.y*=-1; } if (rect->flags&CANVAS_RECT_TRANSPOSE) { //err.. } state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE,texpixel_size); glVertexAttrib4f(1,rect->rect.pos.x,rect->rect.pos.y,rect->rect.size.x,rect->rect.size.y); glVertexAttrib4f(2,src_rect.pos.x,src_rect.pos.y,src_rect.size.x,src_rect.size.y); glDrawArrays(GL_TRIANGLE_FAN,0,4); if (untile) { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); } } else { glVertexAttrib4f(1,rect->rect.pos.x,rect->rect.pos.y,rect->rect.size.x,rect->rect.size.y); glVertexAttrib4f(2,0,0,1,1); glDrawArrays(GL_TRIANGLE_FAN,0,4); } storage->frame.canvas_draw_commands++; } break; case Item::Command::TYPE_NINEPATCH: { Item::CommandNinePatch* np = static_cast<Item::CommandNinePatch*>(c); _set_texture_rect_mode(true); glVertexAttrib4f(VS::ARRAY_COLOR,np->color.r,np->color.g,np->color.b,np->color.a); RasterizerStorageGLES3::Texture* texture = _bind_canvas_texture(np->texture); if ( !texture ) { glVertexAttrib4f(1,np->rect.pos.x,np->rect.pos.y,np->rect.size.x,np->rect.size.y); glVertexAttrib4f(2,0,0,1,1); glDrawArrays(GL_TRIANGLE_FAN,0,4); continue; } Size2 texpixel_size( 1.0/texture->width, 1.0/texture->height ); state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE,texpixel_size); #define DSTRECT(m_x,m_y,m_w,m_h) glVertexAttrib4f(1,m_x,m_y,m_w,m_h) #define SRCRECT(m_x,m_y,m_w,m_h) glVertexAttrib4f(2,(m_x)*texpixel_size.x,(m_y)*texpixel_size.y,(m_w)*texpixel_size.x,(m_h)*texpixel_size.y) //top left DSTRECT(np->rect.pos.x,np->rect.pos.y,np->margin[MARGIN_LEFT],np->margin[MARGIN_TOP]); SRCRECT(0,0,np->margin[MARGIN_LEFT],np->margin[MARGIN_TOP]); glDrawArrays(GL_TRIANGLE_FAN,0,4); //top right DSTRECT(np->rect.pos.x+np->rect.size.x-np->margin[MARGIN_RIGHT],np->rect.pos.y,np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]); SRCRECT(texture->width-np->margin[MARGIN_RIGHT],0,np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]); glDrawArrays(GL_TRIANGLE_FAN,0,4); //bottom right DSTRECT(np->rect.pos.x+np->rect.size.x-np->margin[MARGIN_RIGHT],np->rect.pos.y+np->rect.size.y-np->margin[MARGIN_BOTTOM],np->margin[MARGIN_RIGHT],np->margin[MARGIN_BOTTOM]); SRCRECT(texture->width-np->margin[MARGIN_RIGHT],texture->height-np->margin[MARGIN_BOTTOM],np->margin[MARGIN_RIGHT],np->margin[MARGIN_BOTTOM]); glDrawArrays(GL_TRIANGLE_FAN,0,4); //bottom left DSTRECT(np->rect.pos.x,np->rect.pos.y+np->rect.size.y-np->margin[MARGIN_BOTTOM],np->margin[MARGIN_LEFT],np->margin[MARGIN_BOTTOM]); SRCRECT(0,texture->height-np->margin[MARGIN_BOTTOM],np->margin[MARGIN_LEFT],np->margin[MARGIN_BOTTOM]); glDrawArrays(GL_TRIANGLE_FAN,0,4); //top DSTRECT(np->rect.pos.x+np->margin[MARGIN_LEFT],np->rect.pos.y,np->rect.size.width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]); SRCRECT(np->margin[MARGIN_LEFT],0,texture->width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]); glDrawArrays(GL_TRIANGLE_FAN,0,4); //bottom DSTRECT(np->rect.pos.x+np->margin[MARGIN_LEFT],np->rect.pos.y+np->rect.size.y-np->margin[MARGIN_BOTTOM],np->rect.size.width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP]); SRCRECT(np->margin[MARGIN_LEFT],texture->height-np->margin[MARGIN_BOTTOM],texture->width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_LEFT],np->margin[MARGIN_TOP]); glDrawArrays(GL_TRIANGLE_FAN,0,4); //left DSTRECT(np->rect.pos.x,np->rect.pos.y+np->margin[MARGIN_TOP],np->margin[MARGIN_LEFT],np->rect.size.height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]); SRCRECT(0,np->margin[MARGIN_TOP],np->margin[MARGIN_LEFT],texture->height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]); glDrawArrays(GL_TRIANGLE_FAN,0,4); //right DSTRECT(np->rect.pos.x+np->rect.size.width-np->margin[MARGIN_RIGHT],np->rect.pos.y+np->margin[MARGIN_TOP],np->margin[MARGIN_RIGHT],np->rect.size.height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]); SRCRECT(texture->width-np->margin[MARGIN_RIGHT],np->margin[MARGIN_TOP],np->margin[MARGIN_RIGHT],texture->height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]); glDrawArrays(GL_TRIANGLE_FAN,0,4); if (np->draw_center) { //center DSTRECT(np->rect.pos.x+np->margin[MARGIN_LEFT],np->rect.pos.y+np->margin[MARGIN_TOP],np->rect.size.x-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],np->rect.size.height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]); SRCRECT(np->margin[MARGIN_LEFT],np->margin[MARGIN_TOP],texture->width-np->margin[MARGIN_LEFT]-np->margin[MARGIN_RIGHT],texture->height-np->margin[MARGIN_TOP]-np->margin[MARGIN_BOTTOM]); glDrawArrays(GL_TRIANGLE_FAN,0,4); } #undef SRCRECT #undef DSTRECT storage->frame.canvas_draw_commands++; } break; case Item::Command::TYPE_PRIMITIVE: { Item::CommandPrimitive* primitive = static_cast<Item::CommandPrimitive*>(c); _set_texture_rect_mode(false); ERR_CONTINUE( primitive->points.size()<1); RasterizerStorageGLES3::Texture* texture = _bind_canvas_texture(primitive->texture); if (texture ) { Size2 texpixel_size( 1.0/texture->width, 1.0/texture->height ); state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE,texpixel_size); } if (primitive->colors.size()==1 && primitive->points.size()>1) { Color c = primitive->colors[0]; glVertexAttrib4f(VS::ARRAY_COLOR,c.r,c.g,c.b,c.a); } else if (primitive->colors.empty()) { glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1); } _draw_gui_primitive(primitive->points.size(),primitive->points.ptr(),primitive->colors.ptr(),primitive->uvs.ptr()); } break; case Item::Command::TYPE_POLYGON: { Item::CommandPolygon* polygon = static_cast<Item::CommandPolygon*>(c); _set_texture_rect_mode(false); RasterizerStorageGLES3::Texture* texture = _bind_canvas_texture(polygon->texture); if (texture ) { Size2 texpixel_size( 1.0/texture->width, 1.0/texture->height ); state.canvas_shader.set_uniform(CanvasShaderGLES3::COLOR_TEXPIXEL_SIZE,texpixel_size); } _draw_polygon(polygon->count,polygon->indices.ptr(),polygon->points.ptr(),polygon->uvs.ptr(),polygon->colors.ptr(),polygon->texture,polygon->colors.size()==1); } break; case Item::Command::TYPE_CIRCLE: { _set_texture_rect_mode(false); Item::CommandCircle* circle = static_cast<Item::CommandCircle*>(c); static const int numpoints=32; Vector2 points[numpoints+1]; points[numpoints]=circle->pos; int indices[numpoints*3]; for(int i=0;i<numpoints;i++) { points[i]=circle->pos+Vector2( Math::sin(i*Math_PI*2.0/numpoints),Math::cos(i*Math_PI*2.0/numpoints) )*circle->radius; indices[i*3+0]=i; indices[i*3+1]=(i+1)%numpoints; indices[i*3+2]=numpoints; } _draw_polygon(numpoints*3,indices,points,NULL,&circle->color,RID(),true); //canvas_draw_circle(circle->indices.size(),circle->indices.ptr(),circle->points.ptr(),circle->uvs.ptr(),circle->colors.ptr(),circle->texture,circle->colors.size()==1); } break; case Item::Command::TYPE_TRANSFORM: { Item::CommandTransform* transform = static_cast<Item::CommandTransform*>(c); state.extra_matrix=transform->xform; state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,state.extra_matrix); } break; case Item::Command::TYPE_CLIP_IGNORE: { Item::CommandClipIgnore* ci = static_cast<Item::CommandClipIgnore*>(c); if (current_clip) { if (ci->ignore!=reclip) { if (ci->ignore) { glDisable(GL_SCISSOR_TEST); reclip=true; } else { glEnable(GL_SCISSOR_TEST); //glScissor(viewport.x+current_clip->final_clip_rect.pos.x,viewport.y+ (viewport.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)), //current_clip->final_clip_rect.size.width,current_clip->final_clip_rect.size.height); int x = current_clip->final_clip_rect.pos.x; int y = storage->frame.current_rt->height - ( current_clip->final_clip_rect.pos.y + current_clip->final_clip_rect.size.y ); int w = current_clip->final_clip_rect.size.x; int h = current_clip->final_clip_rect.size.y; glScissor(x,y,w,h); reclip=false; } } } } break; } } } #if 0 void RasterizerGLES2::_canvas_item_setup_shader_params(CanvasItemMaterial *material,Shader* shader) { if (canvas_shader.bind()) rebind_texpixel_size=true; if (material->shader_version!=shader->version) { //todo optimize uniforms material->shader_version=shader->version; } if (shader->has_texscreen && framebuffer.active) { int x = viewport.x; int y = window_size.height-(viewport.height+viewport.y); canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_MULT,Vector2(float(viewport.width)/framebuffer.width,float(viewport.height)/framebuffer.height)); canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_CLAMP,Color(float(x)/framebuffer.width,float(y)/framebuffer.height,float(x+viewport.width)/framebuffer.width,float(y+viewport.height)/framebuffer.height)); canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_TEX,max_texture_units-1); glActiveTexture(GL_TEXTURE0+max_texture_units-1); glBindTexture(GL_TEXTURE_2D,framebuffer.sample_color); if (framebuffer.scale==1 && !canvas_texscreen_used) { #ifdef GLEW_ENABLED if (current_rt) { glReadBuffer(GL_COLOR_ATTACHMENT0); } else { glReadBuffer(GL_BACK); } #endif if (current_rt) { glCopyTexSubImage2D(GL_TEXTURE_2D,0,viewport.x,viewport.y,viewport.x,viewport.y,viewport.width,viewport.height); canvas_shader.set_uniform(CanvasShaderGLES2::TEXSCREEN_SCREEN_CLAMP,Color(float(x)/framebuffer.width,float(viewport.y)/framebuffer.height,float(x+viewport.width)/framebuffer.width,float(y+viewport.height)/framebuffer.height)); //window_size.height-(viewport.height+viewport.y) } else { glCopyTexSubImage2D(GL_TEXTURE_2D,0,x,y,x,y,viewport.width,viewport.height); } canvas_texscreen_used=true; } glActiveTexture(GL_TEXTURE0); } if (shader->has_screen_uv) { canvas_shader.set_uniform(CanvasShaderGLES2::SCREEN_UV_MULT,Vector2(1.0/viewport.width,1.0/viewport.height)); } uses_texpixel_size=shader->uses_texpixel_size; } #endif void RasterizerCanvasGLES3::canvas_render_items(Item *p_item_list,int p_z,const Color& p_modulate,Light *p_light) { Item *current_clip=NULL; RasterizerStorageGLES3::Shader *shader_cache=NULL; bool rebind_shader=true; Size2 rt_size = Size2(storage->frame.current_rt->width,storage->frame.current_rt->height); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD,false); glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_item_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(CanvasItemUBO), &state.canvas_item_ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.current_tex=RID(); state.current_tex_ptr=NULL; glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex); int last_blend_mode=-1; RID canvas_last_material; bool prev_distance_field=false; while(p_item_list) { Item *ci=p_item_list; if (prev_distance_field!=ci->distance_field) { state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_DISTANCE_FIELD,ci->distance_field); prev_distance_field=ci->distance_field; rebind_shader=true; } if (current_clip!=ci->final_clip_owner) { current_clip=ci->final_clip_owner; //setup clip if (current_clip) { glEnable(GL_SCISSOR_TEST); glScissor(current_clip->final_clip_rect.pos.x,(rt_size.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)),current_clip->final_clip_rect.size.width,current_clip->final_clip_rect.size.height); } else { glDisable(GL_SCISSOR_TEST); } } #if 0 if (ci->copy_back_buffer && framebuffer.active && framebuffer.scale==1) { Rect2 rect; int x,y; if (ci->copy_back_buffer->full) { x = viewport.x; y = window_size.height-(viewport.height+viewport.y); } else { x = viewport.x+ci->copy_back_buffer->screen_rect.pos.x; y = window_size.height-(viewport.y+ci->copy_back_buffer->screen_rect.pos.y+ci->copy_back_buffer->screen_rect.size.y); } glActiveTexture(GL_TEXTURE0+max_texture_units-1); glBindTexture(GL_TEXTURE_2D,framebuffer.sample_color); #ifdef GLEW_ENABLED if (current_rt) { glReadBuffer(GL_COLOR_ATTACHMENT0); } else { glReadBuffer(GL_BACK); } #endif if (current_rt) { glCopyTexSubImage2D(GL_TEXTURE_2D,0,viewport.x,viewport.y,viewport.x,viewport.y,viewport.width,viewport.height); //window_size.height-(viewport.height+viewport.y) } else { glCopyTexSubImage2D(GL_TEXTURE_2D,0,x,y,x,y,viewport.width,viewport.height); } canvas_texscreen_used=true; glActiveTexture(GL_TEXTURE0); } #endif //begin rect Item *material_owner = ci->material_owner?ci->material_owner:ci; RID material = material_owner->material; if (material!=canvas_last_material || rebind_shader) { RasterizerStorageGLES3::Material *material_ptr = storage->material_owner.getornull(material); RasterizerStorageGLES3::Shader *shader_ptr = NULL; if (material_ptr) { shader_ptr = material_ptr->shader; if (shader_ptr && shader_ptr->mode!=VS::SHADER_CANVAS_ITEM) { shader_ptr=NULL; //do not use non canvasitem shader } } if (shader_ptr && shader_ptr!=shader_cache) { state.canvas_shader.set_custom_shader(shader_ptr->custom_code_id); state.canvas_shader.bind(); if (material_ptr->ubo_id) { glBindBufferBase(GL_UNIFORM_BUFFER,2,material_ptr->ubo_id); } int tc = material_ptr->textures.size(); RID* textures = material_ptr->textures.ptr(); ShaderLanguage::ShaderNode::Uniform::Hint* texture_hints = shader_ptr->texture_hints.ptr(); for(int i=0;i<tc;i++) { glActiveTexture(GL_TEXTURE1+i); RasterizerStorageGLES3::Texture *t = storage->texture_owner.getornull( textures[i] ); if (!t) { switch(texture_hints[i]) { case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK_ALBEDO: case ShaderLanguage::ShaderNode::Uniform::HINT_BLACK: { glBindTexture(GL_TEXTURE_2D,storage->resources.black_tex); } break; case ShaderLanguage::ShaderNode::Uniform::HINT_ANISO: { glBindTexture(GL_TEXTURE_2D,storage->resources.aniso_tex); } break; case ShaderLanguage::ShaderNode::Uniform::HINT_NORMAL: { glBindTexture(GL_TEXTURE_2D,storage->resources.normal_tex); } break; default: { glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex); } break; } //check hints continue; } if (storage->config.srgb_decode_supported && t->using_srgb) { //no srgb in 2D glTexParameteri(t->target,_TEXTURE_SRGB_DECODE_EXT,_SKIP_DECODE_EXT); t->using_srgb=false; } glBindTexture(t->target,t->tex_id); } } else if (!shader_ptr) { state.canvas_shader.set_custom_shader(0); state.canvas_shader.bind(); } shader_cache=shader_ptr; canvas_last_material=material; rebind_shader=false; } int blend_mode = shader_cache ? shader_cache->canvas_item.blend_mode : RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX; bool unshaded = shader_cache && (shader_cache->canvas_item.light_mode==RasterizerStorageGLES3::Shader::CanvasItem::LIGHT_MODE_UNSHADED || blend_mode!=RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX); bool reclip=false; if (last_blend_mode!=blend_mode) { switch(blend_mode) { case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX: { glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } break; case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_ADD: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA,GL_ONE); } break; case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_SUB: { glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); glBlendFunc(GL_SRC_ALPHA,GL_ONE); } break; case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MUL: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_DST_COLOR,GL_ZERO); } break; case RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_PMALPHA: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_ONE,GL_ONE_MINUS_SRC_ALPHA); } break; } last_blend_mode=blend_mode; } state.canvas_item_modulate = unshaded ? ci->final_modulate : Color( ci->final_modulate.r * p_modulate.r, ci->final_modulate.g * p_modulate.g, ci->final_modulate.b * p_modulate.b, ci->final_modulate.a * p_modulate.a ); state.final_transform = ci->final_transform; state.extra_matrix=Transform2D(); state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,state.canvas_item_modulate); state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,state.final_transform); state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,state.extra_matrix); if (unshaded || (state.canvas_item_modulate.a>0.001 && (!shader_cache || shader_cache->canvas_item.light_mode!=RasterizerStorageGLES3::Shader::CanvasItem::LIGHT_MODE_LIGHT_ONLY) && !ci->light_masked )) _canvas_item_render_commands(ci,current_clip,reclip); if ((blend_mode==RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_MIX || RasterizerStorageGLES3::Shader::CanvasItem::BLEND_MODE_PMALPHA) && p_light && !unshaded) { Light *light = p_light; bool light_used=false; VS::CanvasLightMode mode=VS::CANVAS_LIGHT_MODE_ADD; state.canvas_item_modulate=ci->final_modulate; // remove the canvas modulate while(light) { if (ci->light_mask&light->item_mask && p_z>=light->z_min && p_z<=light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache,light->rect_cache)) { //intersects this light if (!light_used || mode!=light->mode) { mode=light->mode; switch(mode) { case VS::CANVAS_LIGHT_MODE_ADD: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA,GL_ONE); } break; case VS::CANVAS_LIGHT_MODE_SUB: { glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); glBlendFunc(GL_SRC_ALPHA,GL_ONE); } break; case VS::CANVAS_LIGHT_MODE_MIX: case VS::CANVAS_LIGHT_MODE_MASK: { glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } break; } } if (!light_used) { state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING,true); light_used=true; } bool has_shadow = light->shadow_buffer.is_valid() && ci->light_mask&light->item_shadow_mask; state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS,has_shadow); if (has_shadow) { state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_USE_GRADIENT,light->shadow_gradient_length>0); switch(light->shadow_filter) { case VS::CANVAS_LIGHT_FILTER_NONE: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST,true); break; case VS::CANVAS_LIGHT_FILTER_PCF3: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF3,true); break; case VS::CANVAS_LIGHT_FILTER_PCF5: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5,true); break; case VS::CANVAS_LIGHT_FILTER_PCF9: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF9,true); break; case VS::CANVAS_LIGHT_FILTER_PCF13: state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13,true); break; } } bool light_rebind = state.canvas_shader.bind(); if (light_rebind) { state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,state.canvas_item_modulate); state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,state.final_transform); state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,Transform2D()); } glBindBufferBase(GL_UNIFORM_BUFFER,1,static_cast<LightInternal*>(light->light_internal.get_data())->ubo); if (has_shadow) { RasterizerStorageGLES3::CanvasLightShadow *cls = storage->canvas_light_shadow_owner.get(light->shadow_buffer); glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-2); glBindTexture(GL_TEXTURE_2D,cls->distance); /*canvas_shader.set_uniform(CanvasShaderGLES3::SHADOW_MATRIX,light->shadow_matrix_cache); canvas_shader.set_uniform(CanvasShaderGLES3::SHADOW_ESM_MULTIPLIER,light->shadow_esm_mult); canvas_shader.set_uniform(CanvasShaderGLES3::LIGHT_SHADOW_COLOR,light->shadow_color);*/ } glActiveTexture(GL_TEXTURE0+storage->config.max_texture_image_units-1); RasterizerStorageGLES3::Texture *t = storage->texture_owner.getornull(light->texture); if (!t) { glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex); } else { glBindTexture(t->target,t->tex_id); } glActiveTexture(GL_TEXTURE0); _canvas_item_render_commands(ci,current_clip,reclip); //redraw using light } light=light->next_ptr; } if (light_used) { state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_LIGHTING,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_SHADOWS,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_NEAREST,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF3,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF5,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF9,false); state.canvas_shader.set_conditional(CanvasShaderGLES3::SHADOW_FILTER_PCF13,false); state.canvas_shader.bind(); last_blend_mode=-1; /* //this is set again, so it should not be needed anyway? state.canvas_item_modulate = unshaded ? ci->final_modulate : Color( ci->final_modulate.r * p_modulate.r, ci->final_modulate.g * p_modulate.g, ci->final_modulate.b * p_modulate.b, ci->final_modulate.a * p_modulate.a ); state.canvas_shader.set_uniform(CanvasShaderGLES3::MODELVIEW_MATRIX,state.final_transform); state.canvas_shader.set_uniform(CanvasShaderGLES3::EXTRA_MATRIX,Transform2D()); state.canvas_shader.set_uniform(CanvasShaderGLES3::FINAL_MODULATE,state.canvas_item_modulate); glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } //@TODO RESET canvas_blend_mode */ } } if (reclip) { glEnable(GL_SCISSOR_TEST); glScissor(current_clip->final_clip_rect.pos.x,(rt_size.height-(current_clip->final_clip_rect.pos.y+current_clip->final_clip_rect.size.height)),current_clip->final_clip_rect.size.width,current_clip->final_clip_rect.size.height); } p_item_list=p_item_list->next; } if (current_clip) { glDisable(GL_SCISSOR_TEST); } } void RasterizerCanvasGLES3::canvas_debug_viewport_shadows(Light* p_lights_with_shadow){ Light* light=p_lights_with_shadow; canvas_begin(); //reset glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1); int h = 10; int w = storage->frame.current_rt->width; int ofs = h; glDisable(GL_BLEND); //print_line(" debug lights "); while(light) { //print_line("debug light"); if (light->shadow_buffer.is_valid()) { //print_line("sb is valid"); RasterizerStorageGLES3::CanvasLightShadow * sb = storage->canvas_light_shadow_owner.get(light->shadow_buffer); if (sb) { glBindTexture(GL_TEXTURE_2D,sb->distance); //glBindTexture(GL_TEXTURE_2D,storage->resources.white_tex); draw_generic_textured_rect(Rect2(h,ofs,w-h*2,h),Rect2(0,0,1,1)); ofs+=h*2; } } light=light->shadows_next_ptr; } } void RasterizerCanvasGLES3::canvas_light_shadow_buffer_update(RID p_buffer, const Transform2D& p_light_xform, int p_light_mask,float p_near, float p_far, LightOccluderInstance* p_occluders, CameraMatrix *p_xform_cache) { RasterizerStorageGLES3::CanvasLightShadow *cls = storage->canvas_light_shadow_owner.get(p_buffer); ERR_FAIL_COND(!cls); glDisable(GL_BLEND); glDisable(GL_SCISSOR_TEST); glDisable(GL_DITHER); glDisable(GL_CULL_FACE); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); glDepthMask(true); glBindFramebuffer(GL_FRAMEBUFFER, cls->fbo); glEnableVertexAttribArray(VS::ARRAY_VERTEX); state.canvas_shadow_shader.bind(); glViewport(0, 0, cls->size,cls->height); glClearDepth(1.0f); glClearColor(1,1,1,1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); VS::CanvasOccluderPolygonCullMode cull=VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED; for(int i=0;i<4;i++) { //make sure it remains orthogonal, makes easy to read angle later Transform light; light.origin[0]=p_light_xform[2][0]; light.origin[1]=p_light_xform[2][1]; light.basis[0][0]=p_light_xform[0][0]; light.basis[0][1]=p_light_xform[1][0]; light.basis[1][0]=p_light_xform[0][1]; light.basis[1][1]=p_light_xform[1][1]; //light.basis.scale(Vector3(to_light.elements[0].length(),to_light.elements[1].length(),1)); //p_near=1; CameraMatrix projection; { real_t fov = 90; real_t nearp = p_near; real_t farp = p_far; real_t aspect = 1.0; real_t ymax = nearp * Math::tan( Math::deg2rad( fov * 0.5 ) ); real_t ymin = - ymax; real_t xmin = ymin * aspect; real_t xmax = ymax * aspect; projection.set_frustum( xmin, xmax, ymin, ymax, nearp, farp ); } Vector3 cam_target=Basis(Vector3(0,0,Math_PI*2*(i/4.0))).xform(Vector3(0,1,0)); projection = projection * CameraMatrix(Transform().looking_at(cam_target,Vector3(0,0,-1)).affine_inverse()); state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::PROJECTION_MATRIX,projection); state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::LIGHT_MATRIX,light); state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::DISTANCE_NORM,1.0/p_far); if (i==0) *p_xform_cache=projection; glViewport(0, (cls->height/4)*i, cls->size,cls->height/4); LightOccluderInstance *instance=p_occluders; while(instance) { RasterizerStorageGLES3::CanvasOccluder *cc = storage->canvas_occluder_owner.get(instance->polygon_buffer); if (!cc || cc->len==0 || !(p_light_mask&instance->light_mask)) { instance=instance->next; continue; } state.canvas_shadow_shader.set_uniform(CanvasShadowShaderGLES3::WORLD_MATRIX,instance->xform_cache); if (cull!=instance->cull_cache) { cull=instance->cull_cache; switch(cull) { case VS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED: { glDisable(GL_CULL_FACE); } break; case VS::CANVAS_OCCLUDER_POLYGON_CULL_CLOCKWISE: { glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); } break; case VS::CANVAS_OCCLUDER_POLYGON_CULL_COUNTER_CLOCKWISE: { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } break; } } /* if (i==0) { for(int i=0;i<cc->lines.size();i++) { Vector2 p = instance->xform_cache.xform(cc->lines.get(i)); Plane pp(Vector3(p.x,p.y,0),1); pp.normal = light.xform(pp.normal); pp = projection.xform4(pp); print_line(itos(i)+": "+pp.normal/pp.d); //pp=light_mat.xform4(pp); //print_line(itos(i)+": "+pp.normal/pp.d); } } */ glBindBuffer(GL_ARRAY_BUFFER,cc->vertex_id); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,cc->index_id); glVertexAttribPointer(VS::ARRAY_VERTEX, 3, GL_FLOAT, false, 0, 0); glDrawElements(GL_TRIANGLES,cc->len*3,GL_UNSIGNED_SHORT,0); instance=instance->next; } } glDisableVertexAttribArray(VS::ARRAY_VERTEX); glBindBuffer(GL_ARRAY_BUFFER,0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); } void RasterizerCanvasGLES3::reset_canvas() { if (storage->frame.current_rt) { glBindFramebuffer(GL_FRAMEBUFFER, storage->frame.current_rt->fbo); glColorMask(1,1,1,1); //don't touch alpha } glBindVertexArray(0); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_TRANSPARENT]) { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } else { glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } //glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); //glLineWidth(1.0); glBindBuffer(GL_ARRAY_BUFFER,0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0); for(int i=0;i<VS::ARRAY_MAX;i++) { glDisableVertexAttribArray(i); } glActiveTexture(GL_TEXTURE0); glBindTexture( GL_TEXTURE_2D, storage->resources.white_tex ); glVertexAttrib4f(VS::ARRAY_COLOR,1,1,1,1); Transform canvas_transform; if (storage->frame.current_rt) { float csy = 1.0; if (storage->frame.current_rt && storage->frame.current_rt->flags[RasterizerStorage::RENDER_TARGET_VFLIP]) { csy = -1.0; } canvas_transform.translate(-(storage->frame.current_rt->width / 2.0f), -(storage->frame.current_rt->height / 2.0f), 0.0f); canvas_transform.scale( Vector3( 2.0f / storage->frame.current_rt->width, csy * -2.0f / storage->frame.current_rt->height, 1.0f ) ); } else { Vector2 ssize = OS::get_singleton()->get_window_size(); canvas_transform.translate(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f); canvas_transform.scale( Vector3( 2.0f / ssize.width, -2.0f / ssize.height, 1.0f ) ); } state.vp=canvas_transform; store_transform(canvas_transform,state.canvas_item_ubo_data.projection_matrix); for(int i=0;i<4;i++) { state.canvas_item_ubo_data.time[i]=storage->frame.time[i]; } glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_item_ubo); glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(CanvasItemUBO), &state.canvas_item_ubo_data); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.canvas_texscreen_used=false; } void RasterizerCanvasGLES3::draw_generic_textured_rect(const Rect2& p_rect, const Rect2& p_src) { glVertexAttrib4f(1,p_rect.pos.x,p_rect.pos.y,p_rect.size.x,p_rect.size.y); glVertexAttrib4f(2,p_src.pos.x,p_src.pos.y,p_src.size.x,p_src.size.y); glDrawArrays(GL_TRIANGLE_FAN,0,4); } void RasterizerCanvasGLES3::initialize() { { //quad buffers glGenBuffers(1,&data.canvas_quad_vertices); glBindBuffer(GL_ARRAY_BUFFER,data.canvas_quad_vertices); { const float qv[8]={ 0,0, 0,1, 1,1, 1,0 }; glBufferData(GL_ARRAY_BUFFER,sizeof(float)*8,qv,GL_STATIC_DRAW); } glBindBuffer(GL_ARRAY_BUFFER,0); //unbind glGenVertexArrays(1,&data.canvas_quad_array); glBindVertexArray(data.canvas_quad_array); glBindBuffer(GL_ARRAY_BUFFER,data.canvas_quad_vertices); glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,sizeof(float)*2,0); glEnableVertexAttribArray(0); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER,0); //unbind } { glGenBuffers(1,&data.primitive_quad_buffer); glBindBuffer(GL_ARRAY_BUFFER,data.primitive_quad_buffer); glBufferData(GL_ARRAY_BUFFER,sizeof(float)*2+sizeof(float)*2+sizeof(float)*4,NULL,GL_DYNAMIC_DRAW); //allocate max size glBindBuffer(GL_ARRAY_BUFFER,0); for(int i=0;i<4;i++) { glGenVertexArrays(1,&data.primitive_quad_buffer_arrays[i]); glBindVertexArray(data.primitive_quad_buffer_arrays[i]); glBindBuffer(GL_ARRAY_BUFFER,data.primitive_quad_buffer); int uv_ofs=0; int color_ofs=0; int stride=2*4; if (i&1) { //color color_ofs=stride; stride+=4*4; } if (i&2) { //uv uv_ofs=stride; stride+=2*4; } glEnableVertexAttribArray(VS::ARRAY_VERTEX); glVertexAttribPointer(VS::ARRAY_VERTEX,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+0); if (i&1) { glEnableVertexAttribArray(VS::ARRAY_COLOR); glVertexAttribPointer(VS::ARRAY_COLOR,4,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+color_ofs); } if (i&2) { glEnableVertexAttribArray(VS::ARRAY_TEX_UV); glVertexAttribPointer(VS::ARRAY_TEX_UV,2,GL_FLOAT,GL_FALSE,stride,((uint8_t*)NULL)+uv_ofs); } glBindVertexArray(0); } } store_transform(Transform(),state.canvas_item_ubo_data.projection_matrix); glGenBuffers(1, &state.canvas_item_ubo); glBindBuffer(GL_UNIFORM_BUFFER, state.canvas_item_ubo); glBufferData(GL_UNIFORM_BUFFER, sizeof(CanvasItemUBO), &state.canvas_item_ubo_data, GL_DYNAMIC_DRAW); glBindBuffer(GL_UNIFORM_BUFFER, 0); state.canvas_shader.init(); state.canvas_shader.set_base_material_tex_index(1); state.canvas_shadow_shader.init(); state.canvas_shader.set_conditional(CanvasShaderGLES3::USE_RGBA_SHADOWS,storage->config.use_rgba_2d_shadows); state.canvas_shadow_shader.set_conditional(CanvasShadowShaderGLES3::USE_RGBA_SHADOWS,storage->config.use_rgba_2d_shadows); } void RasterizerCanvasGLES3::finalize() { glDeleteBuffers(1,&data.canvas_quad_vertices); glDeleteVertexArrays(1,&data.canvas_quad_array); } RasterizerCanvasGLES3::RasterizerCanvasGLES3() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
drivers/windows/rw_lock_windows.cpp
72
#if defined(WINDOWS_ENABLED) #include "os/memory.h" #include "rw_lock_windows.h" #include "error_macros.h" #include <stdio.h> void RWLockWindows::read_lock() { AcquireSRWLockShared(&lock); } void RWLockWindows::read_unlock() { ReleaseSRWLockShared(&lock); } Error RWLockWindows::read_try_lock() { if (TryAcquireSRWLockShared(&lock)==0) { return ERR_BUSY; } else { return OK; } } void RWLockWindows::write_lock() { AcquireSRWLockExclusive(&lock); } void RWLockWindows::write_unlock() { ReleaseSRWLockExclusive(&lock); } Error RWLockWindows::write_try_lock() { if (TryAcquireSRWLockExclusive(&lock)==0) { return ERR_BUSY; } else { return OK; } } RWLock *RWLockWindows::create_func_windows() { return memnew( RWLockWindows ); } void RWLockWindows::make_default() { create_func=create_func_windows; } RWLockWindows::RWLockWindows() { InitializeSRWLock(&lock); } RWLockWindows::~RWLockWindows() { } #endif
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_chorus.cpp
365
#include "audio_effect_chorus.h" #include "servers/audio_server.h" #include "math_funcs.h" void AudioEffectChorusInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { int todo = p_frame_count; while(todo) { int to_mix = MIN(todo,256); //can't mix too much _process_chunk(p_src_frames,p_dst_frames,to_mix); p_src_frames+=to_mix; p_dst_frames+=to_mix; todo-=to_mix; } } void AudioEffectChorusInstance::_process_chunk(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { //fill ringbuffer for(int i=0;i<p_frame_count;i++) { audio_buffer[(buffer_pos+i)&buffer_mask]=p_src_frames[i]; p_dst_frames[i]=p_src_frames[i]*base->dry; } float mix_rate = AudioServer::get_singleton()->get_mix_rate(); /* process voices */ for (int vc=0;vc<base->voice_count;vc++) { AudioEffectChorus::Voice &v=base->voice[vc]; double time_to_mix=(float)p_frame_count/mix_rate; double cycles_to_mix=time_to_mix*v.rate; unsigned int local_rb_pos=buffer_pos; AudioFrame *dst_buff=p_dst_frames; AudioFrame *rb_buff=audio_buffer.ptr(); double delay_msec=v.delay; unsigned int delay_frames=Math::fast_ftoi((delay_msec/1000.0)*mix_rate); float max_depth_frames=(v.depth/1000.0)*mix_rate; uint64_t local_cycles=cycles[vc]; uint64_t increment=llrint(cycles_to_mix/(double)p_frame_count*(double)(1<<AudioEffectChorus::CYCLES_FRAC)); //check the LFO doesnt read ahead of the write pos if ((((int)max_depth_frames)+10)>delay_frames) { //10 as some threshold to avoid precision stuff delay_frames+=(int)max_depth_frames-delay_frames; delay_frames+=10; //threshold to avoid precision stuff } //low pass filter if (v.cutoff==0) continue; float auxlp=expf(-2.0*Math_PI*v.cutoff/mix_rate); float c1=1.0-auxlp; float c2=auxlp; AudioFrame h=filter_h[vc]; if (v.cutoff>=AudioEffectChorus::MS_CUTOFF_MAX) { c1=1.0; c2=0.0; } //vol modifier AudioFrame vol_modifier=AudioFrame(base->wet,base->wet) * Math::db2linear(v.level); vol_modifier.l*=CLAMP( 1.0 - v.pan, 0, 1); vol_modifier.r*=CLAMP( 1.0 + v.pan, 0, 1); for (int i=0;i<p_frame_count;i++) { /** COMPUTE WAVEFORM **/ float phase=(float)(local_cycles&AudioEffectChorus::CYCLES_MASK)/(float)(1<<AudioEffectChorus::CYCLES_FRAC); float wave_delay=sinf(phase*2.0*Math_PI)*max_depth_frames; int wave_delay_frames=lrint(floor(wave_delay)); float wave_delay_frac=wave_delay-(float)wave_delay_frames; /** COMPUTE RINGBUFFER POS**/ unsigned int rb_source=local_rb_pos; rb_source-=delay_frames; rb_source-=wave_delay_frames; /** READ FROM RINGBUFFER, LINEARLY INTERPOLATE */ AudioFrame val=rb_buff[rb_source&buffer_mask]; AudioFrame val_next=rb_buff[(rb_source-1)&buffer_mask]; val+=(val_next-val)*wave_delay_frac; val=val*c1+h*c2; h=val; /** MIX VALUE TO OUTPUT **/ dst_buff[i]+=val*vol_modifier; local_cycles+=increment; local_rb_pos++; } filter_h[vc]=h; cycles[vc]+=Math::fast_ftoi(cycles_to_mix*(double)(1<<AudioEffectChorus::CYCLES_FRAC)); } buffer_pos+=p_frame_count; } Ref<AudioEffectInstance> AudioEffectChorus::instance() { Ref<AudioEffectChorusInstance> ins; ins.instance(); ins->base=Ref<AudioEffectChorus>(this); for(int i=0;i<4;i++) { ins->filter_h[i]=AudioFrame(0,0); ins->cycles[i]=0; } float ring_buffer_max_size=AudioEffectChorus::MAX_DELAY_MS+AudioEffectChorus::MAX_DEPTH_MS+AudioEffectChorus::MAX_WIDTH_MS; ring_buffer_max_size*=2; //just to avoid complications ring_buffer_max_size/=1000.0;//convert to seconds ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate(); int ringbuff_size=ring_buffer_max_size; int bits=0; while(ringbuff_size>0) { bits++; ringbuff_size/=2; } ringbuff_size=1<<bits; ins->buffer_mask=ringbuff_size-1; ins->buffer_pos=0; ins->audio_buffer.resize(ringbuff_size); for(int i=0;i<ringbuff_size;i++) { ins->audio_buffer[i]=AudioFrame(0,0); } return ins; } void AudioEffectChorus::set_voice_count(int p_voices) { ERR_FAIL_COND(p_voices<1 || p_voices>=MAX_VOICES); voice_count=p_voices; _change_notify(); } int AudioEffectChorus::get_voice_count() const{ return voice_count; } void AudioEffectChorus::set_voice_delay_ms(int p_voice,float p_delay_ms){ ERR_FAIL_INDEX(p_voice,MAX_VOICES); voice[p_voice].delay=p_delay_ms; } float AudioEffectChorus::get_voice_delay_ms(int p_voice) const{ ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); return voice[p_voice].delay; } void AudioEffectChorus::set_voice_rate_hz(int p_voice,float p_rate_hz){ ERR_FAIL_INDEX(p_voice,MAX_VOICES); voice[p_voice].rate=p_rate_hz; } float AudioEffectChorus::get_voice_rate_hz(int p_voice) const{ ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); return voice[p_voice].rate; } void AudioEffectChorus::set_voice_depth_ms(int p_voice,float p_depth_ms){ ERR_FAIL_INDEX(p_voice,MAX_VOICES); voice[p_voice].depth=p_depth_ms; } float AudioEffectChorus::get_voice_depth_ms(int p_voice) const{ ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); return voice[p_voice].depth; } void AudioEffectChorus::set_voice_level_db(int p_voice,float p_level_db){ ERR_FAIL_INDEX(p_voice,MAX_VOICES); voice[p_voice].level=p_level_db; } float AudioEffectChorus::get_voice_level_db(int p_voice) const{ ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); return voice[p_voice].level; } void AudioEffectChorus::set_voice_cutoff_hz(int p_voice,float p_cutoff_hz){ ERR_FAIL_INDEX(p_voice,MAX_VOICES); voice[p_voice].cutoff=p_cutoff_hz; } float AudioEffectChorus::get_voice_cutoff_hz(int p_voice) const{ ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); return voice[p_voice].cutoff; } void AudioEffectChorus::set_voice_pan(int p_voice,float p_pan){ ERR_FAIL_INDEX(p_voice,MAX_VOICES); voice[p_voice].pan=p_pan; } float AudioEffectChorus::get_voice_pan(int p_voice) const{ ERR_FAIL_INDEX_V(p_voice,MAX_VOICES,0); return voice[p_voice].pan; } void AudioEffectChorus::set_wet(float amount){ wet=amount; } float AudioEffectChorus::get_wet() const{ return wet; } void AudioEffectChorus::set_dry(float amount){ dry=amount; } float AudioEffectChorus::get_dry() const{ return dry; } void AudioEffectChorus::_validate_property(PropertyInfo& property) const { if (property.name.begins_with("voice/")) { int voice_idx = property.name.get_slice("/",1).to_int(); if (voice_idx>voice_count) { property.usage=0; } } } void AudioEffectChorus::_bind_methods() { ClassDB::bind_method(_MD("set_voice_count","voices"),&AudioEffectChorus::set_voice_count); ClassDB::bind_method(_MD("get_voice_count"),&AudioEffectChorus::get_voice_count); ClassDB::bind_method(_MD("set_voice_delay_ms","voice_idx","delay_ms"),&AudioEffectChorus::set_voice_delay_ms); ClassDB::bind_method(_MD("get_voice_delay_ms","voice_idx"),&AudioEffectChorus::get_voice_delay_ms); ClassDB::bind_method(_MD("set_voice_rate_hz","voice_idx","rate_hz"),&AudioEffectChorus::set_voice_rate_hz); ClassDB::bind_method(_MD("get_voice_rate_hz","voice_idx"),&AudioEffectChorus::get_voice_rate_hz); ClassDB::bind_method(_MD("set_voice_depth_ms","voice_idx","depth_ms"),&AudioEffectChorus::set_voice_depth_ms); ClassDB::bind_method(_MD("get_voice_depth_ms","voice_idx"),&AudioEffectChorus::get_voice_depth_ms); ClassDB::bind_method(_MD("set_voice_level_db","voice_idx","level_db"),&AudioEffectChorus::set_voice_level_db); ClassDB::bind_method(_MD("get_voice_level_db","voice_idx"),&AudioEffectChorus::get_voice_level_db); ClassDB::bind_method(_MD("set_voice_cutoff_hz","voice_idx","cutoff_hz"),&AudioEffectChorus::set_voice_cutoff_hz); ClassDB::bind_method(_MD("get_voice_cutoff_hz","voice_idx"),&AudioEffectChorus::get_voice_cutoff_hz); ClassDB::bind_method(_MD("set_voice_pan","voice_idx","pan"),&AudioEffectChorus::set_voice_pan); ClassDB::bind_method(_MD("get_voice_pan","voice_idx"),&AudioEffectChorus::get_voice_pan); ClassDB::bind_method(_MD("set_wet","amount"),&AudioEffectChorus::set_wet); ClassDB::bind_method(_MD("get_wet"),&AudioEffectChorus::get_wet); ClassDB::bind_method(_MD("set_dry","amount"),&AudioEffectChorus::set_dry); ClassDB::bind_method(_MD("get_dry"),&AudioEffectChorus::get_dry); ADD_PROPERTY(PropertyInfo(Variant::INT,"voice_count",PROPERTY_HINT_RANGE,"1,4,1"),_SCS("set_voice_count"),_SCS("get_voice_count")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_dry"),_SCS("get_dry")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"wet",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_wet"),_SCS("get_wet")); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),_SCS("set_voice_delay_ms"),_SCS("get_voice_delay_ms"),0); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),_SCS("set_voice_rate_hz"),_SCS("get_voice_rate_hz"),0); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),_SCS("set_voice_depth_ms"),_SCS("get_voice_depth_ms"),0); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),_SCS("set_voice_level_db"),_SCS("get_voice_level_db"),0); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),_SCS("set_voice_cutoff_hz"),_SCS("get_voice_cutoff_hz"),0); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/1/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),_SCS("set_voice_pan"),_SCS("get_voice_pan"),0); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),_SCS("set_voice_delay_ms"),_SCS("get_voice_delay_ms"),1); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),_SCS("set_voice_rate_hz"),_SCS("get_voice_rate_hz"),1); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),_SCS("set_voice_depth_ms"),_SCS("get_voice_depth_ms"),1); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),_SCS("set_voice_level_db"),_SCS("get_voice_level_db"),1); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),_SCS("set_voice_cutoff_hz"),_SCS("get_voice_cutoff_hz"),1); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/2/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),_SCS("set_voice_pan"),_SCS("get_voice_pan"),1); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),_SCS("set_voice_delay_ms"),_SCS("get_voice_delay_ms"),2); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),_SCS("set_voice_rate_hz"),_SCS("get_voice_rate_hz"),2); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),_SCS("set_voice_depth_ms"),_SCS("get_voice_depth_ms"),2); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),_SCS("set_voice_level_db"),_SCS("get_voice_level_db"),2); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),_SCS("set_voice_cutoff_hz"),_SCS("get_voice_cutoff_hz"),2); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/3/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),_SCS("set_voice_pan"),_SCS("get_voice_pan"),2); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/delay_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),_SCS("set_voice_delay_ms"),_SCS("get_voice_delay_ms"),3); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/rate_hz",PROPERTY_HINT_RANGE,"0.1,20,0.1"),_SCS("set_voice_rate_hz"),_SCS("get_voice_rate_hz"),3); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/depth_ms",PROPERTY_HINT_RANGE,"0,20,0.01"),_SCS("set_voice_depth_ms"),_SCS("get_voice_depth_ms"),3); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/level_db",PROPERTY_HINT_RANGE,"-60,24,0.1"),_SCS("set_voice_level_db"),_SCS("get_voice_level_db"),3); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/cutoff_hz",PROPERTY_HINT_RANGE,"1,16000,1"),_SCS("set_voice_cutoff_hz"),_SCS("get_voice_cutoff_hz"),3); ADD_PROPERTYI(PropertyInfo(Variant::REAL,"voice/4/pan",PROPERTY_HINT_RANGE,"-1,1,0.01"),_SCS("set_voice_pan"),_SCS("get_voice_pan"),3); } AudioEffectChorus::AudioEffectChorus() { voice_count=2; voice[0].delay=15; voice[1].delay=20; voice[0].rate=0.8; voice[1].rate=1.2; voice[0].depth=2; voice[1].depth=3; voice[0].cutoff=8000; voice[1].cutoff=8000; voice[0].pan=-0.5; voice[1].pan=0.5; wet=0.5; dry=1.0; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
drivers/unix/rw_lock_posix.cpp
77
#if defined(UNIX_ENABLED) || defined(PTHREAD_ENABLED) #include "os/memory.h" #include "rw_lock_posix.h" #include "error_macros.h" #include <stdio.h> void RWLockPosix::read_lock() { int err =pthread_rwlock_rdlock(&rwlock); if (err!=0) { perror("wtf: "); } ERR_FAIL_COND(err!=0); } void RWLockPosix::read_unlock() { pthread_rwlock_unlock(&rwlock); } Error RWLockPosix::read_try_lock() { if (pthread_rwlock_tryrdlock(&rwlock)!=0) { return ERR_BUSY; } else { return OK; } } void RWLockPosix::write_lock() { int err = pthread_rwlock_wrlock(&rwlock); ERR_FAIL_COND(err!=0); } void RWLockPosix::write_unlock() { pthread_rwlock_unlock(&rwlock); } Error RWLockPosix::write_try_lock() { if (pthread_rwlock_trywrlock(&rwlock)!=0) { return ERR_BUSY; } else { return OK; } } RWLock *RWLockPosix::create_func_posix() { return memnew( RWLockPosix ); } void RWLockPosix::make_default() { create_func=create_func_posix; } RWLockPosix::RWLockPosix() { //rwlock=PTHREAD_RWLOCK_INITIALIZER; fails on OSX pthread_rwlock_init(&rwlock,NULL); } RWLockPosix::~RWLockPosix() { pthread_rwlock_destroy(&rwlock); } #endif
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
scene/resources/sky_box.cpp
159
#include "sky_box.h" #include "io/image_loader.h" void SkyBox::set_radiance_size(RadianceSize p_size) { ERR_FAIL_INDEX(p_size,RADIANCE_SIZE_MAX); radiance_size=p_size; _radiance_changed(); } SkyBox::RadianceSize SkyBox::get_radiance_size() const { return radiance_size; } void SkyBox::_bind_methods() { ClassDB::bind_method(_MD("set_radiance_size","size"),&SkyBox::set_radiance_size); ClassDB::bind_method(_MD("get_radiance_size"),&SkyBox::get_radiance_size); ADD_PROPERTY(PropertyInfo(Variant::INT,"radiance_size",PROPERTY_HINT_ENUM,"256,512,1024,2048"),_SCS("set_radiance_size"),_SCS("get_radiance_size")); BIND_CONSTANT( RADIANCE_SIZE_256 ); BIND_CONSTANT( RADIANCE_SIZE_512 ); BIND_CONSTANT( RADIANCE_SIZE_1024 ); BIND_CONSTANT( RADIANCE_SIZE_2048 ); BIND_CONSTANT( RADIANCE_SIZE_MAX ); } SkyBox::SkyBox() { radiance_size=RADIANCE_SIZE_512; } ///////////////////////////////////////// void ImageSkyBox::_radiance_changed() { if (cube_map_valid) { static const int size[RADIANCE_SIZE_MAX]={ 256,512,1024,2048 }; VS::get_singleton()->skybox_set_texture(sky_box,cube_map,size[get_radiance_size()]); } } void ImageSkyBox::set_image_path(ImagePath p_image,const String &p_path) { ERR_FAIL_INDEX(p_image,IMAGE_PATH_MAX); image_path[p_image]=p_path; bool all_ok=true; for(int i=0;i<IMAGE_PATH_MAX;i++) { if (image_path[i]==String()) { all_ok=false; } } cube_map_valid=false; if (all_ok) { Image images[IMAGE_PATH_MAX]; int w=0,h=0; Image::Format format; for(int i=0;i<IMAGE_PATH_MAX;i++) { Error err = ImageLoader::load_image(image_path[i],&images[i]); if (err) { ERR_PRINTS("Error loading image for skybox: "+image_path[i]); return; } if (i==0) { w=images[0].get_width(); h=images[0].get_height(); format=images[0].get_format(); } else { if (images[i].get_width()!=w || images[i].get_height()!=h || images[i].get_format()!=format) { ERR_PRINTS("Image size mismatch ("+itos(images[i].get_width())+","+itos(images[i].get_height())+":"+Image::get_format_name(images[i].get_format())+" when it should be "+itos(w)+","+itos(h)+":"+Image::get_format_name(format)+"): "+image_path[i]); return; } } } VS::get_singleton()->texture_allocate(cube_map,w,h,format,VS::TEXTURE_FLAG_FILTER|VS::TEXTURE_FLAG_CUBEMAP|VS::TEXTURE_FLAG_MIPMAPS); for(int i=0;i<IMAGE_PATH_MAX;i++) { VS::get_singleton()->texture_set_data(cube_map,images[i],VS::CubeMapSide(i)); } cube_map_valid=true; _radiance_changed(); } } String ImageSkyBox::get_image_path(ImagePath p_image) const { ERR_FAIL_INDEX_V(p_image,IMAGE_PATH_MAX,String()); return image_path[p_image]; } RID ImageSkyBox::get_rid() const { return sky_box; } void ImageSkyBox::_bind_methods() { ClassDB::bind_method(_MD("set_image_path","image","path"),&ImageSkyBox::set_image_path); ClassDB::bind_method(_MD("get_image_path","image"),&ImageSkyBox::get_image_path); List<String> extensions; ImageLoader::get_recognized_extensions(&extensions); String hints; for(List<String>::Element *E=extensions.front();E;E=E->next()) { if (hints!=String()) { hints+=","; } hints+="*."+E->get(); } ADD_GROUP("Image Path","image_path_"); ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_x",PROPERTY_HINT_FILE,hints),_SCS("set_image_path"),_SCS("get_image_path"),IMAGE_PATH_NEGATIVE_X); ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_x",PROPERTY_HINT_FILE,hints),_SCS("set_image_path"),_SCS("get_image_path"),IMAGE_PATH_POSITIVE_X); ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_y",PROPERTY_HINT_FILE,hints),_SCS("set_image_path"),_SCS("get_image_path"),IMAGE_PATH_NEGATIVE_Y); ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_y",PROPERTY_HINT_FILE,hints),_SCS("set_image_path"),_SCS("get_image_path"),IMAGE_PATH_POSITIVE_Y); ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_negative_z",PROPERTY_HINT_FILE,hints),_SCS("set_image_path"),_SCS("get_image_path"),IMAGE_PATH_NEGATIVE_Z); ADD_PROPERTYI(PropertyInfo(Variant::STRING,"image_path_positive_z",PROPERTY_HINT_FILE,hints),_SCS("set_image_path"),_SCS("get_image_path"),IMAGE_PATH_POSITIVE_Z); BIND_CONSTANT( IMAGE_PATH_NEGATIVE_X ); BIND_CONSTANT( IMAGE_PATH_POSITIVE_X ); BIND_CONSTANT( IMAGE_PATH_NEGATIVE_Y ); BIND_CONSTANT( IMAGE_PATH_POSITIVE_Y ); BIND_CONSTANT( IMAGE_PATH_NEGATIVE_Z ); BIND_CONSTANT( IMAGE_PATH_POSITIVE_Z ); BIND_CONSTANT( IMAGE_PATH_MAX ); } ImageSkyBox::ImageSkyBox() { cube_map=VS::get_singleton()->texture_create(); sky_box=VS::get_singleton()->skybox_create(); cube_map_valid=false; } ImageSkyBox::~ImageSkyBox() { VS::get_singleton()->free(cube_map); VS::get_singleton()->free(sky_box); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/visual/visual_server_canvas.cpp
1,270
#include "visual_server_canvas.h" #include "visual_server_global.h" #include "visual_server_viewport.h" void VisualServerCanvas::_render_canvas_item_tree(Item *p_canvas_item, const Transform2D& p_transform, const Rect2& p_clip_rect, const Color& p_modulate, RasterizerCanvas::Light *p_lights) { static const int z_range = VS::CANVAS_ITEM_Z_MAX-VS::CANVAS_ITEM_Z_MIN+1; RasterizerCanvas::Item *z_list[z_range]; RasterizerCanvas::Item *z_last_list[z_range]; for(int i=0;i<z_range;i++) { z_list[i]=NULL; z_last_list[i]=NULL; } _render_canvas_item(p_canvas_item,p_transform,p_clip_rect,Color(1,1,1,1),0,z_list,z_last_list,NULL,NULL); for(int i=0;i<z_range;i++) { if (!z_list[i]) continue; VSG::canvas_render->canvas_render_items(z_list[i],VS::CANVAS_ITEM_Z_MIN+i,p_modulate,p_lights); } } void VisualServerCanvas::_render_canvas_item(Item *p_canvas_item,const Transform2D& p_transform,const Rect2& p_clip_rect, const Color &p_modulate,int p_z,RasterizerCanvas::Item **z_list,RasterizerCanvas::Item **z_last_list,Item *p_canvas_clip,Item *p_material_owner) { Item *ci = p_canvas_item; if (!ci->visible) return; Rect2 rect = ci->get_rect(); Transform2D xform = p_transform * ci->xform; Rect2 global_rect = xform.xform(rect); global_rect.pos+=p_clip_rect.pos; if (ci->use_parent_material && p_material_owner) ci->material_owner=p_material_owner; else { p_material_owner=ci; ci->material_owner=NULL; } Color modulate( ci->modulate.r * p_modulate.r, ci->modulate.g * p_modulate.g,ci->modulate.b * p_modulate.b,ci->modulate.a * p_modulate.a); if (modulate.a<0.007) return; int child_item_count=ci->child_items.size(); Item **child_items=(Item**)alloca(child_item_count*sizeof(Item*)); copymem(child_items,ci->child_items.ptr(),child_item_count*sizeof(Item*)); if (ci->clip) { if (p_canvas_clip != NULL) { ci->final_clip_rect=p_canvas_clip->final_clip_rect.clip(global_rect); } else { ci->final_clip_rect=global_rect; } ci->final_clip_owner=ci; } else { ci->final_clip_owner=p_canvas_clip; } if (ci->sort_y) { SortArray<Item*,ItemPtrSort> sorter; sorter.sort(child_items,child_item_count); } if (ci->z_relative) p_z=CLAMP(p_z+ci->z,VS::CANVAS_ITEM_Z_MIN,VS::CANVAS_ITEM_Z_MAX); else p_z=ci->z; for(int i=0;i<child_item_count;i++) { if (!child_items[i]->behind) continue; _render_canvas_item(child_items[i],xform,p_clip_rect,modulate,p_z,z_list,z_last_list,(Item*)ci->final_clip_owner,p_material_owner); } if (ci->copy_back_buffer) { ci->copy_back_buffer->screen_rect = xform.xform(ci->copy_back_buffer->rect).clip(p_clip_rect); } if ((!ci->commands.empty() && p_clip_rect.intersects(global_rect)) || ci->vp_render || ci->copy_back_buffer) { //something to draw? ci->final_transform=xform; ci->final_modulate=Color(modulate.r*ci->self_modulate.r, modulate.g*ci->self_modulate.g, modulate.b*ci->self_modulate.b, modulate.a*ci->self_modulate.a ); ci->global_rect_cache=global_rect; ci->global_rect_cache.pos-=p_clip_rect.pos; ci->light_masked=false; int zidx = p_z-VS::CANVAS_ITEM_Z_MIN; if (z_last_list[zidx]) { z_last_list[zidx]->next=ci; z_last_list[zidx]=ci; } else { z_list[zidx]=ci; z_last_list[zidx]=ci; } ci->next=NULL; } for(int i=0;i<child_item_count;i++) { if (child_items[i]->behind) continue; _render_canvas_item(child_items[i],xform,p_clip_rect,modulate,p_z,z_list,z_last_list,(Item*)ci->final_clip_owner,p_material_owner); } } void VisualServerCanvas::_light_mask_canvas_items(int p_z,RasterizerCanvas::Item *p_canvas_item,RasterizerCanvas::Light *p_masked_lights) { if (!p_masked_lights) return; RasterizerCanvas::Item *ci=p_canvas_item; while(ci) { RasterizerCanvas::Light *light=p_masked_lights; while(light) { if (ci->light_mask&light->item_mask && p_z>=light->z_min && p_z<=light->z_max && ci->global_rect_cache.intersects_transformed(light->xform_cache,light->rect_cache)) { ci->light_masked=true; } light=light->mask_next_ptr; } ci=ci->next; } } void VisualServerCanvas::render_canvas(Canvas *p_canvas, const Transform2D &p_transform, RasterizerCanvas::Light *p_lights, RasterizerCanvas::Light *p_masked_lights, const Rect2 &p_clip_rect) { VSG::canvas_render->canvas_begin(); int l = p_canvas->child_items.size(); Canvas::ChildItem *ci=p_canvas->child_items.ptr(); bool has_mirror=false; for(int i=0;i<l;i++) { if (ci[i].mirror.x || ci[i].mirror.y) { has_mirror=true; break; } } if (!has_mirror) { static const int z_range = VS::CANVAS_ITEM_Z_MAX-VS::CANVAS_ITEM_Z_MIN+1; RasterizerCanvas::Item *z_list[z_range]; RasterizerCanvas::Item *z_last_list[z_range]; for(int i=0;i<z_range;i++) { z_list[i]=NULL; z_last_list[i]=NULL; } for(int i=0;i<l;i++) { _render_canvas_item(ci[i].item,p_transform,p_clip_rect,Color(1,1,1,1),0,z_list,z_last_list,NULL,NULL); } for(int i=0;i<z_range;i++) { if (!z_list[i]) continue; if (p_masked_lights) { _light_mask_canvas_items(VS::CANVAS_ITEM_Z_MIN+i,z_list[i],p_masked_lights); } VSG::canvas_render->canvas_render_items(z_list[i],VS::CANVAS_ITEM_Z_MIN+i,p_canvas->modulate,p_lights); } } else { for(int i=0;i<l;i++) { Canvas::ChildItem& ci=p_canvas->child_items[i]; _render_canvas_item_tree(ci.item,p_transform,p_clip_rect,p_canvas->modulate,p_lights); //mirroring (useful for scrolling backgrounds) if (ci.mirror.x!=0) { Transform2D xform2 = p_transform * Transform2D(0,Vector2(ci.mirror.x,0)); _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights); } if (ci.mirror.y!=0) { Transform2D xform2 = p_transform * Transform2D(0,Vector2(0,ci.mirror.y)); _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights); } if (ci.mirror.y!=0 && ci.mirror.x!=0) { Transform2D xform2 = p_transform * Transform2D(0,ci.mirror); _render_canvas_item_tree(ci.item,xform2,p_clip_rect,p_canvas->modulate,p_lights); } } } } RID VisualServerCanvas::canvas_create() { Canvas * canvas = memnew( Canvas ); ERR_FAIL_COND_V(!canvas,RID()); RID rid = canvas_owner.make_rid( canvas ); return rid; } void VisualServerCanvas::canvas_set_item_mirroring(RID p_canvas,RID p_item,const Point2& p_mirroring) { Canvas * canvas = canvas_owner.getornull(p_canvas); ERR_FAIL_COND(!canvas); Item *canvas_item = canvas_item_owner.getornull(p_item); ERR_FAIL_COND(!canvas_item); int idx = canvas->find_item(canvas_item); ERR_FAIL_COND(idx==-1); canvas->child_items[idx].mirror=p_mirroring; } void VisualServerCanvas::canvas_set_modulate(RID p_canvas,const Color& p_color) { Canvas * canvas = canvas_owner.get(p_canvas); ERR_FAIL_COND(!canvas); canvas->modulate=p_color; } RID VisualServerCanvas::canvas_item_create() { Item *canvas_item = memnew( Item ); ERR_FAIL_COND_V(!canvas_item,RID()); return canvas_item_owner.make_rid( canvas_item ); } void VisualServerCanvas::canvas_item_set_parent(RID p_item,RID p_parent) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); if (canvas_item->parent.is_valid()) { if (canvas_owner.owns(canvas_item->parent)) { Canvas *canvas = canvas_owner.get(canvas_item->parent); canvas->erase_item(canvas_item); } else if (canvas_item_owner.owns(canvas_item->parent)) { Item *item_owner = canvas_item_owner.get(canvas_item->parent); item_owner->child_items.erase(canvas_item); } canvas_item->parent=RID(); } if (p_parent.is_valid()) { if (canvas_owner.owns(p_parent)) { Canvas *canvas = canvas_owner.get(p_parent); Canvas::ChildItem ci; ci.item=canvas_item; canvas->child_items.push_back(ci); canvas->children_order_dirty=true; } else if (canvas_item_owner.owns(p_parent)) { Item *item_owner = canvas_item_owner.get(p_parent); item_owner->child_items.push_back(canvas_item); item_owner->children_order_dirty=true; } else { ERR_EXPLAIN("Invalid parent"); ERR_FAIL(); } } canvas_item->parent=p_parent; } void VisualServerCanvas::canvas_item_set_visible(RID p_item,bool p_visible){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->visible=p_visible; } void VisualServerCanvas::canvas_item_set_light_mask(RID p_item,int p_mask){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->light_mask=p_mask; } void VisualServerCanvas::canvas_item_set_transform(RID p_item, const Transform2D& p_transform){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->xform=p_transform; } void VisualServerCanvas::canvas_item_set_clip(RID p_item, bool p_clip){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->clip=p_clip; } void VisualServerCanvas::canvas_item_set_distance_field_mode(RID p_item, bool p_enable){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->distance_field=p_enable; } void VisualServerCanvas::canvas_item_set_custom_rect(RID p_item, bool p_custom_rect,const Rect2& p_rect){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->custom_rect=p_custom_rect; canvas_item->rect=p_rect; } void VisualServerCanvas::canvas_item_set_modulate(RID p_item, const Color& p_color) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->modulate=p_color; } void VisualServerCanvas::canvas_item_set_self_modulate(RID p_item, const Color& p_color){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->self_modulate=p_color; } void VisualServerCanvas::canvas_item_set_draw_behind_parent(RID p_item, bool p_enable){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->behind=p_enable; } void VisualServerCanvas::canvas_item_add_line(RID p_item, const Point2& p_from, const Point2& p_to,const Color& p_color,float p_width,bool p_antialiased) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandLine * line = memnew( Item::CommandLine ); ERR_FAIL_COND(!line); line->color=p_color; line->from=p_from; line->to=p_to; line->width=p_width; line->antialiased=p_antialiased; canvas_item->rect_dirty=true; canvas_item->commands.push_back(line); } void VisualServerCanvas::canvas_item_add_rect(RID p_item, const Rect2& p_rect, const Color& p_color) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandRect * rect = memnew( Item::CommandRect ); ERR_FAIL_COND(!rect); rect->modulate=p_color; rect->rect=p_rect; canvas_item->rect_dirty=true; canvas_item->commands.push_back(rect); } void VisualServerCanvas::canvas_item_add_circle(RID p_item, const Point2& p_pos, float p_radius,const Color& p_color) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandCircle * circle = memnew( Item::CommandCircle ); ERR_FAIL_COND(!circle); circle->color=p_color; circle->pos=p_pos; circle->radius=p_radius; canvas_item->commands.push_back(circle); } void VisualServerCanvas::canvas_item_add_texture_rect(RID p_item, const Rect2& p_rect, RID p_texture,bool p_tile,const Color& p_modulate,bool p_transpose) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandRect * rect = memnew( Item::CommandRect ); ERR_FAIL_COND(!rect); rect->modulate=p_modulate; rect->rect=p_rect; rect->flags=0; if (p_tile) { rect->flags|=RasterizerCanvas::CANVAS_RECT_TILE; rect->flags|=RasterizerCanvas::CANVAS_RECT_REGION; rect->source=Rect2(0,0,p_rect.size.width,p_rect.size.height); } if (p_rect.size.x<0) { rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_H; rect->rect.size.x = -rect->rect.size.x; } if (p_rect.size.y<0) { rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_V; rect->rect.size.y = -rect->rect.size.y; } if (p_transpose) { rect->flags|=RasterizerCanvas::CANVAS_RECT_TRANSPOSE; SWAP(rect->rect.size.x, rect->rect.size.y); } rect->texture=p_texture; canvas_item->rect_dirty=true; canvas_item->commands.push_back(rect); } void VisualServerCanvas::canvas_item_add_texture_rect_region(RID p_item, const Rect2& p_rect, RID p_texture,const Rect2& p_src_rect,const Color& p_modulate,bool p_transpose) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandRect * rect = memnew( Item::CommandRect ); ERR_FAIL_COND(!rect); rect->modulate=p_modulate; rect->rect=p_rect; rect->texture=p_texture; rect->source=p_src_rect; rect->flags=RasterizerCanvas::CANVAS_RECT_REGION; if (p_rect.size.x<0) { rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_H; rect->rect.size.x = -rect->rect.size.x; } if (p_rect.size.y<0) { rect->flags|=RasterizerCanvas::CANVAS_RECT_FLIP_V; rect->rect.size.y = -rect->rect.size.y; } if (p_transpose) { rect->flags|=RasterizerCanvas::CANVAS_RECT_TRANSPOSE; SWAP(rect->rect.size.x, rect->rect.size.y); } canvas_item->rect_dirty=true; canvas_item->commands.push_back(rect); } void VisualServerCanvas::canvas_item_add_nine_patch(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector2& p_topleft, const Vector2& p_bottomright,VS::NinePatchAxisMode p_x_axis_mode, VS::NinePatchAxisMode p_y_axis_mode,bool p_draw_center,const Color& p_modulate) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandNinePatch * style = memnew( Item::CommandNinePatch ); ERR_FAIL_COND(!style); style->texture=p_texture; style->rect=p_rect; style->source=p_source; style->draw_center=p_draw_center; style->color=p_modulate; style->margin[MARGIN_LEFT]=p_topleft.x; style->margin[MARGIN_TOP]=p_topleft.y; style->margin[MARGIN_RIGHT]=p_bottomright.x; style->margin[MARGIN_BOTTOM]=p_bottomright.y; style->axis_x=p_x_axis_mode; style->axis_y=p_y_axis_mode; canvas_item->rect_dirty=true; canvas_item->commands.push_back(style); } void VisualServerCanvas::canvas_item_add_primitive(RID p_item,const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture,float p_width) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandPrimitive * prim = memnew( Item::CommandPrimitive ); ERR_FAIL_COND(!prim); prim->texture=p_texture; prim->points=p_points; prim->uvs=p_uvs; prim->colors=p_colors; prim->width=p_width; canvas_item->rect_dirty=true; canvas_item->commands.push_back(prim); } void VisualServerCanvas::canvas_item_add_polygon(RID p_item, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); #ifdef DEBUG_ENABLED int pointcount = p_points.size(); ERR_FAIL_COND(pointcount<3); int color_size=p_colors.size(); int uv_size=p_uvs.size(); ERR_FAIL_COND(color_size!=0 && color_size!=1 && color_size!=pointcount); ERR_FAIL_COND(uv_size!=0 && (uv_size!=pointcount || !p_texture.is_valid())); #endif Vector<int> indices = Geometry::triangulate_polygon(p_points); if (indices.empty()) { ERR_EXPLAIN("Bad Polygon!"); ERR_FAIL_V(); } Item::CommandPolygon * polygon = memnew( Item::CommandPolygon ); ERR_FAIL_COND(!polygon); polygon->texture=p_texture; polygon->points=p_points; polygon->uvs=p_uvs; polygon->colors=p_colors; polygon->indices=indices; polygon->count=indices.size(); canvas_item->rect_dirty=true; canvas_item->commands.push_back(polygon); } void VisualServerCanvas::canvas_item_add_triangle_array(RID p_item, const Vector<int>& p_indices, const Vector<Point2>& p_points, const Vector<Color>& p_colors,const Vector<Point2>& p_uvs, RID p_texture, int p_count) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); int ps = p_points.size(); ERR_FAIL_COND(!p_colors.empty() && p_colors.size()!=ps && p_colors.size()!=1); ERR_FAIL_COND(!p_uvs.empty() && p_uvs.size()!=ps); Vector<int> indices = p_indices; int count = p_count * 3; if (indices.empty()) { ERR_FAIL_COND( ps % 3 != 0 ); if (p_count == -1) count = ps; } else { ERR_FAIL_COND( indices.size() % 3 != 0 ); if (p_count == -1) count = indices.size(); } Item::CommandPolygon * polygon = memnew( Item::CommandPolygon ); ERR_FAIL_COND(!polygon); polygon->texture=p_texture; polygon->points=p_points; polygon->uvs=p_uvs; polygon->colors=p_colors; polygon->indices=indices; polygon->count = count; canvas_item->rect_dirty=true; canvas_item->commands.push_back(polygon); } void VisualServerCanvas::canvas_item_add_set_transform(RID p_item,const Transform2D& p_transform) { Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandTransform * tr = memnew( Item::CommandTransform ); ERR_FAIL_COND(!tr); tr->xform=p_transform; canvas_item->commands.push_back(tr); } void VisualServerCanvas::canvas_item_add_mesh(RID p_item, const RID& p_mesh,RID p_skeleton){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandMesh * m = memnew( Item::CommandMesh ); ERR_FAIL_COND(!m); m->mesh=p_mesh; m->skeleton=p_skeleton; canvas_item->commands.push_back(m); } void VisualServerCanvas::canvas_item_add_multimesh(RID p_item, RID p_mesh,RID p_skeleton){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandMultiMesh * mm = memnew( Item::CommandMultiMesh ); ERR_FAIL_COND(!mm); mm->multimesh=p_mesh; mm->skeleton=p_skeleton; canvas_item->commands.push_back(mm); } void VisualServerCanvas::canvas_item_add_clip_ignore(RID p_item, bool p_ignore){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); Item::CommandClipIgnore * ci = memnew( Item::CommandClipIgnore); ERR_FAIL_COND(!ci); ci->ignore=p_ignore; canvas_item->commands.push_back(ci); } void VisualServerCanvas::canvas_item_set_sort_children_by_y(RID p_item, bool p_enable){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->sort_y=p_enable; } void VisualServerCanvas::canvas_item_set_z(RID p_item, int p_z){ ERR_FAIL_COND(p_z<VS::CANVAS_ITEM_Z_MIN || p_z>VS::CANVAS_ITEM_Z_MAX); Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->z=p_z; } void VisualServerCanvas::canvas_item_set_z_as_relative_to_parent(RID p_item, bool p_enable){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->z_relative=p_enable; } void VisualServerCanvas::canvas_item_set_copy_to_backbuffer(RID p_item, bool p_enable,const Rect2& p_rect){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); if (bool(canvas_item->copy_back_buffer!=NULL) !=p_enable) { if (p_enable) { canvas_item->copy_back_buffer = memnew( RasterizerCanvas::Item::CopyBackBuffer ); } else { memdelete(canvas_item->copy_back_buffer); canvas_item->copy_back_buffer=NULL; } } if (p_enable) { canvas_item->copy_back_buffer->rect=p_rect; canvas_item->copy_back_buffer->full=p_rect==Rect2(); } } void VisualServerCanvas::canvas_item_clear(RID p_item){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->clear(); } void VisualServerCanvas::canvas_item_set_draw_index(RID p_item,int p_index){ Item *canvas_item = canvas_item_owner.getornull( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->index=p_index; if (canvas_item_owner.owns( canvas_item->parent)) { Item *canvas_item_parent = canvas_item_owner.getornull( canvas_item->parent ); canvas_item_parent->children_order_dirty=true; return; } Canvas* canvas = canvas_owner.getornull( canvas_item->parent ); if (canvas) { canvas->children_order_dirty=true; return; } } void VisualServerCanvas::canvas_item_set_material(RID p_item, RID p_material){ Item *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->material=p_material; } void VisualServerCanvas::canvas_item_set_use_parent_material(RID p_item, bool p_enable){ Item *canvas_item = canvas_item_owner.get( p_item ); ERR_FAIL_COND(!canvas_item); canvas_item->use_parent_material=p_enable; } RID VisualServerCanvas::canvas_light_create(){ RasterizerCanvas::Light *clight = memnew( RasterizerCanvas::Light ); clight->light_internal = VSG::canvas_render->light_internal_create(); return canvas_light_owner.make_rid(clight); } void VisualServerCanvas::canvas_light_attach_to_canvas(RID p_light,RID p_canvas){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); if (clight->canvas.is_valid()) { Canvas *canvas = canvas_owner.getornull(clight->canvas); canvas->lights.erase(clight); } if (!canvas_owner.owns(p_canvas)) p_canvas=RID(); clight->canvas=p_canvas; if (clight->canvas.is_valid()) { Canvas *canvas = canvas_owner.get(clight->canvas); canvas->lights.insert(clight); } } void VisualServerCanvas::canvas_light_set_enabled(RID p_light, bool p_enabled){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->enabled=p_enabled; } void VisualServerCanvas::canvas_light_set_scale(RID p_light, float p_scale){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->scale=p_scale; } void VisualServerCanvas::canvas_light_set_transform(RID p_light, const Transform2D& p_transform){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->xform=p_transform; } void VisualServerCanvas::canvas_light_set_texture(RID p_light, RID p_texture){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->texture=p_texture; } void VisualServerCanvas::canvas_light_set_texture_offset(RID p_light, const Vector2& p_offset){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->texture_offset=p_offset; } void VisualServerCanvas::canvas_light_set_color(RID p_light, const Color& p_color){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->color=p_color; } void VisualServerCanvas::canvas_light_set_height(RID p_light, float p_height){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->height=p_height; } void VisualServerCanvas::canvas_light_set_energy(RID p_light, float p_energy){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->energy=p_energy; } void VisualServerCanvas::canvas_light_set_z_range(RID p_light, int p_min_z,int p_max_z){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->z_min=p_min_z; clight->z_max=p_max_z; } void VisualServerCanvas::canvas_light_set_layer_range(RID p_light, int p_min_layer,int p_max_layer){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->layer_max=p_max_layer; clight->layer_min=p_min_layer; } void VisualServerCanvas::canvas_light_set_item_cull_mask(RID p_light, int p_mask){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->item_mask=p_mask; } void VisualServerCanvas::canvas_light_set_item_shadow_cull_mask(RID p_light, int p_mask){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->item_shadow_mask=p_mask; } void VisualServerCanvas::canvas_light_set_mode(RID p_light, VS::CanvasLightMode p_mode){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->mode=p_mode; } void VisualServerCanvas::canvas_light_set_shadow_enabled(RID p_light, bool p_enabled){ RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); if (clight->shadow_buffer.is_valid()==p_enabled) return; if (p_enabled) { clight->shadow_buffer=VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size); } else { VSG::storage->free(clight->shadow_buffer); clight->shadow_buffer=RID(); } } void VisualServerCanvas::canvas_light_set_shadow_buffer_size(RID p_light, int p_size){ ERR_FAIL_COND(p_size<32 || p_size>16384); RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); int new_size = nearest_power_of_2(p_size); if (new_size==clight->shadow_buffer_size) return; clight->shadow_buffer_size=nearest_power_of_2(p_size); if (clight->shadow_buffer.is_valid()) { VSG::storage->free(clight->shadow_buffer); clight->shadow_buffer=VSG::storage->canvas_light_shadow_buffer_create(clight->shadow_buffer_size); } } void VisualServerCanvas::canvas_light_set_shadow_gradient_length(RID p_light, float p_length) { ERR_FAIL_COND(p_length<0); RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->shadow_gradient_length=p_length; } void VisualServerCanvas::canvas_light_set_shadow_filter(RID p_light, VS::CanvasLightShadowFilter p_filter) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->shadow_filter=p_filter; } void VisualServerCanvas::canvas_light_set_shadow_color(RID p_light, const Color& p_color) { RasterizerCanvas::Light *clight = canvas_light_owner.get(p_light); ERR_FAIL_COND(!clight); clight->shadow_color=p_color; } RID VisualServerCanvas::canvas_light_occluder_create() { RasterizerCanvas::LightOccluderInstance *occluder = memnew( RasterizerCanvas::LightOccluderInstance ); return canvas_light_occluder_owner.make_rid(occluder); } void VisualServerCanvas::canvas_light_occluder_attach_to_canvas(RID p_occluder,RID p_canvas){ RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); if (occluder->canvas.is_valid()) { Canvas *canvas = canvas_owner.get(occluder->canvas); canvas->occluders.erase(occluder); } if (!canvas_owner.owns(p_canvas)) p_canvas=RID(); occluder->canvas=p_canvas; if (occluder->canvas.is_valid()) { Canvas *canvas = canvas_owner.get(occluder->canvas); canvas->occluders.insert(occluder); } } void VisualServerCanvas::canvas_light_occluder_set_enabled(RID p_occluder,bool p_enabled) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); occluder->enabled=p_enabled; } void VisualServerCanvas::canvas_light_occluder_set_polygon(RID p_occluder,RID p_polygon) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); if (occluder->polygon.is_valid()) { LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_polygon); if (occluder_poly) { occluder_poly->owners.erase(occluder); } } occluder->polygon=p_polygon; occluder->polygon_buffer=RID(); if (occluder->polygon.is_valid()) { LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_polygon); if (!occluder_poly) occluder->polygon=RID(); ERR_FAIL_COND(!occluder_poly); occluder_poly->owners.insert(occluder); occluder->polygon_buffer=occluder_poly->occluder; occluder->aabb_cache=occluder_poly->aabb; occluder->cull_cache=occluder_poly->cull_mode; } } void VisualServerCanvas::canvas_light_occluder_set_transform(RID p_occluder,const Transform2D& p_xform) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); occluder->xform=p_xform; } void VisualServerCanvas::canvas_light_occluder_set_light_mask(RID p_occluder,int p_mask) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_occluder); ERR_FAIL_COND(!occluder); occluder->light_mask=p_mask; } RID VisualServerCanvas::canvas_occluder_polygon_create() { LightOccluderPolygon * occluder_poly = memnew( LightOccluderPolygon ); occluder_poly->occluder=VSG::storage->canvas_light_occluder_create(); return canvas_light_occluder_polygon_owner.make_rid(occluder_poly); } void VisualServerCanvas::canvas_occluder_polygon_set_shape(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape,bool p_closed) { if (p_shape.size()<3) { canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon,p_shape); return; } PoolVector<Vector2> lines; int lc = p_shape.size()*2; lines.resize(lc-(p_closed?0:2)); { PoolVector<Vector2>::Write w = lines.write(); PoolVector<Vector2>::Read r = p_shape.read(); int max=lc/2; if (!p_closed) { max--; } for(int i=0;i<max;i++) { Vector2 a = r[i]; Vector2 b = r[(i+1)%(lc/2)]; w[i*2+0]=a; w[i*2+1]=b; } } canvas_occluder_polygon_set_shape_as_lines(p_occluder_polygon,lines); } void VisualServerCanvas::canvas_occluder_polygon_set_shape_as_lines(RID p_occluder_polygon,const PoolVector<Vector2>& p_shape) { LightOccluderPolygon * occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon); ERR_FAIL_COND(!occluder_poly); ERR_FAIL_COND(p_shape.size()&1); int lc = p_shape.size(); occluder_poly->aabb=Rect2(); { PoolVector<Vector2>::Read r = p_shape.read(); for(int i=0;i<lc;i++) { if (i==0) occluder_poly->aabb.pos=r[i]; else occluder_poly->aabb.expand_to(r[i]); } } VSG::storage->canvas_light_occluder_set_polylines(occluder_poly->occluder,p_shape); for( Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=occluder_poly->owners.front();E;E=E->next()) { E->get()->aabb_cache=occluder_poly->aabb; } } void VisualServerCanvas::canvas_occluder_polygon_set_cull_mode(RID p_occluder_polygon,VS::CanvasOccluderPolygonCullMode p_mode) { LightOccluderPolygon * occluder_poly = canvas_light_occluder_polygon_owner.get(p_occluder_polygon); ERR_FAIL_COND(!occluder_poly); occluder_poly->cull_mode=p_mode; for( Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=occluder_poly->owners.front();E;E=E->next()) { E->get()->cull_cache=p_mode; } } bool VisualServerCanvas::free(RID p_rid) { if (canvas_owner.owns(p_rid)) { Canvas *canvas = canvas_owner.get(p_rid); ERR_FAIL_COND_V(!canvas,false); while(canvas->viewports.size()) { VisualServerViewport::Viewport *vp = VSG::viewport->viewport_owner.get(canvas->viewports.front()->get()); ERR_FAIL_COND_V(!vp,true); Map<RID,VisualServerViewport::Viewport::CanvasData>::Element *E=vp->canvas_map.find(p_rid); ERR_FAIL_COND_V(!E,true); vp->canvas_map.erase(p_rid); canvas->viewports.erase( canvas->viewports.front() ); } for (int i=0;i<canvas->child_items.size();i++) { canvas->child_items[i].item->parent=RID(); } for (Set<RasterizerCanvas::Light*>::Element *E=canvas->lights.front();E;E=E->next()) { E->get()->canvas=RID(); } for (Set<RasterizerCanvas::LightOccluderInstance*>::Element *E=canvas->occluders.front();E;E=E->next()) { E->get()->canvas=RID(); } canvas_owner.free( p_rid ); memdelete( canvas ); } else if (canvas_item_owner.owns(p_rid)) { Item *canvas_item = canvas_item_owner.get(p_rid); ERR_FAIL_COND_V(!canvas_item,true); if (canvas_item->parent.is_valid()) { if (canvas_owner.owns(canvas_item->parent)) { Canvas *canvas = canvas_owner.get(canvas_item->parent); canvas->erase_item(canvas_item); } else if (canvas_item_owner.owns(canvas_item->parent)) { Item *item_owner = canvas_item_owner.get(canvas_item->parent); item_owner->child_items.erase(canvas_item); } } for (int i=0;i<canvas_item->child_items.size();i++) { canvas_item->child_items[i]->parent=RID(); } /* if (canvas_item->material) { canvas_item->material->owners.erase(canvas_item); } */ canvas_item_owner.free( p_rid ); memdelete( canvas_item ); } else if (canvas_light_owner.owns(p_rid)) { RasterizerCanvas::Light *canvas_light = canvas_light_owner.get(p_rid); ERR_FAIL_COND_V(!canvas_light,true); if (canvas_light->canvas.is_valid()) { Canvas* canvas = canvas_owner.get(canvas_light->canvas); if (canvas) canvas->lights.erase(canvas_light); } if (canvas_light->shadow_buffer.is_valid()) VSG::storage->free(canvas_light->shadow_buffer); VSG::canvas_render->light_internal_free(canvas_light->light_internal); canvas_light_owner.free( p_rid ); memdelete( canvas_light ); } else if (canvas_light_occluder_owner.owns(p_rid)) { RasterizerCanvas::LightOccluderInstance *occluder = canvas_light_occluder_owner.get(p_rid); ERR_FAIL_COND_V(!occluder,true); if (occluder->polygon.is_valid()) { LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(occluder->polygon); if (occluder_poly) { occluder_poly->owners.erase(occluder); } } if (occluder->canvas.is_valid() && canvas_owner.owns(occluder->canvas)) { Canvas *canvas = canvas_owner.get(occluder->canvas); canvas->occluders.erase(occluder); } canvas_light_occluder_owner.free( p_rid ); memdelete(occluder); } else if (canvas_light_occluder_polygon_owner.owns(p_rid)) { LightOccluderPolygon *occluder_poly = canvas_light_occluder_polygon_owner.get(p_rid); ERR_FAIL_COND_V(!occluder_poly,true); VSG::storage->free(occluder_poly->occluder); while(occluder_poly->owners.size()) { occluder_poly->owners.front()->get()->polygon=RID(); occluder_poly->owners.erase( occluder_poly->owners.front() ); } canvas_light_occluder_polygon_owner.free( p_rid ); memdelete(occluder_poly); } else { return false; } return true; } VisualServerCanvas::VisualServerCanvas() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_distortion.cpp
171
#include "audio_effect_distortion.h" #include "servers/audio_server.h" #include "math_funcs.h" void AudioEffectDistortionInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { const float *src = (const float*)p_src_frames; float *dst = (float*)p_dst_frames; //float lpf_c=expf(-2.0*Math_PI*keep_hf_hz.get()/(mix_rate*(float)OVERSAMPLE)); float lpf_c=expf(-2.0*Math_PI*base->keep_hf_hz/(AudioServer::get_singleton()->get_mix_rate())); float lpf_ic=1.0-lpf_c; float drive_f=base->drive; float pregain_f=Math::db2linear(base->pre_gain); float postgain_f=Math::db2linear(base->post_gain); float atan_mult=pow(10,drive_f*drive_f*3.0)-1.0+0.001; float atan_div=1.0/(atanf(atan_mult)*(1.0+drive_f*8)); float lofi_mult=powf(2.0,2.0+(1.0-drive_f)*14); //goes from 16 to 2 bits for (int i=0;i<p_frame_count*2;i++) { float out=undenormalise(src[i]*lpf_ic+lpf_c*h[i&1]); h[i&1]=out; float a=out; float ha=src[i]-out; //high freqs a*=pregain_f; switch (base->mode) { case AudioEffectDistortion::MODE_CLIP: { a=powf(a,1.0001-drive_f); if (a>1.0) a=1.0; else if (a<(-1.0)) a=-1.0; } break; case AudioEffectDistortion::MODE_ATAN: { a=atanf(a*atan_mult)*atan_div; } break; case AudioEffectDistortion::MODE_LOFI: { a = floorf(a*lofi_mult+0.5)/lofi_mult; } break; case AudioEffectDistortion::MODE_OVERDRIVE: { const double x = a * 0.686306; const double z = 1 + exp (sqrt (fabs (x)) * -0.75); a = (expf(x) - expf(-x * z)) / (expf(x) + expf(-x)); } break; case AudioEffectDistortion::MODE_WAVESHAPE: { float x = a; float k= 2*drive_f/(1.00001-drive_f); a = (1.0+k)*x/(1.0+k*fabsf(x)); } break; } dst[i]=a*postgain_f+ha; } } Ref<AudioEffectInstance> AudioEffectDistortion::instance() { Ref<AudioEffectDistortionInstance> ins; ins.instance(); ins->base=Ref<AudioEffectDistortion>(this); ins->h[0]=0; ins->h[1]=0; return ins; } void AudioEffectDistortion::set_mode(Mode p_mode) { mode=p_mode; } AudioEffectDistortion::Mode AudioEffectDistortion::get_mode() const{ return mode; } void AudioEffectDistortion::set_pre_gain(float p_pre_gain){ pre_gain=p_pre_gain; } float AudioEffectDistortion::get_pre_gain() const{ return pre_gain; } void AudioEffectDistortion::set_keep_hf_hz(float p_keep_hf_hz){ keep_hf_hz=p_keep_hf_hz; } float AudioEffectDistortion::get_keep_hf_hz() const{ return keep_hf_hz; } void AudioEffectDistortion::set_drive(float p_drive){ drive=p_drive; } float AudioEffectDistortion::get_drive() const{ return drive; } void AudioEffectDistortion::set_post_gain(float p_post_gain){ post_gain=p_post_gain; } float AudioEffectDistortion::get_post_gain() const{ return post_gain; } void AudioEffectDistortion::_bind_methods() { ClassDB::bind_method(_MD("set_mode","mode"),&AudioEffectDistortion::set_mode); ClassDB::bind_method(_MD("get_mode"),&AudioEffectDistortion::get_mode); ClassDB::bind_method(_MD("set_pre_gain","pre_gain"),&AudioEffectDistortion::set_pre_gain); ClassDB::bind_method(_MD("get_pre_gain"),&AudioEffectDistortion::get_pre_gain); ClassDB::bind_method(_MD("set_keep_hf_hz","keep_hf_hz"),&AudioEffectDistortion::set_keep_hf_hz); ClassDB::bind_method(_MD("get_keep_hf_hz"),&AudioEffectDistortion::get_keep_hf_hz); ClassDB::bind_method(_MD("set_drive","drive"),&AudioEffectDistortion::set_drive); ClassDB::bind_method(_MD("get_drive"),&AudioEffectDistortion::get_drive); ClassDB::bind_method(_MD("set_post_gain","post_gain"),&AudioEffectDistortion::set_post_gain); ClassDB::bind_method(_MD("get_post_gain"),&AudioEffectDistortion::get_post_gain); ADD_PROPERTY(PropertyInfo(Variant::INT,"mode",PROPERTY_HINT_ENUM,"Clip,ATan,LoFi,Overdrive,WaveShape"),_SCS("set_mode"),_SCS("get_mode")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"pre_gain",PROPERTY_HINT_RANGE,"-60,60,0.01"),_SCS("set_pre_gain"),_SCS("get_pre_gain")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"keep_hf_hz",PROPERTY_HINT_RANGE,"1,20000,1"),_SCS("set_keep_hf_hz"),_SCS("get_keep_hf_hz")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"drive",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_drive"),_SCS("get_drive")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"post_gain",PROPERTY_HINT_RANGE,"-80,24,0.01"),_SCS("set_post_gain"),_SCS("get_post_gain")); } AudioEffectDistortion::AudioEffectDistortion() { mode=MODE_CLIP; pre_gain=0; post_gain=0; keep_hf_hz=16000; drive=0; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
scene/resources/material.cpp
1,102
/*************************************************************************/ /* material.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "material.h" #include "scene/scene_string_names.h" RID Material::get_rid() const { return material; } Material::Material() { material=VisualServer::get_singleton()->material_create(); } Material::~Material() { VisualServer::get_singleton()->free(material); } ///////////////////////////////// Mutex *FixedSpatialMaterial::material_mutex=NULL; SelfList<FixedSpatialMaterial>::List FixedSpatialMaterial::dirty_materials; Map<FixedSpatialMaterial::MaterialKey,FixedSpatialMaterial::ShaderData> FixedSpatialMaterial::shader_map; FixedSpatialMaterial::ShaderNames* FixedSpatialMaterial::shader_names=NULL; void FixedSpatialMaterial::init_shaders() { #ifndef NO_THREADS material_mutex = Mutex::create(); #endif shader_names = memnew( ShaderNames ); shader_names->albedo="albedo"; shader_names->specular="specular"; shader_names->roughness="roughness"; shader_names->metalness="metalness"; shader_names->emission="emission"; shader_names->emission_energy="emission_energy"; shader_names->normal_scale="normal_scale"; shader_names->rim="rim"; shader_names->rim_tint="rim_tint"; shader_names->clearcoat="clearcoat"; shader_names->clearcoat_gloss="clearcoat_gloss"; shader_names->anisotropy="anisotropy_ratio"; shader_names->height_scale="height_scale"; shader_names->subsurface_scattering_strength="subsurface_scattering_strength"; shader_names->refraction="refraction"; shader_names->refraction_roughness="refraction_roughness"; shader_names->point_size="point_size"; shader_names->uv1_scale="uv1_scale"; shader_names->uv1_offset="uv1_offset"; shader_names->uv2_scale="uv2_scale"; shader_names->uv2_offset="uv2_offset"; shader_names->texture_names[TEXTURE_ALBEDO]="texture_albedo"; shader_names->texture_names[TEXTURE_SPECULAR]="texture_specular"; shader_names->texture_names[TEXTURE_EMISSION]="texture_emission"; shader_names->texture_names[TEXTURE_NORMAL]="texture_normal"; shader_names->texture_names[TEXTURE_RIM]="texture_rim"; shader_names->texture_names[TEXTURE_CLEARCOAT]="texture_clearcoat"; shader_names->texture_names[TEXTURE_FLOWMAP]="texture_flowmap"; shader_names->texture_names[TEXTURE_AMBIENT_OCCLUSION]="texture_ambient_occlusion"; shader_names->texture_names[TEXTURE_HEIGHT]="texture_height"; shader_names->texture_names[TEXTURE_SUBSURFACE_SCATTERING]="texture_subsurface_scattering"; shader_names->texture_names[TEXTURE_REFRACTION]="texture_refraction"; shader_names->texture_names[TEXTURE_REFRACTION_ROUGHNESS]="texture_refraction_roughness"; shader_names->texture_names[TEXTURE_DETAIL_MASK]="texture_detail_mask"; shader_names->texture_names[TEXTURE_DETAIL_ALBEDO]="texture_detail_albedo"; shader_names->texture_names[TEXTURE_DETAIL_NORMAL]="texture_detail_normal"; } void FixedSpatialMaterial::finish_shaders(){ #ifndef NO_THREADS memdelete( material_mutex ); #endif memdelete( shader_names ); } void FixedSpatialMaterial::_update_shader() { dirty_materials.remove( &element ); MaterialKey mk = _compute_key(); if (mk.key==current_key.key) return; //no update required in the end if (shader_map.has(current_key)) { shader_map[current_key].users--; if (shader_map[current_key].users==0) { //deallocate shader, as it's no longer in use VS::get_singleton()->free(shader_map[current_key].shader); shader_map.erase(current_key); } } current_key=mk; if (shader_map.has(mk)) { VS::get_singleton()->material_set_shader(_get_material(),shader_map[mk].shader); shader_map[mk].users++; return; } //must create a shader! String code="render_mode "; switch(blend_mode) { case BLEND_MODE_MIX: code+="blend_mix"; break; case BLEND_MODE_ADD: code+="blend_add"; break; case BLEND_MODE_SUB: code+="blend_sub"; break; case BLEND_MODE_MUL: code+="blend_mul"; break; } switch(depth_draw_mode) { case DEPTH_DRAW_OPAQUE_ONLY: code+=",depth_draw_opaque"; break; case DEPTH_DRAW_ALWAYS: code+=",depth_draw_always"; break; case DEPTH_DRAW_DISABLED: code+=",depth_draw_never"; break; case DEPTH_DRAW_ALPHA_OPAQUE_PREPASS: code+=",depth_draw_alpha_prepass"; break; } switch(cull_mode) { case CULL_BACK: code+=",cull_back"; break; case CULL_FRONT: code+=",cull_front"; break; case CULL_DISABLED: code+=",cull_disabled"; break; } if (flags[FLAG_UNSHADED]) { code+=",unshaded"; } if (flags[FLAG_ONTOP]) { code+=",ontop"; } code+=";\n"; code+="uniform vec4 albedo : hint_color;\n"; code+="uniform sampler2D texture_albedo : hint_albedo;\n"; if (specular_mode==SPECULAR_MODE_SPECULAR) { code+="uniform vec4 specular : hint_color;\n"; } else { code+="uniform float metalness;\n"; } code+="uniform float roughness : hint_range(0,1);\n"; code+="uniform float point_size : hint_range(0,128);\n"; code+="uniform sampler2D texture_specular : hint_white;\n"; code+="uniform vec2 uv1_scale;\n"; code+="uniform vec2 uv1_offset;\n"; code+="uniform vec2 uv2_scale;\n"; code+="uniform vec2 uv2_offset;\n"; if (features[FEATURE_EMISSION]) { code+="uniform sampler2D texture_emission : hint_black_albedo;\n"; code+="uniform vec4 emission : hint_color;\n"; code+="uniform float emission_energy;\n"; } if (features[FEATURE_NORMAL_MAPPING]) { code+="uniform sampler2D texture_normal : hint_normal;\n"; code+="uniform float normal_scale : hint_range(-16,16);\n"; } if (features[FEATURE_RIM]) { code+="uniform float rim : hint_range(0,1);\n"; code+="uniform float rim_tint : hint_range(0,1);\n"; code+="uniform sampler2D texture_rim : hint_white;\n"; } if (features[FEATURE_CLEARCOAT]) { code+="uniform float clearcoat : hint_range(0,1);\n"; code+="uniform float clearcoat_gloss : hint_range(0,1);\n"; code+="uniform sampler2D texture_clearcoat : hint_white;\n"; } if (features[FEATURE_ANISOTROPY]) { code+="uniform float anisotropy_ratio : hint_range(0,256);\n"; code+="uniform sampler2D texture_flowmap : hint_aniso;\n"; } if (features[FEATURE_AMBIENT_OCCLUSION]) { code+="uniform sampler2D texture_ambient_occlusion : hint_white;\n"; } if (features[FEATURE_DETAIL]) { code+="uniform sampler2D texture_detail_albedo : hint_albedo;\n"; code+="uniform sampler2D texture_detail_normal : hint_normal;\n"; code+="uniform sampler2D texture_detail_mask : hint_white;\n"; } if (features[FEATURE_SUBSURACE_SCATTERING]) { code+="uniform float subsurface_scattering_strength : hint_range(0,1);\n"; code+="uniform sampler2D texture_subsurface_scattering : hint_white;\n"; } code+="\n\n"; code+="void vertex() {\n"; if (flags[FLAG_SRGB_VERTEX_COLOR]) { code+="\tCOLOR.rgb = mix( pow((COLOR.rgb + vec3(0.055)) * (1.0 / (1.0 + 0.055)), vec3(2.4)), COLOR.rgb* (1.0 / 12.92), lessThan(COLOR.rgb,vec3(0.04045)) );\n"; } if (flags[FLAG_USE_POINT_SIZE]) { code+="\tPOINT_SIZE=point_size;\n"; } code+="\tUV=UV*uv1_scale+uv1_offset;\n"; if (detail_uv==DETAIL_UV_2) { code+="\tUV2=UV2*uv2_scale+uv2_offset;\n"; } code+="}\n"; code+="\n\n"; code+="void fragment() {\n"; if (flags[FLAG_USE_POINT_SIZE]) { code+="\tvec4 albedo_tex = texture(texture_albedo,POINT_COORD);\n"; } else { code+="\tvec4 albedo_tex = texture(texture_albedo,UV);\n"; } if (flags[FLAG_ALBEDO_FROM_VERTEX_COLOR]) { code+="\talbedo_tex *= COLOR;\n"; } code+="\tALBEDO = albedo.rgb * albedo_tex.rgb;\n"; if (features[FEATURE_TRANSPARENT]) { code+="\tALPHA = albedo.a * albedo_tex.a;\n"; } if (features[FEATURE_EMISSION]) { code+="\tEMISSION = (emission.rgb+texture(texture_emission,UV).rgb)*emission_energy;\n"; } if (features[FEATURE_NORMAL_MAPPING]) { code+="\tNORMALMAP = texture(texture_normal,UV).rgb;\n"; code+="\tNORMALMAP_DEPTH = normal_scale;\n"; } if (features[FEATURE_RIM]) { code+="\tvec2 rim_tex = texture(texture_rim,UV).xw;\n"; code+="\tRIM = rim*rim_tex.x;"; code+="\tRIM_TINT = rim_tint*rim_tex.y;\n"; } if (features[FEATURE_CLEARCOAT]) { code+="\tvec2 clearcoat_tex = texture(texture_clearcoat,UV).xw;\n"; code+="\tCLEARCOAT = clearcoat*clearcoat_tex.x;"; code+="\tCLEARCOAT_GLOSS = clearcoat_gloss*clearcoat_tex.y;\n"; } if (features[FEATURE_ANISOTROPY]) { code+="\tvec4 anisotropy_tex = texture(texture_flowmap,UV);\n"; code+="\tANISOTROPY = anisotropy_ratio*anisotropy_tex.a;\n"; code+="\tANISOTROPY_FLOW = anisotropy_tex.rg*2.0-1.0;\n"; } if (features[FEATURE_AMBIENT_OCCLUSION]) { code+="\tAO = texture(texture_ambient_occlusion,UV).r;\n"; } if (features[FEATURE_SUBSURACE_SCATTERING]) { code+="\tfloat sss_tex = texture(texture_subsurface_scattering,UV).r;\n"; code+="\tSSS_STRENGTH=subsurface_scattering_strength*sss_tex;\n"; } if (features[FEATURE_DETAIL]) { String det_uv=detail_uv==DETAIL_UV_1?"UV":"UV2"; code+="\tvec4 detail_tex = texture(texture_detail_albedo,"+det_uv+");\n"; code+="\tvec4 detail_norm_tex = texture(texture_detail_normal,"+det_uv+");\n"; code+="\tvec4 detail_mask_tex = texture(texture_detail_mask,UV);\n"; switch(detail_blend_mode) { case BLEND_MODE_MIX: { code+="\tvec3 detail = mix(ALBEDO.rgb,detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_ADD: { code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb+detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_SUB: { code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb-detail_tex.rgb,detail_tex.a);\n"; } break; case BLEND_MODE_MUL: { code+="\tvec3 detail = mix(ALBEDO.rgb,ALBEDO.rgb*detail_tex.rgb,detail_tex.a);\n"; } break; } code+="\tvec3 detail_norm = mix(NORMALMAP,detail_norm_tex.rgb,detail_tex.a);\n"; code+="\tNORMALMAP = mix(NORMALMAP,detail_norm,detail_mask_tex.r);\n"; code+="\tALBEDO.rgb = mix(ALBEDO.rgb,detail,detail_mask_tex.r);\n"; } if (specular_mode==SPECULAR_MODE_SPECULAR) { code+="\tvec4 specular_tex = texture(texture_specular,UV);\n"; code+="\tSPECULAR = specular.rgb * specular_tex.rgb;\n"; code+="\tROUGHNESS = specular_tex.a * roughness;\n"; } else { code+="\tvec4 specular_tex = texture(texture_specular,UV);\n"; code+="\tSPECULAR = vec3(metalness * specular_tex.r);\n"; code+="\tROUGHNESS = specular_tex.a * roughness;\n"; } code+="}\n"; ShaderData shader_data; shader_data.shader = VS::get_singleton()->shader_create(VS::SHADER_SPATIAL); shader_data.users=1; VS::get_singleton()->shader_set_code( shader_data.shader, code ); shader_map[mk]=shader_data; VS::get_singleton()->material_set_shader(_get_material(),shader_data.shader); } void FixedSpatialMaterial::flush_changes() { if (material_mutex) material_mutex->lock(); while (dirty_materials.first()) { dirty_materials.first()->self()->_update_shader(); } if (material_mutex) material_mutex->unlock(); } void FixedSpatialMaterial::_queue_shader_change() { if (material_mutex) material_mutex->lock(); if (!element.in_list()) { dirty_materials.add(&element); } if (material_mutex) material_mutex->unlock(); } bool FixedSpatialMaterial::_is_shader_dirty() const { bool dirty=false; if (material_mutex) material_mutex->lock(); dirty=element.in_list(); if (material_mutex) material_mutex->unlock(); return dirty; } void FixedSpatialMaterial::set_albedo(const Color& p_albedo) { albedo=p_albedo; VS::get_singleton()->material_set_param(_get_material(),shader_names->albedo,p_albedo); } Color FixedSpatialMaterial::get_albedo() const{ return albedo; } void FixedSpatialMaterial::set_specular_mode(SpecularMode p_mode) { specular_mode=p_mode; _change_notify(); _queue_shader_change(); } FixedSpatialMaterial::SpecularMode FixedSpatialMaterial::get_specular_mode() const { return specular_mode; } void FixedSpatialMaterial::set_specular(const Color& p_specular){ specular=p_specular; VS::get_singleton()->material_set_param(_get_material(),shader_names->specular,p_specular); } Color FixedSpatialMaterial::get_specular() const{ return specular; } void FixedSpatialMaterial::set_roughness(float p_roughness){ roughness=p_roughness; VS::get_singleton()->material_set_param(_get_material(),shader_names->roughness,p_roughness); } float FixedSpatialMaterial::get_roughness() const{ return roughness; } void FixedSpatialMaterial::set_metalness(float p_metalness){ metalness=p_metalness; VS::get_singleton()->material_set_param(_get_material(),shader_names->metalness,p_metalness); } float FixedSpatialMaterial::get_metalness() const{ return metalness; } void FixedSpatialMaterial::set_emission(const Color& p_emission){ emission=p_emission; VS::get_singleton()->material_set_param(_get_material(),shader_names->emission,p_emission); } Color FixedSpatialMaterial::get_emission() const{ return emission; } void FixedSpatialMaterial::set_emission_energy(float p_emission_energy){ emission_energy=p_emission_energy; VS::get_singleton()->material_set_param(_get_material(),shader_names->emission_energy,p_emission_energy); } float FixedSpatialMaterial::get_emission_energy() const{ return emission_energy; } void FixedSpatialMaterial::set_normal_scale(float p_normal_scale){ normal_scale=p_normal_scale; VS::get_singleton()->material_set_param(_get_material(),shader_names->normal_scale,p_normal_scale); } float FixedSpatialMaterial::get_normal_scale() const{ return normal_scale; } void FixedSpatialMaterial::set_rim(float p_rim){ rim=p_rim; VS::get_singleton()->material_set_param(_get_material(),shader_names->rim,p_rim); } float FixedSpatialMaterial::get_rim() const{ return rim; } void FixedSpatialMaterial::set_rim_tint(float p_rim_tint){ rim_tint=p_rim_tint; VS::get_singleton()->material_set_param(_get_material(),shader_names->rim_tint,p_rim_tint); } float FixedSpatialMaterial::get_rim_tint() const{ return rim_tint; } void FixedSpatialMaterial::set_clearcoat(float p_clearcoat){ clearcoat=p_clearcoat; VS::get_singleton()->material_set_param(_get_material(),shader_names->clearcoat,p_clearcoat); } float FixedSpatialMaterial::get_clearcoat() const{ return clearcoat; } void FixedSpatialMaterial::set_clearcoat_gloss(float p_clearcoat_gloss){ clearcoat_gloss=p_clearcoat_gloss; VS::get_singleton()->material_set_param(_get_material(),shader_names->clearcoat_gloss,p_clearcoat_gloss); } float FixedSpatialMaterial::get_clearcoat_gloss() const{ return clearcoat_gloss; } void FixedSpatialMaterial::set_anisotropy(float p_anisotropy){ anisotropy=p_anisotropy; VS::get_singleton()->material_set_param(_get_material(),shader_names->anisotropy,p_anisotropy); } float FixedSpatialMaterial::get_anisotropy() const{ return anisotropy; } void FixedSpatialMaterial::set_height_scale(float p_height_scale){ height_scale=p_height_scale; VS::get_singleton()->material_set_param(_get_material(),shader_names->height_scale,p_height_scale); } float FixedSpatialMaterial::get_height_scale() const{ return height_scale; } void FixedSpatialMaterial::set_subsurface_scattering_strength(float p_subsurface_scattering_strength){ subsurface_scattering_strength=p_subsurface_scattering_strength; VS::get_singleton()->material_set_param(_get_material(),shader_names->subsurface_scattering_strength,subsurface_scattering_strength); } float FixedSpatialMaterial::get_subsurface_scattering_strength() const{ return subsurface_scattering_strength; } void FixedSpatialMaterial::set_refraction(float p_refraction){ refraction=p_refraction; VS::get_singleton()->material_set_param(_get_material(),shader_names->refraction,refraction); } float FixedSpatialMaterial::get_refraction() const { return refraction; } void FixedSpatialMaterial::set_refraction_roughness(float p_refraction_roughness) { refraction_roughness=p_refraction_roughness; VS::get_singleton()->material_set_param(_get_material(),shader_names->refraction_roughness,refraction_roughness); } float FixedSpatialMaterial::get_refraction_roughness() const { return refraction_roughness; } void FixedSpatialMaterial::set_detail_uv(DetailUV p_detail_uv) { if (detail_uv==p_detail_uv) return; detail_uv=p_detail_uv; _queue_shader_change(); } FixedSpatialMaterial::DetailUV FixedSpatialMaterial::get_detail_uv() const { return detail_uv; } void FixedSpatialMaterial::set_blend_mode(BlendMode p_mode) { if (blend_mode==p_mode) return; blend_mode=p_mode; _queue_shader_change(); } FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_blend_mode() const { return blend_mode; } void FixedSpatialMaterial::set_detail_blend_mode(BlendMode p_mode) { detail_blend_mode=p_mode; _queue_shader_change(); } FixedSpatialMaterial::BlendMode FixedSpatialMaterial::get_detail_blend_mode() const { return detail_blend_mode; } void FixedSpatialMaterial::set_depth_draw_mode(DepthDrawMode p_mode) { if (depth_draw_mode==p_mode) return; depth_draw_mode=p_mode; _queue_shader_change(); } FixedSpatialMaterial::DepthDrawMode FixedSpatialMaterial::get_depth_draw_mode() const { return depth_draw_mode; } void FixedSpatialMaterial::set_cull_mode(CullMode p_mode) { if (cull_mode==p_mode) return; cull_mode=p_mode; _queue_shader_change(); } FixedSpatialMaterial::CullMode FixedSpatialMaterial::get_cull_mode() const { return cull_mode; } void FixedSpatialMaterial::set_diffuse_mode(DiffuseMode p_mode) { if (diffuse_mode==p_mode) return; diffuse_mode=p_mode; _queue_shader_change(); } FixedSpatialMaterial::DiffuseMode FixedSpatialMaterial::get_diffuse_mode() const { return diffuse_mode; } void FixedSpatialMaterial::set_flag(Flags p_flag,bool p_enabled) { ERR_FAIL_INDEX(p_flag,FLAG_MAX); if (flags[p_flag]==p_enabled) return; flags[p_flag]=p_enabled; _queue_shader_change(); } bool FixedSpatialMaterial::get_flag(Flags p_flag) const { ERR_FAIL_INDEX_V(p_flag,FLAG_MAX,false); return flags[p_flag]; } void FixedSpatialMaterial::set_feature(Feature p_feature,bool p_enabled) { ERR_FAIL_INDEX(p_feature,FEATURE_MAX); if (features[p_feature]==p_enabled) return; features[p_feature]=p_enabled; _change_notify(); _queue_shader_change(); } bool FixedSpatialMaterial::get_feature(Feature p_feature) const { ERR_FAIL_INDEX_V(p_feature,FEATURE_MAX,false); return features[p_feature]; } void FixedSpatialMaterial::set_texture(TextureParam p_param, const Ref<Texture> &p_texture) { ERR_FAIL_INDEX(p_param,TEXTURE_MAX); textures[p_param]=p_texture; RID rid = p_texture.is_valid() ? p_texture->get_rid() : RID(); VS::get_singleton()->material_set_param(_get_material(),shader_names->texture_names[p_param],rid); } Ref<Texture> FixedSpatialMaterial::get_texture(TextureParam p_param) const { ERR_FAIL_INDEX_V(p_param,TEXTURE_MAX,Ref<Texture>()); return textures[p_param]; } void FixedSpatialMaterial::_validate_feature(const String& text, Feature feature,PropertyInfo& property) const { if (property.name.begins_with(text) && property.name!=text+"_enabled" && !features[feature]) { property.usage=0; } } void FixedSpatialMaterial::_validate_property(PropertyInfo& property) const { _validate_feature("normal",FEATURE_NORMAL_MAPPING,property); _validate_feature("emission",FEATURE_EMISSION,property); _validate_feature("rim",FEATURE_RIM,property); _validate_feature("clearcoat",FEATURE_CLEARCOAT,property); _validate_feature("anisotropy",FEATURE_ANISOTROPY,property); _validate_feature("ao",FEATURE_AMBIENT_OCCLUSION,property); _validate_feature("height",FEATURE_HEIGHT_MAPPING,property); _validate_feature("subsurf_scatter",FEATURE_SUBSURACE_SCATTERING,property); _validate_feature("refraction",FEATURE_REFRACTION,property); _validate_feature("detail",FEATURE_DETAIL,property); if (property.name=="specular/color" && specular_mode==SPECULAR_MODE_METALLIC) { property.usage=0; } if (property.name=="specular/metalness" && specular_mode==SPECULAR_MODE_SPECULAR) { property.usage=0; } } void FixedSpatialMaterial::set_line_width(float p_line_width) { line_width=p_line_width; VS::get_singleton()->material_set_line_width(_get_material(),line_width); } float FixedSpatialMaterial::get_line_width() const { return line_width; } void FixedSpatialMaterial::set_point_size(float p_point_size) { point_size=p_point_size; VS::get_singleton()->material_set_param(_get_material(),shader_names->point_size,p_point_size); } float FixedSpatialMaterial::get_point_size() const { return point_size; } void FixedSpatialMaterial::set_uv1_scale(const Vector2& p_scale) { uv1_scale=p_scale; VS::get_singleton()->material_set_param(_get_material(),shader_names->uv1_scale,p_scale); } Vector2 FixedSpatialMaterial::get_uv1_scale() const{ return uv1_scale; } void FixedSpatialMaterial::set_uv1_offset(const Vector2& p_offset){ uv1_offset=p_offset; VS::get_singleton()->material_set_param(_get_material(),shader_names->uv1_offset,p_offset); } Vector2 FixedSpatialMaterial::get_uv1_offset() const{ return uv1_offset; } void FixedSpatialMaterial::set_uv2_scale(const Vector2& p_scale) { uv2_scale=p_scale; VS::get_singleton()->material_set_param(_get_material(),shader_names->uv2_scale,p_scale); } Vector2 FixedSpatialMaterial::get_uv2_scale() const{ return uv2_scale; } void FixedSpatialMaterial::set_uv2_offset(const Vector2& p_offset){ uv2_offset=p_offset; VS::get_singleton()->material_set_param(_get_material(),shader_names->uv2_offset,p_offset); } Vector2 FixedSpatialMaterial::get_uv2_offset() const{ return uv2_offset; } void FixedSpatialMaterial::_bind_methods() { ClassDB::bind_method(_MD("set_albedo","albedo"),&FixedSpatialMaterial::set_albedo); ClassDB::bind_method(_MD("get_albedo"),&FixedSpatialMaterial::get_albedo); ClassDB::bind_method(_MD("set_specular_mode","specular_mode"),&FixedSpatialMaterial::set_specular_mode); ClassDB::bind_method(_MD("get_specular_mode"),&FixedSpatialMaterial::get_specular_mode); ClassDB::bind_method(_MD("set_specular","specular"),&FixedSpatialMaterial::set_specular); ClassDB::bind_method(_MD("get_specular"),&FixedSpatialMaterial::get_specular); ClassDB::bind_method(_MD("set_metalness","metalness"),&FixedSpatialMaterial::set_metalness); ClassDB::bind_method(_MD("get_metalness"),&FixedSpatialMaterial::get_metalness); ClassDB::bind_method(_MD("set_roughness","roughness"),&FixedSpatialMaterial::set_roughness); ClassDB::bind_method(_MD("get_roughness"),&FixedSpatialMaterial::get_roughness); ClassDB::bind_method(_MD("set_emission","emission"),&FixedSpatialMaterial::set_emission); ClassDB::bind_method(_MD("get_emission"),&FixedSpatialMaterial::get_emission); ClassDB::bind_method(_MD("set_emission_energy","emission_energy"),&FixedSpatialMaterial::set_emission_energy); ClassDB::bind_method(_MD("get_emission_energy"),&FixedSpatialMaterial::get_emission_energy); ClassDB::bind_method(_MD("set_normal_scale","normal_scale"),&FixedSpatialMaterial::set_normal_scale); ClassDB::bind_method(_MD("get_normal_scale"),&FixedSpatialMaterial::get_normal_scale); ClassDB::bind_method(_MD("set_rim","rim"),&FixedSpatialMaterial::set_rim); ClassDB::bind_method(_MD("get_rim"),&FixedSpatialMaterial::get_rim); ClassDB::bind_method(_MD("set_rim_tint","rim_tint"),&FixedSpatialMaterial::set_rim_tint); ClassDB::bind_method(_MD("get_rim_tint"),&FixedSpatialMaterial::get_rim_tint); ClassDB::bind_method(_MD("set_clearcoat","clearcoat"),&FixedSpatialMaterial::set_clearcoat); ClassDB::bind_method(_MD("get_clearcoat"),&FixedSpatialMaterial::get_clearcoat); ClassDB::bind_method(_MD("set_clearcoat_gloss","clearcoat_gloss"),&FixedSpatialMaterial::set_clearcoat_gloss); ClassDB::bind_method(_MD("get_clearcoat_gloss"),&FixedSpatialMaterial::get_clearcoat_gloss); ClassDB::bind_method(_MD("set_anisotropy","anisotropy"),&FixedSpatialMaterial::set_anisotropy); ClassDB::bind_method(_MD("get_anisotropy"),&FixedSpatialMaterial::get_anisotropy); ClassDB::bind_method(_MD("set_height_scale","height_scale"),&FixedSpatialMaterial::set_height_scale); ClassDB::bind_method(_MD("get_height_scale"),&FixedSpatialMaterial::get_height_scale); ClassDB::bind_method(_MD("set_subsurface_scattering_strength","strength"),&FixedSpatialMaterial::set_subsurface_scattering_strength); ClassDB::bind_method(_MD("get_subsurface_scattering_strength"),&FixedSpatialMaterial::get_subsurface_scattering_strength); ClassDB::bind_method(_MD("set_refraction","refraction"),&FixedSpatialMaterial::set_refraction); ClassDB::bind_method(_MD("get_refraction"),&FixedSpatialMaterial::get_refraction); ClassDB::bind_method(_MD("set_refraction_roughness","refraction_roughness"),&FixedSpatialMaterial::set_refraction_roughness); ClassDB::bind_method(_MD("get_refraction_roughness"),&FixedSpatialMaterial::get_refraction_roughness); ClassDB::bind_method(_MD("set_line_width","line_width"),&FixedSpatialMaterial::set_line_width); ClassDB::bind_method(_MD("get_line_width"),&FixedSpatialMaterial::get_line_width); ClassDB::bind_method(_MD("set_point_size","point_size"),&FixedSpatialMaterial::set_point_size); ClassDB::bind_method(_MD("get_point_size"),&FixedSpatialMaterial::get_point_size); ClassDB::bind_method(_MD("set_detail_uv","detail_uv"),&FixedSpatialMaterial::set_detail_uv); ClassDB::bind_method(_MD("get_detail_uv"),&FixedSpatialMaterial::get_detail_uv); ClassDB::bind_method(_MD("set_blend_mode","blend_mode"),&FixedSpatialMaterial::set_blend_mode); ClassDB::bind_method(_MD("get_blend_mode"),&FixedSpatialMaterial::get_blend_mode); ClassDB::bind_method(_MD("set_depth_draw_mode","depth_draw_mode"),&FixedSpatialMaterial::set_depth_draw_mode); ClassDB::bind_method(_MD("get_depth_draw_mode"),&FixedSpatialMaterial::get_depth_draw_mode); ClassDB::bind_method(_MD("set_cull_mode","cull_mode"),&FixedSpatialMaterial::set_cull_mode); ClassDB::bind_method(_MD("get_cull_mode"),&FixedSpatialMaterial::get_cull_mode); ClassDB::bind_method(_MD("set_diffuse_mode","diffuse_mode"),&FixedSpatialMaterial::set_diffuse_mode); ClassDB::bind_method(_MD("get_diffuse_mode"),&FixedSpatialMaterial::get_diffuse_mode); ClassDB::bind_method(_MD("set_flag","flag","enable"),&FixedSpatialMaterial::set_flag); ClassDB::bind_method(_MD("get_flag"),&FixedSpatialMaterial::get_flag); ClassDB::bind_method(_MD("set_feature","feature","enable"),&FixedSpatialMaterial::set_feature); ClassDB::bind_method(_MD("get_feature","feature"),&FixedSpatialMaterial::get_feature); ClassDB::bind_method(_MD("set_texture","param:Texture","texture"),&FixedSpatialMaterial::set_texture); ClassDB::bind_method(_MD("get_texture:Texture","param:Texture"),&FixedSpatialMaterial::get_texture); ClassDB::bind_method(_MD("set_detail_blend_mode","detail_blend_mode"),&FixedSpatialMaterial::set_detail_blend_mode); ClassDB::bind_method(_MD("get_detail_blend_mode"),&FixedSpatialMaterial::get_detail_blend_mode); ClassDB::bind_method(_MD("set_uv1_scale","scale"),&FixedSpatialMaterial::set_uv1_scale); ClassDB::bind_method(_MD("get_uv1_scale"),&FixedSpatialMaterial::get_uv1_scale); ClassDB::bind_method(_MD("set_uv1_offset","offset"),&FixedSpatialMaterial::set_uv1_offset); ClassDB::bind_method(_MD("get_uv1_offset"),&FixedSpatialMaterial::get_uv1_offset); ClassDB::bind_method(_MD("set_uv2_scale","scale"),&FixedSpatialMaterial::set_uv2_scale); ClassDB::bind_method(_MD("get_uv2_scale"),&FixedSpatialMaterial::get_uv2_scale); ClassDB::bind_method(_MD("set_uv2_offset","offset"),&FixedSpatialMaterial::set_uv2_offset); ClassDB::bind_method(_MD("get_uv2_offset"),&FixedSpatialMaterial::get_uv2_offset); ADD_GROUP("Flags","flags_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_transparent"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_TRANSPARENT); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_unshaded"),_SCS("set_flag"),_SCS("get_flag"),FLAG_UNSHADED); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_on_top"),_SCS("set_flag"),_SCS("get_flag"),FLAG_ONTOP); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"flags_use_point_size"),_SCS("set_flag"),_SCS("get_flag"),FLAG_USE_POINT_SIZE); ADD_GROUP("Vertex Color","vertex_color"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"vertex_color_use_as_albedo"),_SCS("set_flag"),_SCS("get_flag"),FLAG_ALBEDO_FROM_VERTEX_COLOR); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"vertex_color_is_srgb"),_SCS("set_flag"),_SCS("get_flag"),FLAG_SRGB_VERTEX_COLOR); ADD_GROUP("Parameters","params_"); ADD_PROPERTY(PropertyInfo(Variant::INT,"params_diffuse_mode",PROPERTY_HINT_ENUM,"Labert,Lambert Wrap,Oren Nayar,Burley"),_SCS("set_diffuse_mode"),_SCS("get_diffuse_mode")); ADD_PROPERTY(PropertyInfo(Variant::INT,"params_blend_mode",PROPERTY_HINT_ENUM,"Mix,Add,Sub,Mul"),_SCS("set_blend_mode"),_SCS("get_blend_mode")); ADD_PROPERTY(PropertyInfo(Variant::INT,"params_cull_mode",PROPERTY_HINT_ENUM,"Back,Front,Disabled"),_SCS("set_cull_mode"),_SCS("get_cull_mode")); ADD_PROPERTY(PropertyInfo(Variant::INT,"params_depth_draw_mode",PROPERTY_HINT_ENUM,"Opaque Only,Always,Never,Opaque Pre-Pass"),_SCS("set_depth_draw_mode"),_SCS("get_depth_draw_mode")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"params_line_width",PROPERTY_HINT_RANGE,"0.1,128,0.1"),_SCS("set_line_width"),_SCS("get_line_width")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"params_point_size",PROPERTY_HINT_RANGE,"0.1,128,0.1"),_SCS("set_point_size"),_SCS("get_point_size")); ADD_GROUP("Albedo","albedo_"); ADD_PROPERTY(PropertyInfo(Variant::COLOR,"albedo_color"),_SCS("set_albedo"),_SCS("get_albedo")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"albedo_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_ALBEDO); ADD_GROUP("Specular","specular_"); ADD_PROPERTY(PropertyInfo(Variant::INT,"specular_mode",PROPERTY_HINT_ENUM,"Metallic,Specular"),_SCS("set_specular_mode"),_SCS("get_specular_mode")); ADD_PROPERTY(PropertyInfo(Variant::COLOR,"specular_color",PROPERTY_HINT_COLOR_NO_ALPHA),_SCS("set_specular"),_SCS("get_specular")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"specular_metalness",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_metalness"),_SCS("get_metalness")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"specular_roughness",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_roughness"),_SCS("get_roughness")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"specular_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_SPECULAR); ADD_GROUP("Emission","emission_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"emission_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_EMISSION); ADD_PROPERTY(PropertyInfo(Variant::COLOR,"emission_color",PROPERTY_HINT_COLOR_NO_ALPHA),_SCS("set_emission"),_SCS("get_emission")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"emission_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_emission_energy"),_SCS("get_emission_energy")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"emission_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_EMISSION); ADD_GROUP("NormapMap","normal_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"normal_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_NORMAL_MAPPING); ADD_PROPERTY(PropertyInfo(Variant::REAL,"normal_scale",PROPERTY_HINT_RANGE,"-16,16,0.01"),_SCS("set_normal_scale"),_SCS("get_normal_scale")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"normal_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_NORMAL); ADD_GROUP("Rim","rim_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"rim_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_RIM); ADD_PROPERTY(PropertyInfo(Variant::REAL,"rim_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_rim"),_SCS("get_rim")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"rim_tint",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_rim_tint"),_SCS("get_rim_tint")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"rim_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_RIM); ADD_GROUP("Clearcoat","clearcoat_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"clearcoat_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_CLEARCOAT); ADD_PROPERTY(PropertyInfo(Variant::REAL,"clearcoat_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_clearcoat"),_SCS("get_clearcoat")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"clearcoat_gloss",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_clearcoat_gloss"),_SCS("get_clearcoat_gloss")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"clearcoat_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_CLEARCOAT); ADD_GROUP("Anisotropy","anisotropy_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"anisotropy_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_ANISOTROPY); ADD_PROPERTY(PropertyInfo(Variant::REAL,"anisotropy_anisotropy",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_anisotropy"),_SCS("get_anisotropy")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"anisotropy_flowmap",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_FLOWMAP); ADD_GROUP("Ambient Occlusion","ao_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"ao_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_AMBIENT_OCCLUSION); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"ao_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_AMBIENT_OCCLUSION); ADD_GROUP("Height","height_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"height_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_HEIGHT_MAPPING); ADD_PROPERTY(PropertyInfo(Variant::REAL,"height_scale",PROPERTY_HINT_RANGE,"-16,16,0.01"),_SCS("set_height_scale"),_SCS("get_height_scale")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"height_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_HEIGHT); ADD_GROUP("Subsurf Scatter","subsurf_scatter_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"subsurf_scatter_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_SUBSURACE_SCATTERING); ADD_PROPERTY(PropertyInfo(Variant::REAL,"subsurf_scatter_strength",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_subsurface_scattering_strength"),_SCS("get_subsurface_scattering_strength")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"subsurf_scatter_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_SUBSURFACE_SCATTERING); ADD_GROUP("Refraction","refraction_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"refraction_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_REFRACTION); ADD_PROPERTY(PropertyInfo(Variant::REAL,"refraction_displacement",PROPERTY_HINT_RANGE,"-1,1,0.01"),_SCS("set_refraction"),_SCS("get_refraction")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"refraction_roughness",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_refraction_roughness"),_SCS("get_refraction_roughness")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"refraction_texture",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_REFRACTION); ADD_GROUP("Detail","detail_"); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"detail_enabled"),_SCS("set_feature"),_SCS("get_feature"),FEATURE_DETAIL); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_mask",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_DETAIL_MASK); ADD_PROPERTY(PropertyInfo(Variant::INT,"detail_blend_mode",PROPERTY_HINT_ENUM,"Mix,Add,Sub,Mul"),_SCS("set_detail_blend_mode"),_SCS("get_detail_blend_mode")); ADD_PROPERTY(PropertyInfo(Variant::INT,"detail_uv_layer",PROPERTY_HINT_ENUM,"UV1,UV2"),_SCS("set_detail_uv"),_SCS("get_detail_uv")); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_albedo",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_DETAIL_ALBEDO); ADD_PROPERTYI(PropertyInfo(Variant::OBJECT,"detail_normal",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_texture"),_SCS("get_texture"),TEXTURE_DETAIL_NORMAL); ADD_GROUP("UV1","uv1_"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv1_scale"),_SCS("set_uv1_scale"),_SCS("get_uv1_scale")); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv1_offset"),_SCS("set_uv1_offset"),_SCS("get_uv1_offset")); ADD_GROUP("UV2","uv2_"); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv2_scale"),_SCS("set_uv2_scale"),_SCS("get_uv2_scale")); ADD_PROPERTY(PropertyInfo(Variant::VECTOR2,"uv2_offset"),_SCS("set_uv2_offset"),_SCS("get_uv2_offset")); BIND_CONSTANT( TEXTURE_ALBEDO ); BIND_CONSTANT( TEXTURE_SPECULAR ); BIND_CONSTANT( TEXTURE_EMISSION ); BIND_CONSTANT( TEXTURE_NORMAL ); BIND_CONSTANT( TEXTURE_RIM ); BIND_CONSTANT( TEXTURE_CLEARCOAT ); BIND_CONSTANT( TEXTURE_FLOWMAP ); BIND_CONSTANT( TEXTURE_AMBIENT_OCCLUSION ); BIND_CONSTANT( TEXTURE_HEIGHT ); BIND_CONSTANT( TEXTURE_SUBSURFACE_SCATTERING ); BIND_CONSTANT( TEXTURE_REFRACTION ); BIND_CONSTANT( TEXTURE_REFRACTION_ROUGHNESS ); BIND_CONSTANT( TEXTURE_DETAIL_MASK ); BIND_CONSTANT( TEXTURE_DETAIL_ALBEDO ); BIND_CONSTANT( TEXTURE_DETAIL_NORMAL ); BIND_CONSTANT( TEXTURE_MAX ); BIND_CONSTANT( DETAIL_UV_1 ); BIND_CONSTANT( DETAIL_UV_2 ); BIND_CONSTANT( FEATURE_TRANSPARENT ); BIND_CONSTANT( FEATURE_EMISSION ); BIND_CONSTANT( FEATURE_NORMAL_MAPPING ); BIND_CONSTANT( FEATURE_RIM ); BIND_CONSTANT( FEATURE_CLEARCOAT ); BIND_CONSTANT( FEATURE_ANISOTROPY ); BIND_CONSTANT( FEATURE_AMBIENT_OCCLUSION ); BIND_CONSTANT( FEATURE_HEIGHT_MAPPING ); BIND_CONSTANT( FEATURE_SUBSURACE_SCATTERING ); BIND_CONSTANT( FEATURE_REFRACTION ); BIND_CONSTANT( FEATURE_DETAIL ); BIND_CONSTANT( FEATURE_MAX ); BIND_CONSTANT( BLEND_MODE_MIX ); BIND_CONSTANT( BLEND_MODE_ADD ); BIND_CONSTANT( BLEND_MODE_SUB ); BIND_CONSTANT( BLEND_MODE_MUL ); BIND_CONSTANT( DEPTH_DRAW_OPAQUE_ONLY ); BIND_CONSTANT( DEPTH_DRAW_ALWAYS ); BIND_CONSTANT( DEPTH_DRAW_DISABLED ); BIND_CONSTANT( DEPTH_DRAW_ALPHA_OPAQUE_PREPASS ); BIND_CONSTANT( CULL_BACK ); BIND_CONSTANT( CULL_FRONT ); BIND_CONSTANT( CULL_DISABLED ); BIND_CONSTANT( FLAG_UNSHADED ); BIND_CONSTANT( FLAG_ONTOP ); BIND_CONSTANT( FLAG_ALBEDO_FROM_VERTEX_COLOR ); BIND_CONSTANT( FLAG_SRGB_VERTEX_COLOR ) BIND_CONSTANT( FLAG_USE_POINT_SIZE ) BIND_CONSTANT( FLAG_MAX ); BIND_CONSTANT( DIFFUSE_LAMBERT ); BIND_CONSTANT( DIFFUSE_LAMBERT_WRAP ); BIND_CONSTANT( DIFFUSE_OREN_NAYAR ); BIND_CONSTANT( DIFFUSE_BURLEY ); BIND_CONSTANT( SPECULAR_MODE_METALLIC ); BIND_CONSTANT( SPECULAR_MODE_SPECULAR ); } FixedSpatialMaterial::FixedSpatialMaterial() : element(this) { //initialize to right values specular_mode=SPECULAR_MODE_METALLIC; set_albedo(Color(0.7,0.7,0.7,1.0)); set_specular(Color(0.1,0.1,0.1)); set_roughness(0.0); set_metalness(0.1); set_emission(Color(0,0,0)); set_emission_energy(1.0); set_normal_scale(1); set_rim(1.0); set_rim_tint(0.5); set_clearcoat(1); set_clearcoat_gloss(0.5); set_anisotropy(0); set_height_scale(1); set_subsurface_scattering_strength(0); set_refraction(0); set_refraction_roughness(0); set_line_width(1); set_point_size(1); set_uv1_offset(Vector2(0,0)); set_uv1_scale(Vector2(1,1)); set_uv2_offset(Vector2(0,0)); set_uv2_scale(Vector2(1,1)); detail_uv=DETAIL_UV_1; blend_mode=BLEND_MODE_MIX; detail_blend_mode=BLEND_MODE_MIX; depth_draw_mode=DEPTH_DRAW_OPAQUE_ONLY; cull_mode=CULL_BACK; for(int i=0;i<FLAG_MAX;i++) { flags[i]=0; } diffuse_mode=DIFFUSE_LAMBERT; for(int i=0;i<FEATURE_MAX;i++) { features[i]=false; } current_key.key=0; current_key.invalid_key=1; _queue_shader_change(); } FixedSpatialMaterial::~FixedSpatialMaterial() { if (material_mutex) material_mutex->lock(); if (shader_map.has(current_key)) { shader_map[current_key].users--; if (shader_map[current_key].users==0) { //deallocate shader, as it's no longer in use VS::get_singleton()->free(shader_map[current_key].shader); shader_map.erase(current_key); } VS::get_singleton()->material_set_shader(_get_material(),RID()); } if (material_mutex) material_mutex->unlock(); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/visual_server.cpp
1,301
/*************************************************************************/ /* visual_server.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "visual_server.h" #include "globals.h" #include "method_bind_ext.inc" VisualServer *VisualServer::singleton=NULL; VisualServer* (*VisualServer::create_func)()=NULL; VisualServer *VisualServer::get_singleton() { return singleton; } PoolVector<String> VisualServer::_shader_get_param_list(RID p_shader) const { //remove at some point PoolVector<String> pl; #if 0 List<StringName> params; shader_get_param_list(p_shader,&params); for(List<StringName>::Element *E=params.front();E;E=E->next()) { pl.push_back(E->get()); } #endif return pl; } VisualServer *VisualServer::create() { ERR_FAIL_COND_V(singleton,NULL); if (create_func) return create_func(); return NULL; } RID VisualServer::texture_create_from_image(const Image& p_image,uint32_t p_flags) { RID texture = texture_create(); texture_allocate(texture,p_image.get_width(), p_image.get_height(), p_image.get_format(), p_flags); //if it has mipmaps, use, else generate ERR_FAIL_COND_V(!texture.is_valid(),texture); texture_set_data(texture, p_image ); return texture; } RID VisualServer::get_test_texture() { if (test_texture.is_valid()) { return test_texture; }; #define TEST_TEXTURE_SIZE 256 PoolVector<uint8_t> test_data; test_data.resize(TEST_TEXTURE_SIZE*TEST_TEXTURE_SIZE*3); { PoolVector<uint8_t>::Write w=test_data.write(); for (int x=0;x<TEST_TEXTURE_SIZE;x++) { for (int y=0;y<TEST_TEXTURE_SIZE;y++) { Color c; int r=255-(x+y)/2; if ((x%(TEST_TEXTURE_SIZE/8))<2 ||(y%(TEST_TEXTURE_SIZE/8))<2) { c.r=y; c.g=r; c.b=x; } else { c.r=r; c.g=x; c.b=y; } w[(y*TEST_TEXTURE_SIZE+x)*3+0]=uint8_t(CLAMP(c.r*255,0,255)); w[(y*TEST_TEXTURE_SIZE+x)*3+1]=uint8_t(CLAMP(c.g*255,0,255)); w[(y*TEST_TEXTURE_SIZE+x)*3+2]=uint8_t(CLAMP(c.b*255,0,255)); } } } Image data(TEST_TEXTURE_SIZE,TEST_TEXTURE_SIZE,false,Image::FORMAT_RGB8,test_data); test_texture = texture_create_from_image(data); return test_texture; }; void VisualServer::_free_internal_rids() { if (test_texture.is_valid()) free(test_texture); if (white_texture.is_valid()) free(white_texture); if (test_material.is_valid()) free(test_material); for(int i=0;i<16;i++) { if (material_2d[i].is_valid()) free(material_2d[i]); } } RID VisualServer::_make_test_cube() { PoolVector<Vector3> vertices; PoolVector<Vector3> normals; PoolVector<float> tangents; PoolVector<Vector3> uvs; int vtx_idx=0; #define ADD_VTX(m_idx) \ vertices.push_back( face_points[m_idx] );\ normals.push_back( normal_points[m_idx] );\ tangents.push_back( normal_points[m_idx][1] );\ tangents.push_back( normal_points[m_idx][2] );\ tangents.push_back( normal_points[m_idx][0] );\ tangents.push_back( 1.0 );\ uvs.push_back( Vector3(uv_points[m_idx*2+0],uv_points[m_idx*2+1],0) );\ vtx_idx++;\ for (int i=0;i<6;i++) { Vector3 face_points[4]; Vector3 normal_points[4]; float uv_points[8]={0,0,0,1,1,1,1,0}; for (int j=0;j<4;j++) { float v[3]; v[0]=1.0; v[1]=1-2*((j>>1)&1); v[2]=v[1]*(1-2*(j&1)); for (int k=0;k<3;k++) { if (i<3) face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1); else face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1); } normal_points[j]=Vector3(); normal_points[j][i%3]=(i>=3?-1:1); } //tri 1 ADD_VTX(0); ADD_VTX(1); ADD_VTX(2); //tri 2 ADD_VTX(2); ADD_VTX(3); ADD_VTX(0); } RID test_cube = mesh_create(); Array d; d.resize(VS::ARRAY_MAX); d[VisualServer::ARRAY_NORMAL]= normals ; d[VisualServer::ARRAY_TANGENT]= tangents ; d[VisualServer::ARRAY_TEX_UV]= uvs ; d[VisualServer::ARRAY_VERTEX]= vertices ; PoolVector<int> indices; indices.resize(vertices.size()); for(int i=0;i<vertices.size();i++) indices.set(i,i); d[VisualServer::ARRAY_INDEX]=indices; mesh_add_surface_from_arrays( test_cube, PRIMITIVE_TRIANGLES,d ); /* test_material = fixed_material_create(); //material_set_flag(material, MATERIAL_FLAG_BILLBOARD_TOGGLE,true); fixed_material_set_texture( test_material, FIXED_MATERIAL_PARAM_DIFFUSE, get_test_texture() ); fixed_material_set_param( test_material, FIXED_MATERIAL_PARAM_SPECULAR_EXP, 70 ); fixed_material_set_param( test_material, FIXED_MATERIAL_PARAM_EMISSION, Color(0.2,0.2,0.2) ); fixed_material_set_param( test_material, FIXED_MATERIAL_PARAM_DIFFUSE, Color(1, 1, 1) ); fixed_material_set_param( test_material, FIXED_MATERIAL_PARAM_SPECULAR, Color(1,1,1) ); */ mesh_surface_set_material(test_cube, 0, test_material ); return test_cube; } RID VisualServer::make_sphere_mesh(int p_lats,int p_lons,float p_radius) { PoolVector<Vector3> vertices; PoolVector<Vector3> normals; for(int i = 1; i <= p_lats; i++) { double lat0 = Math_PI * (-0.5 + (double) (i - 1) / p_lats); double z0 = Math::sin(lat0); double zr0 = Math::cos(lat0); double lat1 = Math_PI * (-0.5 + (double) i / p_lats); double z1 = Math::sin(lat1); double zr1 = Math::cos(lat1); for(int j = p_lons; j >= 1; j--) { double lng0 = 2 * Math_PI * (double) (j - 1) / p_lons; double x0 = Math::cos(lng0); double y0 = Math::sin(lng0); double lng1 = 2 * Math_PI * (double) (j) / p_lons; double x1 = Math::cos(lng1); double y1 = Math::sin(lng1); Vector3 v[4]={ Vector3(x1 * zr0, z0, y1 *zr0), Vector3(x1 * zr1, z1, y1 *zr1), Vector3(x0 * zr1, z1, y0 *zr1), Vector3(x0 * zr0, z0, y0 *zr0) }; #define ADD_POINT(m_idx)\ normals.push_back(v[m_idx]); \ vertices.push_back(v[m_idx]*p_radius);\ ADD_POINT(0); ADD_POINT(1); ADD_POINT(2); ADD_POINT(2); ADD_POINT(3); ADD_POINT(0); } } RID mesh = mesh_create(); Array d; d.resize(VS::ARRAY_MAX); d[ARRAY_VERTEX]=vertices; d[ARRAY_NORMAL]=normals; mesh_add_surface_from_arrays(mesh,PRIMITIVE_TRIANGLES,d); return mesh; } RID VisualServer::material_2d_get(bool p_shaded, bool p_transparent, bool p_cut_alpha, bool p_opaque_prepass) { int version=0; if (p_shaded) version=1; if (p_transparent) version|=2; if (p_cut_alpha) version|=4; if (p_opaque_prepass) version|=8; if (material_2d[version].is_valid()) return material_2d[version]; //not valid, make /* material_2d[version]=fixed_material_create(); fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_USE_ALPHA,p_transparent); fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_USE_COLOR_ARRAY,true); fixed_material_set_flag(material_2d[version],FIXED_MATERIAL_FLAG_DISCARD_ALPHA,p_cut_alpha); material_set_flag(material_2d[version],MATERIAL_FLAG_UNSHADED,!p_shaded); material_set_flag(material_2d[version],MATERIAL_FLAG_DOUBLE_SIDED,true); material_set_depth_draw_mode(material_2d[version],p_opaque_prepass?MATERIAL_DEPTH_DRAW_OPAQUE_PRE_PASS_ALPHA:MATERIAL_DEPTH_DRAW_OPAQUE_ONLY); fixed_material_set_texture(material_2d[version],FIXED_MATERIAL_PARAM_DIFFUSE,get_white_texture()); //material cut alpha?*/ return material_2d[version]; } RID VisualServer::get_white_texture() { if (white_texture.is_valid()) return white_texture; PoolVector<uint8_t> wt; wt.resize(16*3); { PoolVector<uint8_t>::Write w =wt.write(); for(int i=0;i<16*3;i++) w[i]=255; } Image white(4,4,0,Image::FORMAT_RGB8,wt); white_texture=texture_create(); texture_allocate(white_texture,4,4,Image::FORMAT_RGB8); texture_set_data(white_texture,white); return white_texture; } Error VisualServer::_surface_set_data(Array p_arrays,uint32_t p_format,uint32_t *p_offsets,uint32_t p_stride,PoolVector<uint8_t> &r_vertex_array,int p_vertex_array_len,PoolVector<uint8_t> &r_index_array,int p_index_array_len,Rect3 &r_aabb,Vector<Rect3> r_bone_aabb) { PoolVector<uint8_t>::Write vw = r_vertex_array.write(); PoolVector<uint8_t>::Write iw; if (r_index_array.size()) { print_line("elements: "+itos(r_index_array.size())); iw=r_index_array.write(); } int max_bone=0; for(int ai=0;ai<VS::ARRAY_MAX;ai++) { if (!(p_format&(1<<ai))) // no array continue; switch(ai) { case VS::ARRAY_VERTEX: { if (p_format& VS::ARRAY_FLAG_USE_2D_VERTICES) { PoolVector<Vector2> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER ); PoolVector<Vector2>::Read read = array.read(); const Vector2* src=read.ptr(); // setting vertices means regenerating the AABB Rect2 aabb; if (p_format&ARRAY_COMPRESS_VERTEX) { for (int i=0;i<p_vertex_array_len;i++) { uint16_t vector[2]={ Math::make_half_float(src[i].x), Math::make_half_float(src[i].y) }; copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(uint16_t)*2); if (i==0) { aabb=Rect2(src[i],Vector2()); } else { aabb.expand_to( src[i] ); } } } else { for (int i=0;i<p_vertex_array_len;i++) { float vector[2]={ src[i].x, src[i].y }; copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(float)*2); if (i==0) { aabb=Rect2(src[i],Vector2()); } else { aabb.expand_to( src[i] ); } } } r_aabb=Rect3(Vector3(aabb.pos.x,aabb.pos.y,0),Vector3(aabb.size.x,aabb.size.y,0)); } else { PoolVector<Vector3> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER ); PoolVector<Vector3>::Read read = array.read(); const Vector3* src=read.ptr(); // setting vertices means regenerating the AABB Rect3 aabb; if (p_format&ARRAY_COMPRESS_VERTEX) { for (int i=0;i<p_vertex_array_len;i++) { uint16_t vector[4]={ Math::make_half_float(src[i].x), Math::make_half_float(src[i].y), Math::make_half_float(src[i].z), Math::make_half_float(1.0) }; copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(uint16_t)*4); if (i==0) { aabb=Rect3(src[i],Vector3()); } else { aabb.expand_to( src[i] ); } } } else { for (int i=0;i<p_vertex_array_len;i++) { float vector[3]={ src[i].x, src[i].y, src[i].z }; copymem(&vw[p_offsets[ai]+i*p_stride], vector, sizeof(float)*3); if (i==0) { aabb=Rect3(src[i],Vector3()); } else { aabb.expand_to( src[i] ); } } } r_aabb=aabb; } } break; case VS::ARRAY_NORMAL: { ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY, ERR_INVALID_PARAMETER ); PoolVector<Vector3> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER ); PoolVector<Vector3>::Read read = array.read(); const Vector3* src=read.ptr(); // setting vertices means regenerating the AABB if (p_format&ARRAY_COMPRESS_NORMAL) { for (int i=0;i<p_vertex_array_len;i++) { uint8_t vector[4]={ CLAMP(src[i].x*127,-128,127), CLAMP(src[i].y*127,-128,127), CLAMP(src[i].z*127,-128,127), 0, }; copymem(&vw[p_offsets[ai]+i*p_stride], vector, 4); } } else { for (int i=0;i<p_vertex_array_len;i++) { float vector[3]={ src[i].x, src[i].y, src[i].z }; copymem(&vw[p_offsets[ai]+i*p_stride], vector, 3*4); } } } break; case VS::ARRAY_TANGENT: { ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER ); PoolVector<real_t> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len*4, ERR_INVALID_PARAMETER ); PoolVector<real_t>::Read read = array.read(); const real_t* src = read.ptr(); if (p_format&ARRAY_COMPRESS_TANGENT) { for (int i=0;i<p_vertex_array_len;i++) { uint8_t xyzw[4]={ CLAMP(src[i*4+0]*127,-128,127), CLAMP(src[i*4+1]*127,-128,127), CLAMP(src[i*4+2]*127,-128,127), CLAMP(src[i*4+3]*127,-128,127) }; copymem(&vw[p_offsets[ai]+i*p_stride], xyzw, 4); } } else { for (int i=0;i<p_vertex_array_len;i++) { float xyzw[4]={ src[i*4+0], src[i*4+1], src[i*4+2], src[i*4+3] }; copymem(&vw[p_offsets[ai]+i*p_stride], xyzw, 4*4); } } } break; case VS::ARRAY_COLOR: { ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_COLOR_ARRAY, ERR_INVALID_PARAMETER ); PoolVector<Color> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len, ERR_INVALID_PARAMETER ); PoolVector<Color>::Read read = array.read(); const Color* src = read.ptr(); if (p_format&ARRAY_COMPRESS_COLOR) { for (int i=0;i<p_vertex_array_len;i++) { uint8_t colors[4]; for(int j=0;j<4;j++) { colors[j]=CLAMP( int((src[i][j])*255.0), 0,255 ); } copymem(&vw[p_offsets[ai]+i*p_stride], colors, 4); } } else { for (int i=0;i<p_vertex_array_len;i++) { copymem(&vw[p_offsets[ai]+i*p_stride], &src[i], 4*4); } } } break; case VS::ARRAY_TEX_UV: { ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER ); PoolVector<Vector2> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len , ERR_INVALID_PARAMETER); PoolVector<Vector2>::Read read = array.read(); const Vector2 * src=read.ptr(); if (p_format&ARRAY_COMPRESS_TEX_UV) { for (int i=0;i<p_vertex_array_len;i++) { uint16_t uv[2]={ Math::make_half_float(src[i].x) , Math::make_half_float(src[i].y) }; copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*2); } } else { for (int i=0;i<p_vertex_array_len;i++) { float uv[2]={ src[i].x , src[i].y }; copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*4); } } } break; case VS::ARRAY_TEX_UV2: { ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_VECTOR3_ARRAY && p_arrays[ai].get_type() != Variant::POOL_VECTOR2_ARRAY, ERR_INVALID_PARAMETER ); PoolVector<Vector2> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len , ERR_INVALID_PARAMETER); PoolVector<Vector2>::Read read = array.read(); const Vector2 * src=read.ptr(); if (p_format&ARRAY_COMPRESS_TEX_UV2) { for (int i=0;i<p_vertex_array_len;i++) { uint16_t uv[2]={ Math::make_half_float(src[i].x) , Math::make_half_float(src[i].y) }; copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*2); } } else { for (int i=0;i<p_vertex_array_len;i++) { float uv[2]={ src[i].x , src[i].y }; copymem(&vw[p_offsets[ai]+i*p_stride], uv, 2*4); } } } break; case VS::ARRAY_WEIGHTS: { ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_REAL_ARRAY, ERR_INVALID_PARAMETER ); PoolVector<real_t> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER ); PoolVector<real_t>::Read read = array.read(); const real_t * src = read.ptr(); if (p_format&ARRAY_COMPRESS_WEIGHTS) { for (int i=0;i<p_vertex_array_len;i++) { uint16_t data[VS::ARRAY_WEIGHTS_SIZE]; for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) { data[j]=CLAMP(src[i*VS::ARRAY_WEIGHTS_SIZE+j]*65535,0,65535); } copymem(&vw[p_offsets[ai]+i*p_stride], data, 2*4); } } else { for (int i=0;i<p_vertex_array_len;i++) { float data[VS::ARRAY_WEIGHTS_SIZE]; for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) { data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j]; } copymem(&vw[p_offsets[ai]+i*p_stride], data, 4*4); } } } break; case VS::ARRAY_BONES: { ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY, ERR_INVALID_PARAMETER ); PoolVector<int> array = p_arrays[ai]; ERR_FAIL_COND_V( array.size() != p_vertex_array_len*VS::ARRAY_WEIGHTS_SIZE, ERR_INVALID_PARAMETER ); PoolVector<int>::Read read = array.read(); const int * src = read.ptr(); if (!(p_format&ARRAY_FLAG_USE_16_BIT_BONES)) { for (int i=0;i<p_vertex_array_len;i++) { uint8_t data[VS::ARRAY_WEIGHTS_SIZE]; for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) { data[j]=CLAMP(src[i*VS::ARRAY_WEIGHTS_SIZE+j],0,255); max_bone=MAX(data[j],max_bone); } copymem(&vw[p_offsets[ai]+i*p_stride], data, 4); } } else { for (int i=0;i<p_vertex_array_len;i++) { uint16_t data[VS::ARRAY_WEIGHTS_SIZE]; for (int j=0;j<VS::ARRAY_WEIGHTS_SIZE;j++) { data[j]=src[i*VS::ARRAY_WEIGHTS_SIZE+j]; max_bone=MAX(data[j],max_bone); } copymem(&vw[p_offsets[ai]+i*p_stride], data, 2*4); } } } break; case VS::ARRAY_INDEX: { ERR_FAIL_COND_V( p_index_array_len<=0, ERR_INVALID_DATA ); ERR_FAIL_COND_V( p_arrays[ai].get_type() != Variant::POOL_INT_ARRAY, ERR_INVALID_PARAMETER ); PoolVector<int> indices = p_arrays[ai]; ERR_FAIL_COND_V( indices.size() == 0, ERR_INVALID_PARAMETER ); ERR_FAIL_COND_V( indices.size() != p_index_array_len, ERR_INVALID_PARAMETER ); /* determine wether using 16 or 32 bits indices */ PoolVector<int>::Read read = indices.read(); const int *src=read.ptr(); for (int i=0;i<p_index_array_len;i++) { if (p_vertex_array_len<(1<<16)) { uint16_t v=src[i]; copymem(&iw[i*2], &v, 2); } else { uint32_t v=src[i]; copymem(&iw[i*4], &v, 4); } } } break; default: { ERR_FAIL_V( ERR_INVALID_DATA ); } } } if (p_format&VS::ARRAY_FORMAT_BONES) { //create AABBs for each detected bone int total_bones = max_bone+1; bool first = r_bone_aabb.size()==0; r_bone_aabb.resize(total_bones); if (first) { for(int i=0;i<total_bones;i++) { r_bone_aabb[i].size==Vector3(-1,-1,-1); //negative means unused } } PoolVector<Vector3> vertices = p_arrays[VS::ARRAY_VERTEX]; PoolVector<int> bones = p_arrays[VS::ARRAY_BONES]; PoolVector<float> weights = p_arrays[VS::ARRAY_WEIGHTS]; bool any_valid=false; if (vertices.size() && bones.size()==vertices.size()*4 && weights.size()==bones.size()) { int vs = vertices.size(); PoolVector<Vector3>::Read rv =vertices.read(); PoolVector<int>::Read rb=bones.read(); PoolVector<float>::Read rw=weights.read(); Rect3 *bptr = r_bone_aabb.ptr(); for(int i=0;i<vs;i++) { Vector3 v = rv[i]; for(int j=0;j<4;j++) { int idx = rb[i*4+j]; float w = rw[i*4+j]; if (w==0) continue;//break; ERR_FAIL_INDEX_V(idx,total_bones,ERR_INVALID_DATA); if (bptr->size.x<0) { //first bptr[idx]=Rect3(); bptr[idx].pos=v; any_valid=true; } else { bptr[idx].expand_to(v); } } } } if (!any_valid && first) { r_bone_aabb.clear(); } } return OK; } void VisualServer::mesh_add_surface_from_arrays(RID p_mesh,PrimitiveType p_primitive,const Array& p_arrays,const Array& p_blend_shapes,uint32_t p_compress_format) { ERR_FAIL_INDEX( p_primitive, VS::PRIMITIVE_MAX ); ERR_FAIL_COND(p_arrays.size()!=VS::ARRAY_MAX); uint32_t format=0; // validation int index_array_len=0; int array_len=0; for(int i=0;i<p_arrays.size();i++) { if (p_arrays[i].get_type()==Variant::NIL) continue; format|=(1<<i); if (i==VS::ARRAY_VERTEX) { Variant var = p_arrays[i]; switch(var.get_type()) { case Variant::POOL_VECTOR2_ARRAY: { PoolVector<Vector2> v2 = var; array_len=v2.size(); } break; case Variant::POOL_VECTOR3_ARRAY: { PoolVector<Vector3> v3 = var; array_len=v3.size(); } break; default: { Array v = var; array_len=v.size(); } break; } array_len=PoolVector3Array(p_arrays[i]).size(); ERR_FAIL_COND(array_len==0); } else if (i==VS::ARRAY_INDEX) { index_array_len=PoolIntArray(p_arrays[i]).size(); } } ERR_FAIL_COND((format&VS::ARRAY_FORMAT_VERTEX)==0); // mandatory if (p_blend_shapes.size()) { //validate format for morphs for(int i=0;i<p_blend_shapes.size();i++) { uint32_t bsformat=0; Array arr = p_blend_shapes[i]; for(int j=0;j<arr.size();j++) { if (arr[j].get_type()!=Variant::NIL) bsformat|=(1<<j); } ERR_FAIL_COND( (bsformat)!=(format&(VS::ARRAY_FORMAT_INDEX-1))); } } uint32_t offsets[VS::ARRAY_MAX]; int total_elem_size=0; for (int i=0;i<VS::ARRAY_MAX;i++) { offsets[i]=0; //reset if (!(format&(1<<i))) // no array continue; int elem_size=0; switch(i) { case VS::ARRAY_VERTEX: { Variant arr = p_arrays[0]; if (arr.get_type()==Variant::POOL_VECTOR2_ARRAY) { elem_size=2; p_compress_format|=ARRAY_FLAG_USE_2D_VERTICES; } else if (arr.get_type()==Variant::POOL_VECTOR3_ARRAY) { p_compress_format&=~ARRAY_FLAG_USE_2D_VERTICES; elem_size=3; } else { elem_size=(p_compress_format&ARRAY_FLAG_USE_2D_VERTICES)?2:3; } if (p_compress_format&ARRAY_COMPRESS_VERTEX) { elem_size*=sizeof(int16_t); } else { elem_size*=sizeof(float); } if (elem_size==6) { //had to pad elem_size=8; } } break; case VS::ARRAY_NORMAL: { if (p_compress_format&ARRAY_COMPRESS_NORMAL) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*3; } } break; case VS::ARRAY_TANGENT: { if (p_compress_format&ARRAY_COMPRESS_TANGENT) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*4; } } break; case VS::ARRAY_COLOR: { if (p_compress_format&ARRAY_COMPRESS_COLOR) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*4; } } break; case VS::ARRAY_TEX_UV: { if (p_compress_format&ARRAY_COMPRESS_TEX_UV) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*2; } } break; case VS::ARRAY_TEX_UV2: { if (p_compress_format&ARRAY_COMPRESS_TEX_UV2) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*2; } } break; case VS::ARRAY_WEIGHTS: { if (p_compress_format&ARRAY_COMPRESS_WEIGHTS) { elem_size=sizeof(uint16_t)*4; } else { elem_size=sizeof(float)*4; } } break; case VS::ARRAY_BONES: { PoolVector<int> bones = p_arrays[VS::ARRAY_BONES]; int max_bone=0; { int bc = bones.size(); PoolVector<int>::Read r=bones.read(); for(int j=0;j<bc;j++) { max_bone=MAX(r[j],max_bone); } } if (max_bone > 255) { p_compress_format|=ARRAY_FLAG_USE_16_BIT_BONES; elem_size=sizeof(uint16_t)*4; } else { p_compress_format&=~ARRAY_FLAG_USE_16_BIT_BONES; elem_size=sizeof(uint32_t); } } break; case VS::ARRAY_INDEX: { if (index_array_len<=0) { ERR_PRINT("index_array_len==NO_INDEX_ARRAY"); break; } /* determine wether using 16 or 32 bits indices */ if (array_len>=(1<<16)) { elem_size=4; } else { elem_size=2; } offsets[i]=elem_size; continue; } break; default: { ERR_FAIL( ); } } offsets[i]=total_elem_size; total_elem_size+=elem_size; } uint32_t mask = (1<<ARRAY_MAX)-1; format|=(~mask)&p_compress_format; //make the full format int array_size = total_elem_size * array_len; PoolVector<uint8_t> vertex_array; vertex_array.resize(array_size); int index_array_size = offsets[VS::ARRAY_INDEX]*index_array_len; PoolVector<uint8_t> index_array; index_array.resize(index_array_size); Rect3 aabb; Vector<Rect3> bone_aabb; Error err = _surface_set_data(p_arrays,format,offsets,total_elem_size,vertex_array,array_len,index_array,index_array_len,aabb,bone_aabb); if (err) { ERR_EXPLAIN("Invalid array format for surface"); ERR_FAIL_COND(err!=OK); } Vector<PoolVector<uint8_t> > blend_shape_data; for(int i=0;i<p_blend_shapes.size();i++) { PoolVector<uint8_t> vertex_array_shape; vertex_array_shape.resize(array_size); PoolVector<uint8_t> noindex; Rect3 laabb; Error err = _surface_set_data(p_blend_shapes[i],format&~ARRAY_FORMAT_INDEX,offsets,total_elem_size,vertex_array_shape,array_len,noindex,0,laabb,bone_aabb); aabb.merge_with(laabb); if (err) { ERR_EXPLAIN("Invalid blend shape array format for surface"); ERR_FAIL_COND(err!=OK); } blend_shape_data.push_back(vertex_array_shape); } mesh_add_surface(p_mesh,format,p_primitive,vertex_array,array_len,index_array,index_array_len,aabb,blend_shape_data,bone_aabb); } Array VisualServer::_get_array_from_surface(uint32_t p_format,PoolVector<uint8_t> p_vertex_data,int p_vertex_len,PoolVector<uint8_t> p_index_data,int p_index_len) const { uint32_t offsets[ARRAY_MAX]; int total_elem_size=0; for (int i=0;i<VS::ARRAY_MAX;i++) { offsets[i]=0; //reset if (!(p_format&(1<<i))) // no array continue; int elem_size=0; switch(i) { case VS::ARRAY_VERTEX: { if (p_format&ARRAY_FLAG_USE_2D_VERTICES) { elem_size=2; } else { elem_size=3; } if (p_format&ARRAY_COMPRESS_VERTEX) { elem_size*=sizeof(int16_t); } else { elem_size*=sizeof(float); } if (elem_size==6) { elem_size=8; } } break; case VS::ARRAY_NORMAL: { if (p_format&ARRAY_COMPRESS_NORMAL) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*3; } } break; case VS::ARRAY_TANGENT: { if (p_format&ARRAY_COMPRESS_TANGENT) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*4; } } break; case VS::ARRAY_COLOR: { if (p_format&ARRAY_COMPRESS_COLOR) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*4; } } break; case VS::ARRAY_TEX_UV: { if (p_format&ARRAY_COMPRESS_TEX_UV) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*2; } } break; case VS::ARRAY_TEX_UV2: { if (p_format&ARRAY_COMPRESS_TEX_UV2) { elem_size=sizeof(uint32_t); } else { elem_size=sizeof(float)*2; } } break; case VS::ARRAY_WEIGHTS: { if (p_format&ARRAY_COMPRESS_WEIGHTS) { elem_size=sizeof(uint16_t)*4; } else { elem_size=sizeof(float)*4; } } break; case VS::ARRAY_BONES: { if (p_format&ARRAY_FLAG_USE_16_BIT_BONES) { elem_size=sizeof(uint16_t)*4; } else { elem_size=sizeof(uint32_t); } } break; case VS::ARRAY_INDEX: { if (p_index_len<=0) { ERR_PRINT("index_array_len==NO_INDEX_ARRAY"); break; } /* determine wether using 16 or 32 bits indices */ if (p_vertex_len>=(1<<16)) { elem_size=4; } else { elem_size=2; } offsets[i]=elem_size; continue; } break; default: { ERR_FAIL_V( Array() ); } } offsets[i]=total_elem_size; total_elem_size+=elem_size; } Array ret; ret.resize(VS::ARRAY_MAX); PoolVector<uint8_t>::Read r = p_vertex_data.read(); for(int i=0;i<VS::ARRAY_MAX;i++) { if (!(p_format&(1<<i))) continue; switch(i) { case VS::ARRAY_VERTEX: { if (p_format&ARRAY_FLAG_USE_2D_VERTICES) { PoolVector<Vector2> arr_2d; arr_2d.resize(p_vertex_len); if (p_format&ARRAY_COMPRESS_VERTEX) { PoolVector<Vector2>::Write w = arr_2d.write(); for(int j=0;j<p_vertex_len;j++) { const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1])); } } else { PoolVector<Vector2>::Write w = arr_2d.write(); for(int j=0;j<p_vertex_len;j++) { const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector2(v[0],v[1]); } } ret[i]=arr_2d; } else { PoolVector<Vector3> arr_3d; arr_3d.resize(p_vertex_len); if (p_format&ARRAY_COMPRESS_VERTEX) { PoolVector<Vector3>::Write w = arr_3d.write(); for(int j=0;j<p_vertex_len;j++) { const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector3(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1]),Math::halfptr_to_float(&v[2])); } } else { PoolVector<Vector3>::Write w = arr_3d.write(); for(int j=0;j<p_vertex_len;j++) { const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector3(v[0],v[1],v[2]); } } ret[i]=arr_3d; } } break; case VS::ARRAY_NORMAL: { PoolVector<Vector3> arr; arr.resize(p_vertex_len); if (p_format&ARRAY_COMPRESS_NORMAL) { PoolVector<Vector3>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector3( float(v[0]/255.0)*2.0-1.0, float(v[1]/255.0)*2.0-1.0, float(v[2]/255.0)*2.0-1.0 ); } } else { PoolVector<Vector3>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector3(v[0],v[1],v[2]); } } ret[i]=arr; } break; case VS::ARRAY_TANGENT: { PoolVector<float> arr; arr.resize(p_vertex_len*4); if (p_format&ARRAY_COMPRESS_TANGENT) { PoolVector<float>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]]; for(int k=0;k<4;k++) { w[j*4+k]=float(v[k]/255.0)*2.0-1.0; } } } else { PoolVector<float>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; for(int k=0;k<4;k++) { w[j*4+k]=v[k]; } } } ret[i]=arr; } break; case VS::ARRAY_COLOR: { PoolVector<Color> arr; arr.resize(p_vertex_len); if (p_format&ARRAY_COMPRESS_COLOR) { PoolVector<Color>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]]; w[j]=Color( float(v[0]/255.0)*2.0-1.0, float(v[1]/255.0)*2.0-1.0, float(v[2]/255.0)*2.0-1.0, float(v[3]/255.0)*2.0-1.0 ); } } else { PoolVector<Color>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; w[j]=Color(v[0],v[1],v[2],v[3]); } } ret[i]=arr; } break; case VS::ARRAY_TEX_UV: { PoolVector<Vector2> arr; arr.resize(p_vertex_len); if (p_format&ARRAY_COMPRESS_TEX_UV) { PoolVector<Vector2>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1])); } } else { PoolVector<Vector2>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector2(v[0],v[1]); } } ret[i]=arr; } break; case VS::ARRAY_TEX_UV2: { PoolVector<Vector2> arr; arr.resize(p_vertex_len); if (p_format&ARRAY_COMPRESS_TEX_UV2) { PoolVector<Vector2>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector2(Math::halfptr_to_float(&v[0]),Math::halfptr_to_float(&v[1])); } } else { PoolVector<Vector2>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; w[j]=Vector2(v[0],v[1]); } } ret[i]=arr; } break; case VS::ARRAY_WEIGHTS: { PoolVector<float> arr; arr.resize(p_vertex_len*4); if (p_format&ARRAY_COMPRESS_WEIGHTS) { PoolVector<float>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; for(int k=0;k<4;k++) { w[j*4+k]=float(v[k]/65535.0)*2.0-1.0; } } } else { PoolVector<float>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const float *v = (const float*)&r[j*total_elem_size+offsets[i]]; for(int k=0;k<4;k++) { w[j*4+k]=v[k]; } } } ret[i]=arr; } break; case VS::ARRAY_BONES: { PoolVector<int> arr; arr.resize(p_vertex_len*4); if (p_format&ARRAY_FLAG_USE_16_BIT_BONES) { PoolVector<int>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const uint16_t *v = (const uint16_t*)&r[j*total_elem_size+offsets[i]]; for(int k=0;k<4;k++) { w[j*4+k]=v[k]; } } } else { PoolVector<int>::Write w = arr.write(); for(int j=0;j<p_vertex_len;j++) { const uint8_t *v = (const uint8_t*)&r[j*total_elem_size+offsets[i]]; for(int k=0;k<4;k++) { w[j*4+k]=v[k]; } } } ret[i]=arr; } break; case VS::ARRAY_INDEX: { /* determine wether using 16 or 32 bits indices */ PoolVector<uint8_t>::Read ir = p_index_data.read(); PoolVector<int> arr; arr.resize(p_index_len); if (p_vertex_len<(1<<16)) { PoolVector<int>::Write w = arr.write(); for(int j=0;j<p_index_len;j++) { const uint16_t *v = (const uint16_t*)&ir[j*2]; w[j]=*v; } } else { PoolVector<int>::Write w = arr.write(); for(int j=0;j<p_index_len;j++) { const int *v = (const int*)&ir[j*4]; w[j]=*v; } } ret[i]=arr; } break; default: { ERR_FAIL_V( ret ); } } } return ret; } Array VisualServer::mesh_surface_get_arrays(RID p_mesh,int p_surface) const { PoolVector<uint8_t> vertex_data = mesh_surface_get_array(p_mesh,p_surface); ERR_FAIL_COND_V(vertex_data.size()==0,Array()); int vertex_len = mesh_surface_get_array_len(p_mesh,p_surface); PoolVector<uint8_t> index_data = mesh_surface_get_index_array(p_mesh,p_surface); int index_len = mesh_surface_get_array_index_len(p_mesh,p_surface); uint32_t format = mesh_surface_get_format(p_mesh,p_surface); return _get_array_from_surface(format,vertex_data,vertex_len,index_data,index_len); } void VisualServer::_bind_methods() { ClassDB::bind_method(_MD("texture_create"),&VisualServer::texture_create); ClassDB::bind_method(_MD("texture_create_from_image"),&VisualServer::texture_create_from_image,DEFVAL( TEXTURE_FLAGS_DEFAULT ) ); //ClassDB::bind_method(_MD("texture_allocate"),&VisualServer::texture_allocate,DEFVAL( TEXTURE_FLAGS_DEFAULT ) ); //ClassDB::bind_method(_MD("texture_set_data"),&VisualServer::texture_blit_rect,DEFVAL( CUBEMAP_LEFT ) ); //ClassDB::bind_method(_MD("texture_get_rect"),&VisualServer::texture_get_rect ); ClassDB::bind_method(_MD("texture_set_flags"),&VisualServer::texture_set_flags ); ClassDB::bind_method(_MD("texture_get_flags"),&VisualServer::texture_get_flags ); ClassDB::bind_method(_MD("texture_get_width"),&VisualServer::texture_get_width ); ClassDB::bind_method(_MD("texture_get_height"),&VisualServer::texture_get_height ); ClassDB::bind_method(_MD("texture_set_shrink_all_x2_on_set_data","shrink"),&VisualServer::texture_set_shrink_all_x2_on_set_data ); } void VisualServer::_canvas_item_add_style_box(RID p_item, const Rect2& p_rect, const Rect2& p_source, RID p_texture,const Vector<float>& p_margins, const Color& p_modulate) { ERR_FAIL_COND(p_margins.size()!=4); //canvas_item_add_style_box(p_item,p_rect,p_source,p_texture,Vector2(p_margins[0],p_margins[1]),Vector2(p_margins[2],p_margins[3]),true,p_modulate); } void VisualServer::_camera_set_orthogonal(RID p_camera,float p_size,float p_z_near,float p_z_far) { camera_set_orthogonal(p_camera,p_size,p_z_near,p_z_far); } void VisualServer::mesh_add_surface_from_mesh_data( RID p_mesh, const Geometry::MeshData& p_mesh_data) { #if 1 PoolVector<Vector3> vertices; PoolVector<Vector3> normals; for (int i=0;i<p_mesh_data.faces.size();i++) { const Geometry::MeshData::Face& f = p_mesh_data.faces[i]; for (int j=2;j<f.indices.size();j++) { #define _ADD_VERTEX(m_idx)\ vertices.push_back( p_mesh_data.vertices[ f.indices[m_idx] ] );\ normals.push_back( f.plane.normal ); _ADD_VERTEX( 0 ); _ADD_VERTEX( j-1 ); _ADD_VERTEX( j ); } } Array d; d.resize(VS::ARRAY_MAX); d[ARRAY_VERTEX]=vertices; d[ARRAY_NORMAL]=normals; mesh_add_surface_from_arrays(p_mesh,PRIMITIVE_TRIANGLES, d); #else PoolVector<Vector3> vertices; for (int i=0;i<p_mesh_data.edges.size();i++) { const Geometry::MeshData::Edge& f = p_mesh_data.edges[i]; vertices.push_back(p_mesh_data.vertices[ f.a]); vertices.push_back(p_mesh_data.vertices[ f.b]); } Array d; d.resize(VS::ARRAY_MAX); d[ARRAY_VERTEX]=vertices; mesh_add_surface(p_mesh,PRIMITIVE_LINES, d); #endif } void VisualServer::mesh_add_surface_from_planes( RID p_mesh, const PoolVector<Plane>& p_planes) { Geometry::MeshData mdata = Geometry::build_convex_mesh(p_planes); mesh_add_surface_from_mesh_data(p_mesh,mdata); } void VisualServer::immediate_vertex_2d(RID p_immediate,const Vector2& p_vertex) { immediate_vertex(p_immediate,Vector3(p_vertex.x,p_vertex.y,0)); } RID VisualServer::instance_create2(RID p_base, RID p_scenario) { RID instance = instance_create(); instance_set_base(instance,p_base); instance_set_scenario(instance,p_scenario); return instance; } VisualServer::VisualServer() { //ERR_FAIL_COND(singleton); singleton=this; } VisualServer::~VisualServer() { singleton=NULL; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
thirdparty/zlib/uncompr.c
74
/* uncompr.c -- decompress a memory buffer * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ /* @(#) $Id$ */ #define ZLIB_INTERNAL #include "zlib.h" /* =========================================================================== Decompresses the source buffer into the destination buffer. *sourceLen is the byte length of the source buffer. Upon entry, *destLen is the total size of the destination buffer, which must be large enough to hold the entire uncompressed data. (The size of the uncompressed data must have been saved previously by the compressor and transmitted to the decompressor by some mechanism outside the scope of this compression library.) Upon exit, *destLen is the size of the decompressed data and *sourceLen is the number of source bytes consumed. Upon return, source + *sourceLen points to the first unused input byte. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if there was not enough room in the output buffer, or Z_DATA_ERROR if the input data was corrupted, including if the input data is an incomplete zlib stream. */ int ZEXPORT uncompress2 (dest, destLen, source, sourceLen) Bytef *dest; uLongf *destLen; const Bytef *source; uLong *sourceLen; { z_stream stream; int err; const uInt max = (uInt)-1; uLong len, left; Byte buf[1]; /* for detection of incomplete stream when *destLen == 0 */ len = *sourceLen; if (*destLen) { left = *destLen; *destLen = 0; } else { left = 1; dest = buf; } stream.next_in = (z_const Bytef *)source; stream.avail_in = 0; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; stream.opaque = (voidpf)0; err = inflateInit(&stream); if (err != Z_OK) return err; stream.next_out = dest; stream.avail_out = 0; do { if (stream.avail_out == 0) { stream.avail_out = left > (uLong)max ? max : (uInt)left; left -= stream.avail_out; } if (stream.avail_in == 0) { stream.avail_in = len > (uLong)max ? max : (uInt)len; len -= stream.avail_in; } err = inflate(&stream, Z_NO_FLUSH); } while (err == Z_OK); *sourceLen -= len + stream.avail_in; if (dest != buf) *destLen = stream.total_out; else if (stream.total_out && err == Z_BUF_ERROR) left = 1; inflateEnd(&stream); return err == Z_STREAM_END ? Z_OK : err == Z_NEED_DICT ? Z_DATA_ERROR : err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR : err; } int ZEXPORT uncompress (dest, destLen, source, sourceLen) Bytef *dest; uLongf *destLen; const Bytef *source; uLong sourceLen; { return uncompress2(dest, destLen, source, &sourceLen); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
tools/editor/editor_audio_buses.cpp
1,192
#include "editor_audio_buses.h" #include "editor_node.h" #include "servers/audio_server.h" #include "os/keyboard.h" #include "io/resource_saver.h" #include "filesystem_dock.h" void EditorAudioBus::_notification(int p_what) { if (p_what==NOTIFICATION_READY) { vu_l->set_under_texture(get_icon("BusVuEmpty","EditorIcons")); vu_l->set_progress_texture(get_icon("BusVuFull","EditorIcons")); vu_r->set_under_texture(get_icon("BusVuEmpty","EditorIcons")); vu_r->set_progress_texture(get_icon("BusVuFull","EditorIcons")); scale->set_texture( get_icon("BusVuDb","EditorIcons")); disabled_vu = get_icon("BusVuFrozen","EditorIcons"); prev_active=true; update_bus(); set_process(true); } if (p_what==NOTIFICATION_DRAW) { if (has_focus()) { draw_style_box(get_stylebox("focus","Button"),Rect2(Vector2(),get_size())); } } if (p_what==NOTIFICATION_PROCESS) { float real_peak[2]={-100,-100}; bool activity_found=false; int cc; switch(AudioServer::get_singleton()->get_speaker_mode()) { case AudioServer::SPEAKER_MODE_STEREO: cc = 1; break; case AudioServer::SPEAKER_SURROUND_51: cc = 4; break; case AudioServer::SPEAKER_SURROUND_71: cc = 5; break; } for(int i=0;i<cc;i++) { if (AudioServer::get_singleton()->is_bus_channel_active(get_index(),i)) { activity_found=true; real_peak[0]=MAX(real_peak[0],AudioServer::get_singleton()->get_bus_peak_volume_left_db(get_index(),i)); real_peak[1]=MAX(real_peak[1],AudioServer::get_singleton()->get_bus_peak_volume_right_db(get_index(),i)); } } if (real_peak[0]>peak_l) { peak_l = real_peak[0]; } else { peak_l-=get_process_delta_time()*60.0; } if (real_peak[1]>peak_r) { peak_r = real_peak[1]; } else { peak_r-=get_process_delta_time()*60.0; } vu_l->set_value(peak_l); vu_r->set_value(peak_r); if (activity_found!=prev_active) { if (activity_found) { vu_l->set_over_texture(Ref<Texture>()); vu_r->set_over_texture(Ref<Texture>()); } else { vu_l->set_over_texture(disabled_vu); vu_r->set_over_texture(disabled_vu); } prev_active=activity_found; } } if (p_what==NOTIFICATION_VISIBILITY_CHANGED) { peak_l=-100; peak_r=-100; prev_active=true; set_process(is_visible_in_tree()); } } void EditorAudioBus::update_send() { send->clear(); if (get_index()==0) { send->set_disabled(true); send->set_text("Speakers"); } else { send->set_disabled(false); StringName current_send = AudioServer::get_singleton()->get_bus_send(get_index()); int current_send_index=0; //by default to master for(int i=0;i<get_index();i++) { StringName send_name = AudioServer::get_singleton()->get_bus_name(i); send->add_item(send_name); if (send_name==current_send) { current_send_index=i; } } send->select(current_send_index); } } void EditorAudioBus::update_bus() { if (updating_bus) return; updating_bus=true; int index = get_index(); slider->set_value(AudioServer::get_singleton()->get_bus_volume_db(index)); track_name->set_text(AudioServer::get_singleton()->get_bus_name(index)); if (get_index()==0) track_name->set_editable(false); solo->set_pressed( AudioServer::get_singleton()->is_bus_solo(index)); mute->set_pressed( AudioServer::get_singleton()->is_bus_mute(index)); bypass->set_pressed( AudioServer::get_singleton()->is_bus_bypassing_effects(index)); // effects.. effects->clear(); TreeItem *root = effects->create_item(); for(int i=0;i<AudioServer::get_singleton()->get_bus_effect_count(index);i++) { Ref<AudioEffect> afx = AudioServer::get_singleton()->get_bus_effect(index,i); TreeItem *fx = effects->create_item(root); fx->set_cell_mode(0,TreeItem::CELL_MODE_CHECK); fx->set_editable(0,true); fx->set_checked(0,AudioServer::get_singleton()->is_bus_effect_enabled(index,i)); fx->set_text(0,afx->get_name()); fx->set_metadata(0,i); } TreeItem *add = effects->create_item(root); add->set_cell_mode(0,TreeItem::CELL_MODE_CUSTOM); add->set_editable(0,true); add->set_selectable(0,false); add->set_text(0,"Add Effect"); update_send(); updating_bus=false; } void EditorAudioBus::_name_changed(const String& p_new_name) { if (p_new_name==AudioServer::get_singleton()->get_bus_name(get_index())) return; String attempt=p_new_name; int attempts=1; while(true) { bool name_free=true; for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) { if (AudioServer::get_singleton()->get_bus_name(i)==attempt) { name_free=false; break; } } if (name_free) { break; } attempts++; attempt=p_new_name+" "+itos(attempts); } updating_bus=true; UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); StringName current = AudioServer::get_singleton()->get_bus_name(get_index()); ur->create_action("Rename Audio Bus"); ur->add_do_method(AudioServer::get_singleton(),"set_bus_name",get_index(),attempt); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_name",get_index(),current); for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) { if (AudioServer::get_singleton()->get_bus_send(i)==current) { ur->add_do_method(AudioServer::get_singleton(),"set_bus_send",i,attempt); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_send",i,current); } } ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->add_do_method(buses,"_update_sends"); ur->add_undo_method(buses,"_update_sends"); ur->commit_action(); updating_bus=false; } void EditorAudioBus::_volume_db_changed(float p_db){ if (updating_bus) return; updating_bus=true; UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Change Audio Bus Volume",UndoRedo::MERGE_ENDS); ur->add_do_method(AudioServer::get_singleton(),"set_bus_volume_db",get_index(),p_db); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_volume_db",get_index(),AudioServer::get_singleton()->get_bus_volume_db(get_index())); ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->commit_action(); updating_bus=false; } void EditorAudioBus::_solo_toggled(){ updating_bus=true; UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Toggle Audio Bus Solo"); ur->add_do_method(AudioServer::get_singleton(),"set_bus_solo",get_index(),solo->is_pressed()); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_solo",get_index(),AudioServer::get_singleton()->is_bus_solo(get_index())); ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->commit_action(); updating_bus=false; } void EditorAudioBus::_mute_toggled(){ updating_bus=true; UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Toggle Audio Bus Mute"); ur->add_do_method(AudioServer::get_singleton(),"set_bus_mute",get_index(),mute->is_pressed()); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_mute",get_index(),AudioServer::get_singleton()->is_bus_mute(get_index())); ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->commit_action(); updating_bus=false; } void EditorAudioBus::_bypass_toggled(){ updating_bus=true; UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Toggle Audio Bus Bypass Effects"); ur->add_do_method(AudioServer::get_singleton(),"set_bus_bypass_effects",get_index(),bypass->is_pressed()); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_bypass_effects",get_index(),AudioServer::get_singleton()->is_bus_bypassing_effects(get_index())); ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->commit_action(); updating_bus=false; } void EditorAudioBus::_send_selected(int p_which) { updating_bus=true; UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Select Audio Bus Send"); ur->add_do_method(AudioServer::get_singleton(),"set_bus_send",get_index(),send->get_item_text(p_which)); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_send",get_index(),AudioServer::get_singleton()->get_bus_send(get_index())); ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->commit_action(); updating_bus=false; } void EditorAudioBus::_effect_selected() { TreeItem *effect = effects->get_selected(); if (!effect) return; updating_bus=true; if (effect->get_metadata(0)!=Variant()) { int index = effect->get_metadata(0); Ref<AudioEffect> effect = AudioServer::get_singleton()->get_bus_effect(get_index(),index); if (effect.is_valid()) { EditorNode::get_singleton()->push_item(effect.ptr()); } } updating_bus=false; } void EditorAudioBus::_effect_edited() { if (updating_bus) return; TreeItem *effect = effects->get_edited(); if (!effect) return; if (effect->get_metadata(0)==Variant()) { Rect2 area = effects->get_item_rect(effect); effect_options->set_pos(effects->get_global_pos()+area.pos+Vector2(0,area.size.y)); effect_options->popup(); //add effect } else { int index = effect->get_metadata(0); updating_bus=true; UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Select Audio Bus Send"); ur->add_do_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),index,effect->is_checked(0)); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),index,AudioServer::get_singleton()->is_bus_effect_enabled(get_index(),index)); ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->commit_action(); updating_bus=false; } } void EditorAudioBus::_effect_add(int p_which) { if (updating_bus) return; StringName name = effect_options->get_item_metadata(p_which); Object *fx = ClassDB::instance(name); ERR_FAIL_COND(!fx); AudioEffect *afx = fx->cast_to<AudioEffect>(); ERR_FAIL_COND(!afx); Ref<AudioEffect> afxr = Ref<AudioEffect>(afx); afxr->set_name(effect_options->get_item_text(p_which)); UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Add Audio Bus Effect"); ur->add_do_method(AudioServer::get_singleton(),"add_bus_effect",get_index(),afxr,-1); ur->add_undo_method(AudioServer::get_singleton(),"remove_bus_effect",get_index(),AudioServer::get_singleton()->get_bus_effect_count(get_index())); ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->commit_action(); } void EditorAudioBus::_gui_input(const InputEvent& p_event) { if (p_event.type==InputEvent::KEY && p_event.key.pressed && p_event.key.scancode==KEY_DELETE && !p_event.key.echo) { accept_event(); emit_signal("delete_request"); } if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==2 && p_event.mouse_button.pressed) { Vector2 pos = Vector2(p_event.mouse_button.x,p_event.mouse_button.y); delete_popup->set_pos(get_global_pos()+pos); delete_popup->popup(); } } void EditorAudioBus::_delete_pressed(int p_option) { if (p_option==1) { emit_signal("delete_request"); } else if (p_option==0) { //duplicate emit_signal("duplicate_request",get_index()); } } Variant EditorAudioBus::get_drag_data(const Point2& p_point) { if (get_index()==0) { return Variant(); } Control *c = memnew(Control); Panel *p = memnew( Panel ); c->add_child(p); p->add_style_override("panel",get_stylebox("focus","Button")); p->set_size(get_size()); p->set_pos(-p_point); set_drag_preview(c); Dictionary d; d["type"]="move_audio_bus"; d["index"]=get_index(); emit_signal("drop_end_request"); return d; } bool EditorAudioBus::can_drop_data(const Point2& p_point,const Variant& p_data) const { if (get_index()==0) return false; Dictionary d=p_data; if (d.has("type") && String(d["type"])=="move_audio_bus") { return true; } return false; } void EditorAudioBus::drop_data(const Point2& p_point,const Variant& p_data) { Dictionary d=p_data; emit_signal("dropped",d["index"],get_index()); } Variant EditorAudioBus::get_drag_data_fw(const Point2& p_point,Control* p_from) { print_line("drag fw"); TreeItem *item = effects->get_item_at_pos(p_point); if (!item) { print_line("no item"); return Variant(); } Variant md = item->get_metadata(0); if (md.get_type()==Variant::INT) { Dictionary fxd; fxd["type"]="audio_bus_effect"; fxd["bus"]=get_index(); fxd["effect"]=md; Label *l = memnew( Label ); l->set_text(item->get_text(0)); effects->set_drag_preview(l); return fxd; } return Variant(); } bool EditorAudioBus::can_drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from) const{ Dictionary d = p_data; if (!d.has("type") || String(d["type"])!="audio_bus_effect") return false; TreeItem *item = effects->get_item_at_pos(p_point); if (!item) return false; effects->set_drop_mode_flags(Tree::DROP_MODE_INBETWEEN); return true; } void EditorAudioBus::drop_data_fw(const Point2& p_point,const Variant& p_data,Control* p_from){ Dictionary d = p_data; TreeItem *item = effects->get_item_at_pos(p_point); if (!item) return; int pos=effects->get_drop_section_at_pos(p_point); Variant md = item->get_metadata(0); int paste_at; int bus = d["bus"]; int effect = d["effect"]; if (md.get_type()==Variant::INT) { paste_at=md; if (pos>0) paste_at++; if (bus==get_index() && paste_at >effect) { paste_at--; } } else { paste_at=-1; } bool enabled = AudioServer::get_singleton()->is_bus_effect_enabled(bus,effect); UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Move Bus Effect"); ur->add_do_method(AudioServer::get_singleton(),"remove_bus_effect",bus,effect); ur->add_do_method(AudioServer::get_singleton(),"add_bus_effect",get_index(),AudioServer::get_singleton()->get_bus_effect(bus,effect),paste_at); if (paste_at==-1) { paste_at = AudioServer::get_singleton()->get_bus_effect_count(get_index()); if (bus==get_index()) { paste_at--; } } if (!enabled) { ur->add_do_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),paste_at,false); } ur->add_undo_method(AudioServer::get_singleton(),"remove_bus_effect",get_index(),paste_at); ur->add_undo_method(AudioServer::get_singleton(),"add_bus_effect",bus,AudioServer::get_singleton()->get_bus_effect(bus,effect),effect); if (!enabled) { ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",bus,effect,false); } ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); if (get_index()!=bus) { ur->add_do_method(buses,"_update_bus",bus); ur->add_undo_method(buses,"_update_bus",bus); } ur->commit_action(); } void EditorAudioBus::_delete_effect_pressed(int p_option) { TreeItem * item = effects->get_selected(); if (!item) return; if (item->get_metadata(0).get_type()!=Variant::INT) return; int index = item->get_metadata(0); UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Delete Bus Effect"); ur->add_do_method(AudioServer::get_singleton(),"remove_bus_effect",get_index(),index); ur->add_undo_method(AudioServer::get_singleton(),"add_bus_effect",get_index(),AudioServer::get_singleton()->get_bus_effect(get_index(),index),index); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",get_index(),index,AudioServer::get_singleton()->is_bus_effect_enabled(get_index(),index)); ur->add_do_method(buses,"_update_bus",get_index()); ur->add_undo_method(buses,"_update_bus",get_index()); ur->commit_action(); } void EditorAudioBus::_effect_rmb(const Vector2& p_pos) { TreeItem * item = effects->get_selected(); if (!item) return; if (item->get_metadata(0).get_type()!=Variant::INT) return; delete_effect_popup->set_pos(get_global_mouse_pos()); delete_effect_popup->popup(); } void EditorAudioBus::_bind_methods() { ClassDB::bind_method("update_bus",&EditorAudioBus::update_bus); ClassDB::bind_method("update_send",&EditorAudioBus::update_send); ClassDB::bind_method("_name_changed",&EditorAudioBus::_name_changed); ClassDB::bind_method("_volume_db_changed",&EditorAudioBus::_volume_db_changed); ClassDB::bind_method("_solo_toggled",&EditorAudioBus::_solo_toggled); ClassDB::bind_method("_mute_toggled",&EditorAudioBus::_mute_toggled); ClassDB::bind_method("_bypass_toggled",&EditorAudioBus::_bypass_toggled); ClassDB::bind_method("_name_focus_exit",&EditorAudioBus::_name_focus_exit); ClassDB::bind_method("_send_selected",&EditorAudioBus::_send_selected); ClassDB::bind_method("_effect_edited",&EditorAudioBus::_effect_edited); ClassDB::bind_method("_effect_selected",&EditorAudioBus::_effect_selected); ClassDB::bind_method("_effect_add",&EditorAudioBus::_effect_add); ClassDB::bind_method("_gui_input",&EditorAudioBus::_gui_input); ClassDB::bind_method("_delete_pressed",&EditorAudioBus::_delete_pressed); ClassDB::bind_method("get_drag_data_fw",&EditorAudioBus::get_drag_data_fw); ClassDB::bind_method("can_drop_data_fw",&EditorAudioBus::can_drop_data_fw); ClassDB::bind_method("drop_data_fw",&EditorAudioBus::drop_data_fw); ClassDB::bind_method("_delete_effect_pressed",&EditorAudioBus::_delete_effect_pressed); ClassDB::bind_method("_effect_rmb",&EditorAudioBus::_effect_rmb); ADD_SIGNAL(MethodInfo("duplicate_request")); ADD_SIGNAL(MethodInfo("delete_request")); ADD_SIGNAL(MethodInfo("drop_end_request")); ADD_SIGNAL(MethodInfo("dropped")); } EditorAudioBus::EditorAudioBus(EditorAudioBuses *p_buses) { buses=p_buses; updating_bus=false; VBoxContainer *vb = memnew( VBoxContainer ); add_child(vb); set_v_size_flags(SIZE_EXPAND_FILL); track_name = memnew( LineEdit ); vb->add_child(track_name); track_name->connect("text_entered",this,"_name_changed"); track_name->connect("focus_exited",this,"_name_focus_exit"); HBoxContainer *hbc = memnew( HBoxContainer); vb->add_child(hbc); hbc->add_spacer(); solo = memnew( ToolButton ); solo->set_text("S"); solo->set_toggle_mode(true); solo->set_modulate(Color(0.8,1.2,0.8)); solo->set_focus_mode(FOCUS_NONE); solo->connect("pressed",this,"_solo_toggled"); hbc->add_child(solo); mute = memnew( ToolButton ); mute->set_text("M"); mute->set_toggle_mode(true); mute->set_modulate(Color(1.2,0.8,0.8)); mute->set_focus_mode(FOCUS_NONE); mute->connect("pressed",this,"_mute_toggled"); hbc->add_child(mute); bypass = memnew( ToolButton ); bypass->set_text("B"); bypass->set_toggle_mode(true); bypass->set_modulate(Color(1.1,1.1,0.8)); bypass->set_focus_mode(FOCUS_NONE); bypass->connect("pressed",this,"_bypass_toggled"); hbc->add_child(bypass); hbc->add_spacer(); HBoxContainer *hb = memnew( HBoxContainer ); vb->add_child(hb); slider = memnew( VSlider ); slider->set_min(-80); slider->set_max(24); slider->set_step(0.1); slider->connect("value_changed",this,"_volume_db_changed"); hb->add_child(slider); vu_l = memnew( TextureProgress ); vu_l->set_fill_mode(TextureProgress::FILL_BOTTOM_TO_TOP); hb->add_child(vu_l); vu_l->set_min(-80); vu_l->set_max(24); vu_l->set_step(0.1); vu_r = memnew( TextureProgress ); vu_r->set_fill_mode(TextureProgress::FILL_BOTTOM_TO_TOP); hb->add_child(vu_r); vu_r->set_min(-80); vu_r->set_max(24); vu_r->set_step(0.1); scale = memnew( TextureRect ); hb->add_child(scale); //add_child(hb); effects = memnew( Tree ); effects->set_hide_root(true); effects->set_custom_minimum_size(Size2(0,90)*EDSCALE); effects->set_hide_folding(true); vb->add_child(effects); effects->connect("item_edited",this,"_effect_edited"); effects->connect("cell_selected",this,"_effect_selected"); effects->set_edit_checkbox_cell_only_when_checkbox_is_pressed(true); effects->set_drag_forwarding(this); effects->connect("item_rmb_selected",this,"_effect_rmb"); effects->set_allow_rmb_select(true); send = memnew( OptionButton ); send->set_clip_text(true); send->connect("item_selected",this,"_send_selected"); vb->add_child(send); set_focus_mode(FOCUS_CLICK); effect_options = memnew( PopupMenu ); effect_options->connect("index_pressed",this,"_effect_add"); add_child(effect_options); List<StringName> effects; ClassDB::get_inheriters_from_class("AudioEffect",&effects); effects.sort_custom<StringName::AlphCompare>(); for (List<StringName>::Element *E=effects.front();E;E=E->next()) { if (!ClassDB::can_instance(E->get())) continue; Ref<Texture> icon; if (has_icon(E->get(),"EditorIcons")) { icon = get_icon(E->get(),"EditorIcons"); } String name = E->get().operator String().replace("AudioEffect",""); effect_options->add_item(name); effect_options->set_item_metadata(effect_options->get_item_count()-1,E->get()); effect_options->set_item_icon(effect_options->get_item_count()-1,icon); } delete_popup = memnew( PopupMenu ); delete_popup->add_item("Duplicate"); delete_popup->add_item("Delete"); add_child(delete_popup); delete_popup->connect("index_pressed",this,"_delete_pressed"); delete_effect_popup = memnew( PopupMenu ); delete_effect_popup->add_item("Delete Effect"); add_child(delete_effect_popup); delete_effect_popup->connect("index_pressed",this,"_delete_effect_pressed"); } bool EditorAudioBusDrop::can_drop_data(const Point2& p_point,const Variant& p_data) const { Dictionary d=p_data; if (d.has("type") && String(d["type"])=="move_audio_bus") { return true; } return false; } void EditorAudioBusDrop::drop_data(const Point2& p_point,const Variant& p_data){ Dictionary d=p_data; emit_signal("dropped",d["index"],-1); } void EditorAudioBusDrop::_bind_methods() { ADD_SIGNAL(MethodInfo("dropped")); } EditorAudioBusDrop::EditorAudioBusDrop() { } void EditorAudioBuses::_update_buses() { while(bus_hb->get_child_count()>0) { memdelete(bus_hb->get_child(0)); } drop_end=NULL; for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) { EditorAudioBus *audio_bus = memnew( EditorAudioBus(this) ); if (i==0) { audio_bus->set_self_modulate(Color(1,0.9,0.9)); } bus_hb->add_child(audio_bus); audio_bus->connect("delete_request",this,"_delete_bus",varray(audio_bus),CONNECT_DEFERRED); audio_bus->connect("duplicate_request",this,"_duplicate_bus",varray(),CONNECT_DEFERRED); audio_bus->connect("drop_end_request",this,"_request_drop_end"); audio_bus->connect("dropped",this,"_drop_at_index",varray(),CONNECT_DEFERRED); } } EditorAudioBuses *EditorAudioBuses::register_editor() { EditorAudioBuses * audio_buses = memnew( EditorAudioBuses ); EditorNode::get_singleton()->add_bottom_panel_item("Audio",audio_buses); return audio_buses; } void EditorAudioBuses::_notification(int p_what) { if (p_what==NOTIFICATION_READY) { _update_buses(); } if (p_what==NOTIFICATION_DRAG_END) { if (drop_end) { drop_end->queue_delete(); drop_end=NULL; } } if (p_what==NOTIFICATION_PROCESS) { //check if anything was edited bool edited = AudioServer::get_singleton()->is_edited(); for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) { for(int j=0;j<AudioServer::get_singleton()->get_bus_effect_count(i);j++) { Ref<AudioEffect> effect = AudioServer::get_singleton()->get_bus_effect(i,j); if (effect->is_edited()) { edited=true; effect->set_edited(false); } } } AudioServer::get_singleton()->set_edited(false); if (edited) { save_timer->start(); } } } void EditorAudioBuses::_add_bus() { UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); //need to simulate new name, so we can undi :( ur->create_action("Add Audio Bus"); ur->add_do_method(AudioServer::get_singleton(),"set_bus_count",AudioServer::get_singleton()->get_bus_count()+1); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_count",AudioServer::get_singleton()->get_bus_count()); ur->add_do_method(this,"_update_buses"); ur->add_undo_method(this,"_update_buses"); ur->commit_action(); } void EditorAudioBuses::_update_bus(int p_index) { if (p_index>=bus_hb->get_child_count()) return; bus_hb->get_child(p_index)->call("update_bus"); } void EditorAudioBuses::_update_sends() { for(int i=0;i<bus_hb->get_child_count();i++) { bus_hb->get_child(i)->call("update_send"); } } void EditorAudioBuses::_delete_bus(Object* p_which) { EditorAudioBus *bus = p_which->cast_to<EditorAudioBus>(); int index = bus->get_index(); if (index==0) { EditorNode::get_singleton()->show_warning("Master bus can't be deleted!"); return; } UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Delete Audio Bus"); ur->add_do_method(AudioServer::get_singleton(),"remove_bus",index); ur->add_undo_method(AudioServer::get_singleton(),"add_bus",index); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_name",index,AudioServer::get_singleton()->get_bus_name(index)); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_volume_db",index,AudioServer::get_singleton()->get_bus_volume_db(index)); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_send",index,AudioServer::get_singleton()->get_bus_send(index)); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_solo",index,AudioServer::get_singleton()->is_bus_solo(index)); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_mute",index,AudioServer::get_singleton()->is_bus_mute(index)); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_bypass_effects",index,AudioServer::get_singleton()->is_bus_bypassing_effects(index)); for(int i=0;i<AudioServer::get_singleton()->get_bus_effect_count(index);i++) { ur->add_undo_method(AudioServer::get_singleton(),"add_bus_effect",index,AudioServer::get_singleton()->get_bus_effect(index,i)); ur->add_undo_method(AudioServer::get_singleton(),"set_bus_effect_enabled",index,i,AudioServer::get_singleton()->is_bus_effect_enabled(index,i)); } ur->add_do_method(this,"_update_buses"); ur->add_undo_method(this,"_update_buses"); ur->commit_action(); } void EditorAudioBuses::_duplicate_bus(int p_which) { int add_at_pos = p_which+1; UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); ur->create_action("Duplicate Audio Bus"); ur->add_do_method(AudioServer::get_singleton(),"add_bus",add_at_pos); ur->add_do_method(AudioServer::get_singleton(),"set_bus_name",add_at_pos,AudioServer::get_singleton()->get_bus_name(p_which)+" Copy"); ur->add_do_method(AudioServer::get_singleton(),"set_bus_volume_db",add_at_pos,AudioServer::get_singleton()->get_bus_volume_db(p_which)); ur->add_do_method(AudioServer::get_singleton(),"set_bus_send",add_at_pos,AudioServer::get_singleton()->get_bus_send(p_which)); ur->add_do_method(AudioServer::get_singleton(),"set_bus_solo",add_at_pos,AudioServer::get_singleton()->is_bus_solo(p_which)); ur->add_do_method(AudioServer::get_singleton(),"set_bus_mute",add_at_pos,AudioServer::get_singleton()->is_bus_mute(p_which)); ur->add_do_method(AudioServer::get_singleton(),"set_bus_bypass_effects",add_at_pos,AudioServer::get_singleton()->is_bus_bypassing_effects(p_which)); for(int i=0;i<AudioServer::get_singleton()->get_bus_effect_count(p_which);i++) { ur->add_do_method(AudioServer::get_singleton(),"add_bus_effect",add_at_pos,AudioServer::get_singleton()->get_bus_effect(p_which,i)); ur->add_do_method(AudioServer::get_singleton(),"set_bus_effect_enabled",add_at_pos,i,AudioServer::get_singleton()->is_bus_effect_enabled(p_which,i)); } ur->add_undo_method(AudioServer::get_singleton(),"remove_bus",add_at_pos); ur->add_do_method(this,"_update_buses"); ur->add_undo_method(this,"_update_buses"); ur->commit_action(); } void EditorAudioBuses::_request_drop_end() { if (!drop_end && bus_hb->get_child_count()) { drop_end = memnew( EditorAudioBusDrop ); bus_hb->add_child(drop_end); drop_end->set_custom_minimum_size(bus_hb->get_child(0)->cast_to<Control>()->get_size()); drop_end->connect("dropped",this,"_drop_at_index",varray(),CONNECT_DEFERRED); } } void EditorAudioBuses::_drop_at_index(int p_bus,int p_index) { UndoRedo *ur = EditorNode::get_singleton()->get_undo_redo(); //need to simulate new name, so we can undi :( ur->create_action("Move Audio Bus"); ur->add_do_method(AudioServer::get_singleton(),"move_bus",p_bus,p_index); int final_pos; if (p_index==p_bus) { final_pos=p_bus; } else if (p_index==-1) { final_pos = AudioServer::get_singleton()->get_bus_count()-1; } else if (p_index<p_bus) { final_pos = p_index; } else { final_pos = p_index -1; } ur->add_undo_method(AudioServer::get_singleton(),"move_bus",final_pos,p_bus); ur->add_do_method(this,"_update_buses"); ur->add_undo_method(this,"_update_buses"); ur->commit_action(); } void EditorAudioBuses::_server_save() { Ref<AudioBusLayout> state = AudioServer::get_singleton()->generate_bus_layout(); ResourceSaver::save(edited_path,state); } void EditorAudioBuses::_select_layout() { EditorNode::get_singleton()->get_filesystem_dock()->select_file(edited_path); } void EditorAudioBuses::_save_as_layout() { file_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); file_dialog->set_title(TTR("Save Audio Bus Layout As..")); file_dialog->set_current_path(edited_path); file_dialog->popup_centered_ratio(); new_layout=false; } void EditorAudioBuses::_new_layout() { file_dialog->set_mode(EditorFileDialog::MODE_SAVE_FILE); file_dialog->set_title(TTR("Location for New Layout..")); file_dialog->set_current_path(edited_path); file_dialog->popup_centered_ratio(); new_layout=true; } void EditorAudioBuses::_load_layout() { file_dialog->set_mode(EditorFileDialog::MODE_OPEN_FILE); file_dialog->set_title(TTR("Open Audio Bus Layout")); file_dialog->set_current_path(edited_path); file_dialog->popup_centered_ratio(); new_layout=false; } void EditorAudioBuses::_load_default_layout() { Ref<AudioBusLayout> state = ResourceLoader::load("res://default_bus_layout.tres"); if (state.is_null()) { EditorNode::get_singleton()->show_warning("There is no 'res://default_bus_layout.tres' file."); return; } edited_path="res://default_bus_layout.tres"; file->set_text(edited_path.get_file()); AudioServer::get_singleton()->set_bus_layout(state); _update_buses(); EditorNode::get_singleton()->get_undo_redo()->clear_history(); call_deferred("_select_layout"); } void EditorAudioBuses::_file_dialog_callback(const String& p_string) { if (file_dialog->get_mode()==EditorFileDialog::MODE_OPEN_FILE) { Ref<AudioBusLayout> state = ResourceLoader::load(p_string); if (state.is_null()) { EditorNode::get_singleton()->show_warning("Invalid file, not an audio bus layout."); return; } edited_path=p_string; file->set_text(p_string.get_file()); AudioServer::get_singleton()->set_bus_layout(state); _update_buses(); EditorNode::get_singleton()->get_undo_redo()->clear_history(); call_deferred("_select_layout"); } else if (file_dialog->get_mode()==EditorFileDialog::MODE_SAVE_FILE) { if (new_layout) { Ref<AudioBusLayout> empty_state; empty_state.instance(); AudioServer::get_singleton()->set_bus_layout(empty_state); } Error err = ResourceSaver::save(p_string,AudioServer::get_singleton()->generate_bus_layout()); if (err!=OK) { EditorNode::get_singleton()->show_warning("Error saving file: "+p_string); return; } edited_path=p_string; file->set_text(p_string.get_file()); _update_buses(); EditorNode::get_singleton()->get_undo_redo()->clear_history(); call_deferred("_select_layout"); } } void EditorAudioBuses::_bind_methods() { ClassDB::bind_method("_add_bus",&EditorAudioBuses::_add_bus); ClassDB::bind_method("_update_buses",&EditorAudioBuses::_update_buses); ClassDB::bind_method("_update_bus",&EditorAudioBuses::_update_bus); ClassDB::bind_method("_update_sends",&EditorAudioBuses::_update_sends); ClassDB::bind_method("_delete_bus",&EditorAudioBuses::_delete_bus); ClassDB::bind_method("_request_drop_end",&EditorAudioBuses::_request_drop_end); ClassDB::bind_method("_drop_at_index",&EditorAudioBuses::_drop_at_index); ClassDB::bind_method("_server_save",&EditorAudioBuses::_server_save); ClassDB::bind_method("_select_layout",&EditorAudioBuses::_select_layout); ClassDB::bind_method("_save_as_layout",&EditorAudioBuses::_save_as_layout); ClassDB::bind_method("_load_layout",&EditorAudioBuses::_load_layout); ClassDB::bind_method("_load_default_layout",&EditorAudioBuses::_load_default_layout); ClassDB::bind_method("_new_layout",&EditorAudioBuses::_new_layout); ClassDB::bind_method("_duplicate_bus",&EditorAudioBuses::_duplicate_bus); ClassDB::bind_method("_file_dialog_callback",&EditorAudioBuses::_file_dialog_callback); } EditorAudioBuses::EditorAudioBuses() { drop_end = NULL; top_hb = memnew( HBoxContainer ); add_child(top_hb); add = memnew( Button ); top_hb->add_child(add);; add->set_text(TTR("Add Bus")); add->connect("pressed",this,"_add_bus"); top_hb->add_spacer(); file = memnew( ToolButton ); file->set_text("default_bus_layout.tres"); top_hb->add_child(file); file->connect("pressed",this,"_select_layout"); load = memnew( Button ); load->set_text(TTR("Load")); top_hb->add_child(load); load->connect("pressed",this,"_load_layout"); save_as = memnew( Button ); save_as->set_text(TTR("Save As")); top_hb->add_child(save_as); save_as->connect("pressed",this,"_save_as_layout"); _default = memnew( Button ); _default->set_text(TTR("Default")); top_hb->add_child(_default); _default->connect("pressed",this,"_load_default_layout"); _new = memnew( Button ); _new->set_text(TTR("Create")); top_hb->add_child(_new); _new->connect("pressed",this,"_new_layout"); bus_scroll = memnew( ScrollContainer ); bus_scroll->set_v_size_flags(SIZE_EXPAND_FILL); bus_scroll->set_enable_h_scroll(true); bus_scroll->set_enable_v_scroll(false); add_child(bus_scroll); bus_hb = memnew( HBoxContainer ); bus_scroll->add_child(bus_hb); save_timer=memnew(Timer); save_timer->set_wait_time(0.8); save_timer->set_one_shot(true); add_child(save_timer); save_timer->connect("timeout",this,"_server_save"); set_v_size_flags(SIZE_EXPAND_FILL); edited_path = "res://default_bus_layout.tres"; file_dialog = memnew( EditorFileDialog ); List<String> ext; ResourceLoader::get_recognized_extensions_for_type("AudioServerState",&ext); for (List<String>::Element *E=ext.front();E;E=E->next()) { file_dialog->add_filter("*."+E->get()+"; Audio Bus State"); } add_child(file_dialog); file_dialog->connect("file_selected",this,"_file_dialog_callback"); set_process(true); } void EditorAudioBuses::open_layout(const String& p_path) { EditorNode::get_singleton()->make_bottom_panel_item_visible(this); Ref<AudioBusLayout> state = ResourceLoader::load(p_path); if (state.is_null()) { EditorNode::get_singleton()->show_warning("Invalid file, not an audio bus layout."); return; } edited_path=p_path; file->set_text(p_path.get_file()); AudioServer::get_singleton()->set_bus_layout(state); _update_buses(); EditorNode::get_singleton()->get_undo_redo()->clear_history(); call_deferred("_select_layout"); } void AudioBusesEditorPlugin::edit(Object *p_node) { if (p_node->cast_to<AudioBusLayout>()) { String path = p_node->cast_to<AudioBusLayout>()->get_path(); if (path.is_resource_file()) { audio_bus_editor->open_layout(path); } } } bool AudioBusesEditorPlugin::handles(Object *p_node) const { return (p_node->cast_to<AudioBusLayout>()!=NULL); } void AudioBusesEditorPlugin::make_visible(bool p_visible){ } AudioBusesEditorPlugin::AudioBusesEditorPlugin(EditorAudioBuses *p_node) { audio_bus_editor=p_node; } AudioBusesEditorPlugin::~AudioBusesEditorPlugin() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_filter.cpp
151
#include "audio_effect_filter.h" #include "servers/audio_server.h" template<int S> void AudioEffectFilterInstance::_process_filter(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { for(int i=0;i<p_frame_count;i++) { float f = p_src_frames[i].l; filter_process[0][0].process_one(f); if (S>1) filter_process[0][1].process_one(f); if (S>2) filter_process[0][2].process_one(f); if (S>3) filter_process[0][3].process_one(f); p_dst_frames[i].l=f; } for(int i=0;i<p_frame_count;i++) { float f = p_src_frames[i].r; filter_process[1][0].process_one(f); if (S>1) filter_process[1][1].process_one(f); if (S>2) filter_process[1][2].process_one(f); if (S>3) filter_process[1][3].process_one(f); p_dst_frames[i].r=f; } } void AudioEffectFilterInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { filter.set_cutoff(base->cutoff); filter.set_gain(base->gain); filter.set_resonance(base->resonance); filter.set_mode(base->mode); int stages = int(base->db)+1; filter.set_stages(stages); filter.set_sampling_rate(AudioServer::get_singleton()->get_mix_rate()); for(int i=0;i<2;i++) { for(int j=0;j<4;j++) { filter_process[i][j].update_coeffs(); } } if (stages==1) { _process_filter<1>(p_src_frames,p_dst_frames,p_frame_count); } else if (stages==2) { _process_filter<2>(p_src_frames,p_dst_frames,p_frame_count); } else if (stages==3) { _process_filter<3>(p_src_frames,p_dst_frames,p_frame_count); } else if (stages==4) { _process_filter<4>(p_src_frames,p_dst_frames,p_frame_count); } } AudioEffectFilterInstance::AudioEffectFilterInstance() { for(int i=0;i<2;i++) { for(int j=0;j<4;j++) { filter_process[i][j].set_filter(&filter); } } } Ref<AudioEffectInstance> AudioEffectFilter::instance() { Ref<AudioEffectFilterInstance> ins; ins.instance(); ins->base=Ref<AudioEffectFilter>(this); return ins; } void AudioEffectFilter::set_cutoff(float p_freq) { cutoff=p_freq; } float AudioEffectFilter::get_cutoff() const{ return cutoff; } void AudioEffectFilter::set_resonance(float p_amount){ resonance=p_amount; } float AudioEffectFilter::get_resonance() const{ return resonance; } void AudioEffectFilter::set_gain(float p_amount){ gain=p_amount; } float AudioEffectFilter::get_gain() const { return gain; } void AudioEffectFilter::set_db(FilterDB p_db) { db=p_db; } AudioEffectFilter::FilterDB AudioEffectFilter::get_db() const { return db; } void AudioEffectFilter::_bind_methods() { ClassDB::bind_method(_MD("set_cutoff","freq"),&AudioEffectFilter::set_cutoff); ClassDB::bind_method(_MD("get_cutoff"),&AudioEffectFilter::get_cutoff); ClassDB::bind_method(_MD("set_resonance","amount"),&AudioEffectFilter::set_resonance); ClassDB::bind_method(_MD("get_resonance"),&AudioEffectFilter::get_resonance); ClassDB::bind_method(_MD("set_gain","amount"),&AudioEffectFilter::set_gain); ClassDB::bind_method(_MD("get_gain"),&AudioEffectFilter::get_gain); ClassDB::bind_method(_MD("set_db","amount"),&AudioEffectFilter::set_db); ClassDB::bind_method(_MD("get_db"),&AudioEffectFilter::get_db); ADD_PROPERTY(PropertyInfo(Variant::REAL,"cutoff_hz",PROPERTY_HINT_RANGE,"1,40000,0.1"),_SCS("set_cutoff"),_SCS("get_cutoff")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"resonance",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_resonance"),_SCS("get_resonance")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"gain",PROPERTY_HINT_RANGE,"0,4,0.01"),_SCS("set_gain"),_SCS("get_gain")); ADD_PROPERTY(PropertyInfo(Variant::INT,"dB",PROPERTY_HINT_ENUM,"6db,12db,18db,24db"),_SCS("set_db"),_SCS("get_db")); } AudioEffectFilter::AudioEffectFilter(AudioFilterSW::Mode p_mode) { mode=p_mode; cutoff=2000; resonance=0.5; gain=1.0; db=FILTER_6DB; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
scene/gui/viewport_container.cpp
103
#include "viewport_container.h" #include "scene/main/viewport.h" Size2 ViewportContainer::get_minimum_size() const { if (stretch) return Size2(); Size2 ms; for(int i=0;i<get_child_count();i++) { Viewport *c = get_child(i)->cast_to<Viewport>(); if (!c) continue; Size2 minsize = c->get_size(); ms.width = MAX(ms.width , minsize.width); ms.height = MAX(ms.height , minsize.height); } return ms; } void ViewportContainer::set_stretch(bool p_enable) { stretch=p_enable; queue_sort(); update(); } bool ViewportContainer::is_stretch_enabled() const { return stretch; } void ViewportContainer::_notification(int p_what) { if (p_what==NOTIFICATION_RESIZED) { if (!stretch) return; for(int i=0;i<get_child_count();i++) { Viewport *c = get_child(i)->cast_to<Viewport>(); if (!c) continue; c->set_size(get_size()); } } if (p_what==NOTIFICATION_ENTER_TREE || p_what==NOTIFICATION_VISIBILITY_CHANGED) { for(int i=0;i<get_child_count();i++) { Viewport *c = get_child(i)->cast_to<Viewport>(); if (!c) continue; if (is_visible_in_tree()) c->set_update_mode(Viewport::UPDATE_ALWAYS); else c->set_update_mode(Viewport::UPDATE_DISABLED); } } if (p_what==NOTIFICATION_DRAW) { for(int i=0;i<get_child_count();i++) { Viewport *c = get_child(i)->cast_to<Viewport>(); if (!c) continue; if (stretch) draw_texture_rect(c->get_texture(),Rect2(Vector2(),get_size()*Size2(1,-1))); else draw_texture_rect(c->get_texture(),Rect2(Vector2(),c->get_size()*Size2(1,-1))); } } } void ViewportContainer::_bind_methods() { ClassDB::bind_method(_MD("set_stretch","enable"),&ViewportContainer::set_stretch); ClassDB::bind_method(_MD("is_stretch_enabled"),&ViewportContainer::is_stretch_enabled); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"stretch"),_SCS("set_stretch"),_SCS("is_stretch_enabled")); } ViewportContainer::ViewportContainer() { stretch=false; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/register_server_types.cpp
73
/*************************************************************************/ /* register_server_types.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "register_server_types.h" #include "globals.h" #include "visual_server.h" #include "audio_server.h" #include "physics_server.h" #include "physics_2d_server.h" #include "script_debugger_remote.h" #include "visual/shader_types.h" #include "audio/audio_stream.h" #include "audio/audio_effect.h" #include "audio/effects/audio_effect_amplify.h" #include "audio/effects/audio_effect_reverb.h" #include "audio/effects/audio_effect_filter.h" #include "audio/effects/audio_effect_eq.h" #include "audio/effects/audio_effect_distortion.h" #include "audio/effects/audio_effect_stereo_enhance.h" #include "audio/effects/audio_effect_panner.h" #include "audio/effects/audio_effect_chorus.h" #include "audio/effects/audio_effect_delay.h" #include "audio/effects/audio_effect_compressor.h" #include "audio/effects/audio_effect_limiter.h" #include "audio/effects/audio_effect_pitch_shift.h" #include "audio/effects/audio_effect_phaser.h" static void _debugger_get_resource_usage(List<ScriptDebuggerRemote::ResourceUsage>* r_usage) { List<VS::TextureInfo> tinfo; VS::get_singleton()->texture_debug_usage(&tinfo); for (List<VS::TextureInfo>::Element *E=tinfo.front();E;E=E->next()) { ScriptDebuggerRemote::ResourceUsage usage; usage.path=E->get().path; usage.vram=E->get().bytes; usage.id=E->get().texture; usage.type="Texture"; usage.format=itos(E->get().size.width)+"x"+itos(E->get().size.height)+" "+Image::get_format_name(E->get().format); r_usage->push_back(usage); } } ShaderTypes *shader_types=NULL; void register_server_types() { GLOBAL_DEF("memory/multithread/thread_rid_pool_prealloc",20); GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("VisualServer",VisualServer::get_singleton()) ); GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("AudioServer",AudioServer::get_singleton()) ); GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("PhysicsServer",PhysicsServer::get_singleton()) ); GlobalConfig::get_singleton()->add_singleton( GlobalConfig::Singleton("Physics2DServer",Physics2DServer::get_singleton()) ); shader_types = memnew( ShaderTypes ); ClassDB::register_virtual_class<AudioStream>(); ClassDB::register_virtual_class<AudioStreamPlayback>(); ClassDB::register_virtual_class<AudioEffect>(); ClassDB::register_class<AudioBusLayout>(); { //audio effects ClassDB::register_class<AudioEffectAmplify>(); ClassDB::register_class<AudioEffectReverb>(); ClassDB::register_class<AudioEffectLowPassFilter>(); ClassDB::register_class<AudioEffectHighPassFilter>(); ClassDB::register_class<AudioEffectBandPassFilter>(); ClassDB::register_class<AudioEffectNotchFilter>(); ClassDB::register_class<AudioEffectBandLimitFilter>(); ClassDB::register_class<AudioEffectLowShelfFilter>(); ClassDB::register_class<AudioEffectHighShelfFilter>(); ClassDB::register_class<AudioEffectEQ6>(); ClassDB::register_class<AudioEffectEQ10>(); ClassDB::register_class<AudioEffectEQ21>(); ClassDB::register_class<AudioEffectDistortion>(); ClassDB::register_class<AudioEffectStereoEnhance>(); ClassDB::register_class<AudioEffectPanner>(); ClassDB::register_class<AudioEffectChorus>(); ClassDB::register_class<AudioEffectDelay>(); ClassDB::register_class<AudioEffectCompressor>(); ClassDB::register_class<AudioEffectLimiter>(); ClassDB::register_class<AudioEffectPitchShift>(); ClassDB::register_class<AudioEffectPhaser>(); } ClassDB::register_virtual_class<Physics2DDirectBodyState>(); ClassDB::register_virtual_class<Physics2DDirectSpaceState>(); ClassDB::register_virtual_class<Physics2DShapeQueryResult>(); ClassDB::register_class<Physics2DTestMotionResult>(); ClassDB::register_class<Physics2DShapeQueryParameters>(); ClassDB::register_class<PhysicsShapeQueryParameters>(); ClassDB::register_virtual_class<PhysicsDirectBodyState>(); ClassDB::register_virtual_class<PhysicsDirectSpaceState>(); ClassDB::register_virtual_class<PhysicsShapeQueryResult>(); ScriptDebuggerRemote::resource_usage_func=_debugger_get_resource_usage; } void unregister_server_types(){ memdelete( shader_types ); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
scene/3d/gi_probe.cpp
1,406
#include "gi_probe.h" #include "mesh_instance.h" void GIProbeData::set_bounds(const Rect3& p_bounds) { VS::get_singleton()->gi_probe_set_bounds(probe,p_bounds); } Rect3 GIProbeData::get_bounds() const{ return VS::get_singleton()->gi_probe_get_bounds(probe); } void GIProbeData::set_cell_size(float p_size) { VS::get_singleton()->gi_probe_set_cell_size(probe,p_size); } float GIProbeData::get_cell_size() const { return VS::get_singleton()->gi_probe_get_cell_size(probe); } void GIProbeData::set_to_cell_xform(const Transform& p_xform) { VS::get_singleton()->gi_probe_set_to_cell_xform(probe,p_xform); } Transform GIProbeData::get_to_cell_xform() const { return VS::get_singleton()->gi_probe_get_to_cell_xform(probe); } void GIProbeData::set_dynamic_data(const PoolVector<int>& p_data){ VS::get_singleton()->gi_probe_set_dynamic_data(probe,p_data); } PoolVector<int> GIProbeData::get_dynamic_data() const{ return VS::get_singleton()->gi_probe_get_dynamic_data(probe); } void GIProbeData::set_dynamic_range(int p_range){ VS::get_singleton()->gi_probe_set_dynamic_range(probe,p_range); } void GIProbeData::set_energy(float p_range) { VS::get_singleton()->gi_probe_set_energy(probe,p_range); } float GIProbeData::get_energy() const{ return VS::get_singleton()->gi_probe_get_energy(probe); } void GIProbeData::set_interior(bool p_enable) { VS::get_singleton()->gi_probe_set_interior(probe,p_enable); } bool GIProbeData::is_interior() const{ return VS::get_singleton()->gi_probe_is_interior(probe); } bool GIProbeData::is_compressed() const{ return VS::get_singleton()->gi_probe_is_compressed(probe); } void GIProbeData::set_compress(bool p_enable) { VS::get_singleton()->gi_probe_set_compress(probe,p_enable); } int GIProbeData::get_dynamic_range() const{ return VS::get_singleton()->gi_probe_get_dynamic_range(probe); } RID GIProbeData::get_rid() const { return probe; } void GIProbeData::_bind_methods() { ClassDB::bind_method(_MD("set_bounds","bounds"),&GIProbeData::set_bounds); ClassDB::bind_method(_MD("get_bounds"),&GIProbeData::get_bounds); ClassDB::bind_method(_MD("set_cell_size","cell_size"),&GIProbeData::set_cell_size); ClassDB::bind_method(_MD("get_cell_size"),&GIProbeData::get_cell_size); ClassDB::bind_method(_MD("set_to_cell_xform","to_cell_xform"),&GIProbeData::set_to_cell_xform); ClassDB::bind_method(_MD("get_to_cell_xform"),&GIProbeData::get_to_cell_xform); ClassDB::bind_method(_MD("set_dynamic_data","dynamic_data"),&GIProbeData::set_dynamic_data); ClassDB::bind_method(_MD("get_dynamic_data"),&GIProbeData::get_dynamic_data); ClassDB::bind_method(_MD("set_dynamic_range","dynamic_range"),&GIProbeData::set_dynamic_range); ClassDB::bind_method(_MD("get_dynamic_range"),&GIProbeData::get_dynamic_range); ClassDB::bind_method(_MD("set_energy","energy"),&GIProbeData::set_energy); ClassDB::bind_method(_MD("get_energy"),&GIProbeData::get_energy); ClassDB::bind_method(_MD("set_interior","interior"),&GIProbeData::set_interior); ClassDB::bind_method(_MD("is_interior"),&GIProbeData::is_interior); ClassDB::bind_method(_MD("set_compress","compress"),&GIProbeData::set_compress); ClassDB::bind_method(_MD("is_compressed"),&GIProbeData::is_compressed); ADD_PROPERTY(PropertyInfo(Variant::RECT3,"bounds",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),_SCS("set_bounds"),_SCS("get_bounds")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"cell_size",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),_SCS("set_cell_size"),_SCS("get_cell_size")); ADD_PROPERTY(PropertyInfo(Variant::TRANSFORM,"to_cell_xform",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),_SCS("set_to_cell_xform"),_SCS("get_to_cell_xform")); ADD_PROPERTY(PropertyInfo(Variant::POOL_INT_ARRAY,"dynamic_data",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),_SCS("set_dynamic_data"),_SCS("get_dynamic_data")); ADD_PROPERTY(PropertyInfo(Variant::INT,"dynamic_range",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),_SCS("set_dynamic_range"),_SCS("get_dynamic_range")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"energy",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),_SCS("set_energy"),_SCS("get_energy")); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"interior",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),_SCS("set_interior"),_SCS("is_interior")); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"compress",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR),_SCS("set_compress"),_SCS("is_compressed")); } GIProbeData::GIProbeData() { probe=VS::get_singleton()->gi_probe_create(); } GIProbeData::~GIProbeData() { VS::get_singleton()->free(probe); } ////////////////////// ////////////////////// void GIProbe::set_probe_data(const Ref<GIProbeData>& p_data) { if (p_data.is_valid()) { VS::get_singleton()->instance_set_base(get_instance(),p_data->get_rid()); } else { VS::get_singleton()->instance_set_base(get_instance(),RID()); } probe_data=p_data; } Ref<GIProbeData> GIProbe::get_probe_data() const { return probe_data; } void GIProbe::set_subdiv(Subdiv p_subdiv) { ERR_FAIL_INDEX(p_subdiv,SUBDIV_MAX); subdiv=p_subdiv; update_gizmo(); } GIProbe::Subdiv GIProbe::get_subdiv() const { return subdiv; } void GIProbe::set_extents(const Vector3& p_extents) { extents=p_extents; update_gizmo(); } Vector3 GIProbe::get_extents() const { return extents; } void GIProbe::set_dynamic_range(int p_dynamic_range) { dynamic_range=p_dynamic_range; } int GIProbe::get_dynamic_range() const { return dynamic_range; } void GIProbe::set_energy(float p_energy) { energy=p_energy; if (probe_data.is_valid()) { probe_data->set_energy(energy); } } float GIProbe::get_energy() const { return energy; } void GIProbe::set_interior(bool p_enable) { interior=p_enable; if (probe_data.is_valid()) { probe_data->set_interior(p_enable); } } bool GIProbe::is_interior() const { return interior; } void GIProbe::set_compress(bool p_enable) { compress=p_enable; if (probe_data.is_valid()) { probe_data->set_compress(p_enable); } } bool GIProbe::is_compressed() const { return compress; } #include "math.h" #define FINDMINMAX(x0,x1,x2,min,max) \ min = max = x0; \ if(x1<min) min=x1;\ if(x1>max) max=x1;\ if(x2<min) min=x2;\ if(x2>max) max=x2; static bool planeBoxOverlap(Vector3 normal,float d, Vector3 maxbox) { int q; Vector3 vmin,vmax; for(q=0;q<=2;q++) { if(normal[q]>0.0f) { vmin[q]=-maxbox[q]; vmax[q]=maxbox[q]; } else { vmin[q]=maxbox[q]; vmax[q]=-maxbox[q]; } } if(normal.dot(vmin)+d>0.0f) return false; if(normal.dot(vmax)+d>=0.0f) return true; return false; } /*======================== X-tests ========================*/ #define AXISTEST_X01(a, b, fa, fb) \ p0 = a*v0.y - b*v0.z; \ p2 = a*v2.y - b*v2.z; \ if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \ rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \ if(min>rad || max<-rad) return false; #define AXISTEST_X2(a, b, fa, fb) \ p0 = a*v0.y - b*v0.z; \ p1 = a*v1.y - b*v1.z; \ if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \ rad = fa * boxhalfsize.y + fb * boxhalfsize.z; \ if(min>rad || max<-rad) return false; /*======================== Y-tests ========================*/ #define AXISTEST_Y02(a, b, fa, fb) \ p0 = -a*v0.x + b*v0.z; \ p2 = -a*v2.x + b*v2.z; \ if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;} \ rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \ if(min>rad || max<-rad) return false; #define AXISTEST_Y1(a, b, fa, fb) \ p0 = -a*v0.x + b*v0.z; \ p1 = -a*v1.x + b*v1.z; \ if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \ rad = fa * boxhalfsize.x + fb * boxhalfsize.z; \ if(min>rad || max<-rad) return false; /*======================== Z-tests ========================*/ #define AXISTEST_Z12(a, b, fa, fb) \ p1 = a*v1.x - b*v1.y; \ p2 = a*v2.x - b*v2.y; \ if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;} \ rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \ if(min>rad || max<-rad) return false; #define AXISTEST_Z0(a, b, fa, fb) \ p0 = a*v0.x - b*v0.y; \ p1 = a*v1.x - b*v1.y; \ if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;} \ rad = fa * boxhalfsize.x + fb * boxhalfsize.y; \ if(min>rad || max<-rad) return false; static bool fast_tri_box_overlap(const Vector3& boxcenter,const Vector3 boxhalfsize,const Vector3 *triverts) { /* use separating axis theorem to test overlap between triangle and box */ /* need to test for overlap in these directions: */ /* 1) the {x,y,z}-directions (actually, since we use the AABB of the triangle */ /* we do not even need to test these) */ /* 2) normal of the triangle */ /* 3) crossproduct(edge from tri, {x,y,z}-directin) */ /* this gives 3x3=9 more tests */ Vector3 v0,v1,v2; float min,max,d,p0,p1,p2,rad,fex,fey,fez; Vector3 normal,e0,e1,e2; /* This is the fastest branch on Sun */ /* move everything so that the boxcenter is in (0,0,0) */ v0=triverts[0]-boxcenter; v1=triverts[1]-boxcenter; v2=triverts[2]-boxcenter; /* compute triangle edges */ e0=v1-v0; /* tri edge 0 */ e1=v2-v1; /* tri edge 1 */ e2=v0-v2; /* tri edge 2 */ /* Bullet 3: */ /* test the 9 tests first (this was faster) */ fex = Math::abs(e0.x); fey = Math::abs(e0.y); fez = Math::abs(e0.z); AXISTEST_X01(e0.z, e0.y, fez, fey); AXISTEST_Y02(e0.z, e0.x, fez, fex); AXISTEST_Z12(e0.y, e0.x, fey, fex); fex = Math::abs(e1.x); fey = Math::abs(e1.y); fez = Math::abs(e1.z); AXISTEST_X01(e1.z, e1.y, fez, fey); AXISTEST_Y02(e1.z, e1.x, fez, fex); AXISTEST_Z0(e1.y, e1.x, fey, fex); fex = Math::abs(e2.x); fey = Math::abs(e2.y); fez = Math::abs(e2.z); AXISTEST_X2(e2.z, e2.y, fez, fey); AXISTEST_Y1(e2.z, e2.x, fez, fex); AXISTEST_Z12(e2.y, e2.x, fey, fex); /* Bullet 1: */ /* first test overlap in the {x,y,z}-directions */ /* find min, max of the triangle each direction, and test for overlap in */ /* that direction -- this is equivalent to testing a minimal AABB around */ /* the triangle against the AABB */ /* test in X-direction */ FINDMINMAX(v0.x,v1.x,v2.x,min,max); if(min>boxhalfsize.x || max<-boxhalfsize.x) return false; /* test in Y-direction */ FINDMINMAX(v0.y,v1.y,v2.y,min,max); if(min>boxhalfsize.y || max<-boxhalfsize.y) return false; /* test in Z-direction */ FINDMINMAX(v0.z,v1.z,v2.z,min,max); if(min>boxhalfsize.z || max<-boxhalfsize.z) return false; /* Bullet 2: */ /* test if the box intersects the plane of the triangle */ /* compute plane equation of triangle: normal*x+d=0 */ normal=e0.cross(e1); d=-normal.dot(v0); /* plane eq: normal.x+d=0 */ if(!planeBoxOverlap(normal,d,boxhalfsize)) return false; return true; /* box and triangle overlaps */ } static _FORCE_INLINE_ Vector2 get_uv(const Vector3& p_pos, const Vector3 *p_vtx, const Vector2* p_uv) { if (p_pos.distance_squared_to(p_vtx[0])<CMP_EPSILON2) return p_uv[0]; if (p_pos.distance_squared_to(p_vtx[1])<CMP_EPSILON2) return p_uv[1]; if (p_pos.distance_squared_to(p_vtx[2])<CMP_EPSILON2) return p_uv[2]; Vector3 v0 = p_vtx[1] - p_vtx[0]; Vector3 v1 = p_vtx[2] - p_vtx[0]; Vector3 v2 = p_pos - p_vtx[0]; float d00 = v0.dot( v0); float d01 = v0.dot( v1); float d11 = v1.dot( v1); float d20 = v2.dot( v0); float d21 = v2.dot( v1); float denom = (d00 * d11 - d01 * d01); if (denom==0) return p_uv[0]; float v = (d11 * d20 - d01 * d21) / denom; float w = (d00 * d21 - d01 * d20) / denom; float u = 1.0f - v - w; return p_uv[0]*u + p_uv[1]*v + p_uv[2]*w; } void GIProbe::_plot_face(int p_idx, int p_level,int p_x,int p_y,int p_z, const Vector3 *p_vtx, const Vector2* p_uv, const Baker::MaterialCache& p_material, const Rect3 &p_aabb,Baker *p_baker) { if (p_level==p_baker->cell_subdiv-1) { //plot the face by guessing it's albedo and emission value //find best axis to map to, for scanning values int closest_axis; float closest_dot; Vector3 normal = Plane(p_vtx[0],p_vtx[1],p_vtx[2]).normal; for(int i=0;i<3;i++) { Vector3 axis; axis[i]=1.0; float dot=ABS(normal.dot(axis)); if (i==0 || dot>closest_dot) { closest_axis=i; closest_dot=dot; } } Vector3 axis; axis[closest_axis]=1.0; Vector3 t1; t1[(closest_axis+1)%3]=1.0; Vector3 t2; t2[(closest_axis+2)%3]=1.0; t1*=p_aabb.size[(closest_axis+1)%3]/float(color_scan_cell_width); t2*=p_aabb.size[(closest_axis+2)%3]/float(color_scan_cell_width); Color albedo_accum; Color emission_accum; Vector3 normal_accum; float alpha=0.0; //map to a grid average in the best axis for this face for(int i=0;i<color_scan_cell_width;i++) { Vector3 ofs_i=float(i)*t1; for(int j=0;j<color_scan_cell_width;j++) { Vector3 ofs_j=float(j)*t2; Vector3 from = p_aabb.pos+ofs_i+ofs_j; Vector3 to = from + t1 + t2 + axis * p_aabb.size[closest_axis]; Vector3 half = (to-from)*0.5; //is in this cell? if (!fast_tri_box_overlap(from+half,half,p_vtx)) { continue; //face does not span this cell } //go from -size to +size*2 to avoid skipping collisions Vector3 ray_from = from + (t1+t2)*0.5 - axis * p_aabb.size[closest_axis]; Vector3 ray_to = ray_from + axis * p_aabb.size[closest_axis]*2; Vector3 intersection; if (!Geometry::ray_intersects_triangle(ray_from,ray_to,p_vtx[0],p_vtx[1],p_vtx[2],&intersection)) { //no intersect? look in edges float closest_dist=1e20; for(int j=0;j<3;j++) { Vector3 c; Vector3 inters; Geometry::get_closest_points_between_segments(p_vtx[j],p_vtx[(j+1)%3],ray_from,ray_to,inters,c); float d=c.distance_to(intersection); if (j==0 || d<closest_dist) { closest_dist=d; intersection=inters; } } } Vector2 uv = get_uv(intersection,p_vtx,p_uv); int uv_x = CLAMP(Math::fposmod(uv.x,1.0f)*bake_texture_size,0,bake_texture_size-1); int uv_y = CLAMP(Math::fposmod(uv.y,1.0f)*bake_texture_size,0,bake_texture_size-1); int ofs = uv_y*bake_texture_size+uv_x; albedo_accum.r+=p_material.albedo[ofs].r; albedo_accum.g+=p_material.albedo[ofs].g; albedo_accum.b+=p_material.albedo[ofs].b; albedo_accum.a+=p_material.albedo[ofs].a; emission_accum.r+=p_material.emission[ofs].r; emission_accum.g+=p_material.emission[ofs].g; emission_accum.b+=p_material.emission[ofs].b; normal_accum+=normal; alpha+=1.0; } } if (alpha==0) { //could not in any way get texture information.. so use closest point to center Face3 f( p_vtx[0],p_vtx[1],p_vtx[2]); Vector3 inters = f.get_closest_point_to(p_aabb.pos+p_aabb.size*0.5); Vector2 uv = get_uv(inters,p_vtx,p_uv); int uv_x = CLAMP(Math::fposmod(uv.x,1.0f)*bake_texture_size,0,bake_texture_size-1); int uv_y = CLAMP(Math::fposmod(uv.y,1.0f)*bake_texture_size,0,bake_texture_size-1); int ofs = uv_y*bake_texture_size+uv_x; alpha = 1.0/(color_scan_cell_width*color_scan_cell_width); albedo_accum.r=p_material.albedo[ofs].r*alpha; albedo_accum.g=p_material.albedo[ofs].g*alpha; albedo_accum.b=p_material.albedo[ofs].b*alpha; albedo_accum.a=p_material.albedo[ofs].a*alpha; emission_accum.r=p_material.emission[ofs].r*alpha; emission_accum.g=p_material.emission[ofs].g*alpha; emission_accum.b=p_material.emission[ofs].b*alpha; normal_accum*=alpha; } else { float accdiv = 1.0/(color_scan_cell_width*color_scan_cell_width); alpha*=accdiv; albedo_accum.r*=accdiv; albedo_accum.g*=accdiv; albedo_accum.b*=accdiv; albedo_accum.a*=accdiv; emission_accum.r*=accdiv; emission_accum.g*=accdiv; emission_accum.b*=accdiv; normal_accum*=accdiv; } //put this temporarily here, corrected in a later step p_baker->bake_cells[p_idx].albedo[0]+=albedo_accum.r; p_baker->bake_cells[p_idx].albedo[1]+=albedo_accum.g; p_baker->bake_cells[p_idx].albedo[2]+=albedo_accum.b; p_baker->bake_cells[p_idx].emission[0]+=emission_accum.r; p_baker->bake_cells[p_idx].emission[1]+=emission_accum.g; p_baker->bake_cells[p_idx].emission[2]+=emission_accum.b; p_baker->bake_cells[p_idx].normal[0]+=normal_accum.x; p_baker->bake_cells[p_idx].normal[1]+=normal_accum.y; p_baker->bake_cells[p_idx].normal[2]+=normal_accum.z; p_baker->bake_cells[p_idx].alpha+=alpha; static const Vector3 side_normals[6]={ Vector3(-1, 0, 0), Vector3( 1, 0, 0), Vector3( 0,-1, 0), Vector3( 0, 1, 0), Vector3( 0, 0,-1), Vector3( 0, 0, 1), }; /* for(int i=0;i<6;i++) { if (normal.dot(side_normals[i])>CMP_EPSILON) { p_baker->bake_cells[p_idx].used_sides|=(1<<i); } }*/ } else { //go down int half = (1<<(p_baker->cell_subdiv-1)) >> (p_level+1); for(int i=0;i<8;i++) { Rect3 aabb=p_aabb; aabb.size*=0.5; int nx=p_x; int ny=p_y; int nz=p_z; if (i&1) { aabb.pos.x+=aabb.size.x; nx+=half; } if (i&2) { aabb.pos.y+=aabb.size.y; ny+=half; } if (i&4) { aabb.pos.z+=aabb.size.z; nz+=half; } //make sure to not plot beyond limits if (nx<0 || nx>=p_baker->axis_cell_size[0] || ny<0 || ny>=p_baker->axis_cell_size[1] || nz<0 || nz>=p_baker->axis_cell_size[2]) continue; { Rect3 test_aabb=aabb; //test_aabb.grow_by(test_aabb.get_longest_axis_size()*0.05); //grow a bit to avoid numerical error in real-time Vector3 qsize = test_aabb.size*0.5; //quarter size, for fast aabb test if (!fast_tri_box_overlap(test_aabb.pos+qsize,qsize,p_vtx)) { //if (!Face3(p_vtx[0],p_vtx[1],p_vtx[2]).intersects_aabb2(aabb)) { //does not fit in child, go on continue; } } if (p_baker->bake_cells[p_idx].childs[i]==Baker::CHILD_EMPTY) { //sub cell must be created uint32_t child_idx = p_baker->bake_cells.size(); p_baker->bake_cells[p_idx].childs[i]=child_idx; p_baker->bake_cells.resize( p_baker->bake_cells.size() + 1); p_baker->bake_cells[child_idx].level=p_level+1; } _plot_face(p_baker->bake_cells[p_idx].childs[i],p_level+1,nx,ny,nz,p_vtx,p_uv,p_material,aabb,p_baker); } } } void GIProbe::_fixup_plot(int p_idx, int p_level,int p_x,int p_y, int p_z,Baker *p_baker) { if (p_level==p_baker->cell_subdiv-1) { p_baker->leaf_voxel_count++; float alpha = p_baker->bake_cells[p_idx].alpha; p_baker->bake_cells[p_idx].albedo[0]/=alpha; p_baker->bake_cells[p_idx].albedo[1]/=alpha; p_baker->bake_cells[p_idx].albedo[2]/=alpha; //transfer emission to light p_baker->bake_cells[p_idx].emission[0]/=alpha; p_baker->bake_cells[p_idx].emission[1]/=alpha; p_baker->bake_cells[p_idx].emission[2]/=alpha; p_baker->bake_cells[p_idx].normal[0]/=alpha; p_baker->bake_cells[p_idx].normal[1]/=alpha; p_baker->bake_cells[p_idx].normal[2]/=alpha; Vector3 n(p_baker->bake_cells[p_idx].normal[0],p_baker->bake_cells[p_idx].normal[1],p_baker->bake_cells[p_idx].normal[2]); if (n.length()<0.01) { //too much fight over normal, zero it p_baker->bake_cells[p_idx].normal[0]=0; p_baker->bake_cells[p_idx].normal[1]=0; p_baker->bake_cells[p_idx].normal[2]=0; } else { n.normalize(); p_baker->bake_cells[p_idx].normal[0]=n.x; p_baker->bake_cells[p_idx].normal[1]=n.y; p_baker->bake_cells[p_idx].normal[2]=n.z; } p_baker->bake_cells[p_idx].alpha=1.0; /* //remove neighbours from used sides for(int n=0;n<6;n++) { int ofs[3]={0,0,0}; ofs[n/2]=(n&1)?1:-1; //convert to x,y,z on this level int x=p_x; int y=p_y; int z=p_z; x+=ofs[0]; y+=ofs[1]; z+=ofs[2]; int ofs_x=0; int ofs_y=0; int ofs_z=0; int size = 1<<p_level; int half=size/2; if (x<0 || x>=size || y<0 || y>=size || z<0 || z>=size) { //neighbour is out, can't use it p_baker->bake_cells[p_idx].used_sides&=~(1<<uint32_t(n)); continue; } uint32_t neighbour=0; for(int i=0;i<p_baker->cell_subdiv-1;i++) { Baker::Cell *bc = &p_baker->bake_cells[neighbour]; int child = 0; if (x >= ofs_x + half) { child|=1; ofs_x+=half; } if (y >= ofs_y + half) { child|=2; ofs_y+=half; } if (z >= ofs_z + half) { child|=4; ofs_z+=half; } neighbour = bc->childs[child]; if (neighbour==Baker::CHILD_EMPTY) { break; } half>>=1; } if (neighbour!=Baker::CHILD_EMPTY) { p_baker->bake_cells[p_idx].used_sides&=~(1<<uint32_t(n)); } } */ } else { //go down float alpha_average=0; int half = (1<<(p_baker->cell_subdiv-1)) >> (p_level+1); for(int i=0;i<8;i++) { uint32_t child = p_baker->bake_cells[p_idx].childs[i]; if (child==Baker::CHILD_EMPTY) continue; int nx=p_x; int ny=p_y; int nz=p_z; if (i&1) nx+=half; if (i&2) ny+=half; if (i&4) nz+=half; _fixup_plot(child,p_level+1,nx,ny,nz,p_baker); alpha_average+=p_baker->bake_cells[child].alpha; } p_baker->bake_cells[p_idx].alpha=alpha_average/8.0; p_baker->bake_cells[p_idx].emission[0]=0; p_baker->bake_cells[p_idx].emission[1]=0; p_baker->bake_cells[p_idx].emission[2]=0; p_baker->bake_cells[p_idx].normal[0]=0; p_baker->bake_cells[p_idx].normal[1]=0; p_baker->bake_cells[p_idx].normal[2]=0; p_baker->bake_cells[p_idx].albedo[0]=0; p_baker->bake_cells[p_idx].albedo[1]=0; p_baker->bake_cells[p_idx].albedo[2]=0; } } Vector<Color> GIProbe::_get_bake_texture(Image &p_image,const Color& p_color) { Vector<Color> ret; if (p_image.empty()) { ret.resize(bake_texture_size*bake_texture_size); for(int i=0;i<bake_texture_size*bake_texture_size;i++) { ret[i]=p_color; } return ret; } p_image.convert(Image::FORMAT_RGBA8); p_image.resize(bake_texture_size,bake_texture_size,Image::INTERPOLATE_CUBIC); PoolVector<uint8_t>::Read r = p_image.get_data().read(); ret.resize(bake_texture_size*bake_texture_size); for(int i=0;i<bake_texture_size*bake_texture_size;i++) { Color c; c.r = r[i*4+0]/255.0; c.g = r[i*4+1]/255.0; c.b = r[i*4+2]/255.0; c.a = r[i*4+3]/255.0; ret[i]=c; } return ret; } GIProbe::Baker::MaterialCache GIProbe::_get_material_cache(Ref<Material> p_material,Baker *p_baker) { //this way of obtaining materials is inaccurate and also does not support some compressed formats very well Ref<FixedSpatialMaterial> mat = p_material; Ref<Material> material = mat; //hack for now if (p_baker->material_cache.has(material)) { return p_baker->material_cache[material]; } Baker::MaterialCache mc; if (mat.is_valid()) { Ref<ImageTexture> albedo_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_ALBEDO); Image img_albedo; if (albedo_tex.is_valid()) { img_albedo = albedo_tex->get_data(); } mc.albedo=_get_bake_texture(img_albedo,mat->get_albedo()); Ref<ImageTexture> emission_tex = mat->get_texture(FixedSpatialMaterial::TEXTURE_EMISSION); Color emission_col = mat->get_emission(); emission_col.r*=mat->get_emission_energy(); emission_col.g*=mat->get_emission_energy(); emission_col.b*=mat->get_emission_energy(); Image img_emission; if (emission_tex.is_valid()) { img_emission = emission_tex->get_data(); } mc.emission=_get_bake_texture(img_emission,emission_col); } else { Image empty; mc.albedo=_get_bake_texture(empty,Color(0.7,0.7,0.7)); mc.emission=_get_bake_texture(empty,Color(0,0,0)); } p_baker->material_cache[p_material]=mc; return mc; } void GIProbe::_plot_mesh(const Transform& p_xform, Ref<Mesh>& p_mesh, Baker *p_baker) { for(int i=0;i<p_mesh->get_surface_count();i++) { if (p_mesh->surface_get_primitive_type(i)!=Mesh::PRIMITIVE_TRIANGLES) continue; //only triangles Baker::MaterialCache material = _get_material_cache(p_mesh->surface_get_material(i),p_baker); Array a = p_mesh->surface_get_arrays(i); PoolVector<Vector3> vertices = a[Mesh::ARRAY_VERTEX]; PoolVector<Vector3>::Read vr=vertices.read(); PoolVector<Vector2> uv = a[Mesh::ARRAY_TEX_UV]; PoolVector<Vector2>::Read uvr; PoolVector<int> index = a[Mesh::ARRAY_INDEX]; bool read_uv=false; if (uv.size()) { uvr=uv.read(); read_uv=true; } if (index.size()) { int facecount = index.size()/3; PoolVector<int>::Read ir=index.read(); for(int j=0;j<facecount;j++) { Vector3 vtxs[3]; Vector2 uvs[3]; for(int k=0;k<3;k++) { vtxs[k]=p_xform.xform(vr[ir[j*3+k]]); } if (read_uv) { for(int k=0;k<3;k++) { uvs[k]=uvr[ir[j*3+k]]; } } //test against original bounds if (!fast_tri_box_overlap(-extents,extents*2,vtxs)) continue; //plot _plot_face(0,0,0,0,0,vtxs,uvs,material,p_baker->po2_bounds,p_baker); } } else { int facecount = vertices.size()/3; for(int j=0;j<facecount;j++) { Vector3 vtxs[3]; Vector2 uvs[3]; for(int k=0;k<3;k++) { vtxs[k]=p_xform.xform(vr[j*3+k]); } if (read_uv) { for(int k=0;k<3;k++) { uvs[k]=uvr[j*3+k]; } } //test against original bounds if (!fast_tri_box_overlap(-extents,extents*2,vtxs)) continue; //plot face _plot_face(0,0,0,0,0,vtxs,uvs,material,p_baker->po2_bounds,p_baker); } } } } void GIProbe::_find_meshes(Node *p_at_node,Baker *p_baker){ MeshInstance *mi = p_at_node->cast_to<MeshInstance>(); if (mi && mi->get_flag(GeometryInstance::FLAG_USE_BAKED_LIGHT)) { Ref<Mesh> mesh = mi->get_mesh(); if (mesh.is_valid()) { Rect3 aabb = mesh->get_aabb(); Transform xf = get_global_transform().affine_inverse() * mi->get_global_transform(); if (Rect3(-extents,extents*2).intersects(xf.xform(aabb))) { Baker::PlotMesh pm; pm.local_xform=xf; pm.mesh=mesh; p_baker->mesh_list.push_back(pm); } } } for(int i=0;i<p_at_node->get_child_count();i++) { Node *child = p_at_node->get_child(i); if (!child->get_owner()) continue; //maybe a helper _find_meshes(child,p_baker); } } void GIProbe::bake(Node *p_from_node, bool p_create_visual_debug){ Baker baker; static const int subdiv_value[SUBDIV_MAX]={7,8,9,10}; baker.cell_subdiv=subdiv_value[subdiv]; baker.bake_cells.resize(1); //find out the actual real bounds, power of 2, which gets the highest subdivision baker.po2_bounds=Rect3(-extents,extents*2.0); int longest_axis = baker.po2_bounds.get_longest_axis_index(); baker.axis_cell_size[longest_axis]=(1<<(baker.cell_subdiv-1)); baker.leaf_voxel_count=0; for(int i=0;i<3;i++) { if (i==longest_axis) continue; baker.axis_cell_size[i]=baker.axis_cell_size[longest_axis]; float axis_size = baker.po2_bounds.size[longest_axis]; //shrink until fit subdiv while (axis_size/2.0 >= baker.po2_bounds.size[i]) { axis_size/=2.0; baker.axis_cell_size[i]>>=1; } baker.po2_bounds.size[i]=baker.po2_bounds.size[longest_axis]; } Transform to_bounds; to_bounds.basis.scale(Vector3(baker.po2_bounds.size[longest_axis],baker.po2_bounds.size[longest_axis],baker.po2_bounds.size[longest_axis])); to_bounds.origin=baker.po2_bounds.pos; Transform to_grid; to_grid.basis.scale(Vector3(baker.axis_cell_size[longest_axis],baker.axis_cell_size[longest_axis],baker.axis_cell_size[longest_axis])); baker.to_cell_space = to_grid * to_bounds.affine_inverse(); _find_meshes(p_from_node?p_from_node:get_parent(),&baker); int pmc=0; for(List<Baker::PlotMesh>::Element *E=baker.mesh_list.front();E;E=E->next()) { print_line("plotting mesh "+itos(pmc++)+"/"+itos(baker.mesh_list.size())); _plot_mesh(E->get().local_xform,E->get().mesh,&baker); } _fixup_plot(0,0,0,0,0,&baker); //create the data for visual server PoolVector<int> data; data.resize( 16+(8+1+1+1+1)*baker.bake_cells.size() ); //4 for header, rest for rest. { PoolVector<int>::Write w = data.write(); uint32_t * w32 = (uint32_t*)w.ptr(); w32[0]=0;//version w32[1]=baker.cell_subdiv; //subdiv w32[2]=baker.axis_cell_size[0]; w32[3]=baker.axis_cell_size[1]; w32[4]=baker.axis_cell_size[2]; w32[5]=baker.bake_cells.size(); w32[6]=baker.leaf_voxel_count; int ofs=16; for(int i=0;i<baker.bake_cells.size();i++) { for(int j=0;j<8;j++) { w32[ofs++]=baker.bake_cells[i].childs[j]; } { //albedo uint32_t rgba=uint32_t(CLAMP(baker.bake_cells[i].albedo[0]*255.0,0,255))<<16; rgba|=uint32_t(CLAMP(baker.bake_cells[i].albedo[1]*255.0,0,255))<<8; rgba|=uint32_t(CLAMP(baker.bake_cells[i].albedo[2]*255.0,0,255))<<0; w32[ofs++]=rgba; } { //emission Vector3 e(baker.bake_cells[i].emission[0],baker.bake_cells[i].emission[1],baker.bake_cells[i].emission[2]); float l = e.length(); if (l>0) { e.normalize(); l=CLAMP(l/8.0,0,1.0); } uint32_t em=uint32_t(CLAMP(e[0]*255,0,255))<<24; em|=uint32_t(CLAMP(e[1]*255,0,255))<<16; em|=uint32_t(CLAMP(e[2]*255,0,255))<<8; em|=uint32_t(CLAMP(l*255,0,255)); w32[ofs++]=em; } //w32[ofs++]=baker.bake_cells[i].used_sides; { //normal Vector3 n(baker.bake_cells[i].normal[0],baker.bake_cells[i].normal[1],baker.bake_cells[i].normal[2]); n=n*Vector3(0.5,0.5,0.5)+Vector3(0.5,0.5,0.5); uint32_t norm=0; norm|=uint32_t(CLAMP( n.x*255.0, 0, 255))<<16; norm|=uint32_t(CLAMP( n.y*255.0, 0, 255))<<8; norm|=uint32_t(CLAMP( n.z*255.0, 0, 255))<<0; w32[ofs++]=norm; } { uint16_t alpha = CLAMP(uint32_t(baker.bake_cells[i].alpha*65535.0),0,65535); uint16_t level = baker.bake_cells[i].level; w32[ofs++] = (uint32_t(level)<<16)|uint32_t(alpha); } } } Ref<GIProbeData> probe_data; probe_data.instance(); probe_data->set_bounds(Rect3(-extents,extents*2.0)); probe_data->set_cell_size(baker.po2_bounds.size[longest_axis]/baker.axis_cell_size[longest_axis]); probe_data->set_dynamic_data(data); probe_data->set_dynamic_range(dynamic_range); probe_data->set_energy(energy); probe_data->set_interior(interior); probe_data->set_compress(compress); probe_data->set_to_cell_xform(baker.to_cell_space); set_probe_data(probe_data); if (p_create_visual_debug) { //_create_debug_mesh(&baker); } } void GIProbe::_debug_mesh(int p_idx, int p_level, const Rect3 &p_aabb,Ref<MultiMesh> &p_multimesh,int &idx,Baker *p_baker) { if (p_level==p_baker->cell_subdiv-1) { Vector3 center = p_aabb.pos+p_aabb.size*0.5; Transform xform; xform.origin=center; xform.basis.scale(p_aabb.size*0.5); p_multimesh->set_instance_transform(idx,xform); Color col=Color(p_baker->bake_cells[p_idx].albedo[0],p_baker->bake_cells[p_idx].albedo[1],p_baker->bake_cells[p_idx].albedo[2]); p_multimesh->set_instance_color(idx,col); idx++; } else { for(int i=0;i<8;i++) { if (p_baker->bake_cells[p_idx].childs[i]==Baker::CHILD_EMPTY) continue; Rect3 aabb=p_aabb; aabb.size*=0.5; if (i&1) aabb.pos.x+=aabb.size.x; if (i&2) aabb.pos.y+=aabb.size.y; if (i&4) aabb.pos.z+=aabb.size.z; _debug_mesh(p_baker->bake_cells[p_idx].childs[i],p_level+1,aabb,p_multimesh,idx,p_baker); } } } void GIProbe::_create_debug_mesh(Baker *p_baker) { Ref<MultiMesh> mm; mm.instance(); mm->set_transform_format(MultiMesh::TRANSFORM_3D); mm->set_color_format(MultiMesh::COLOR_8BIT); print_line("leaf voxels: "+itos(p_baker->leaf_voxel_count)); mm->set_instance_count(p_baker->leaf_voxel_count); Ref<Mesh> mesh; mesh.instance(); { Array arr; arr.resize(Mesh::ARRAY_MAX); PoolVector<Vector3> vertices; PoolVector<Color> colors; int vtx_idx=0; #define ADD_VTX(m_idx);\ vertices.push_back( face_points[m_idx] );\ colors.push_back( Color(1,1,1,1) );\ vtx_idx++;\ for (int i=0;i<6;i++) { Vector3 face_points[4]; for (int j=0;j<4;j++) { float v[3]; v[0]=1.0; v[1]=1-2*((j>>1)&1); v[2]=v[1]*(1-2*(j&1)); for (int k=0;k<3;k++) { if (i<3) face_points[j][(i+k)%3]=v[k]*(i>=3?-1:1); else face_points[3-j][(i+k)%3]=v[k]*(i>=3?-1:1); } } //tri 1 ADD_VTX(0); ADD_VTX(1); ADD_VTX(2); //tri 2 ADD_VTX(2); ADD_VTX(3); ADD_VTX(0); } arr[Mesh::ARRAY_VERTEX]=vertices; arr[Mesh::ARRAY_COLOR]=colors; mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES,arr); } { Ref<FixedSpatialMaterial> fsm; fsm.instance(); fsm->set_flag(FixedSpatialMaterial::FLAG_SRGB_VERTEX_COLOR,true); fsm->set_flag(FixedSpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR,true); fsm->set_flag(FixedSpatialMaterial::FLAG_UNSHADED,true); fsm->set_albedo(Color(1,1,1,1)); mesh->surface_set_material(0,fsm); } mm->set_mesh(mesh); int idx=0; _debug_mesh(0,0,p_baker->po2_bounds,mm,idx,p_baker); MultiMeshInstance *mmi = memnew( MultiMeshInstance ); mmi->set_multimesh(mm); add_child(mmi); #ifdef TOOLS_ENABLED if (get_tree()->get_edited_scene_root()==this){ mmi->set_owner(this); } else { mmi->set_owner(get_owner()); } #else mmi->set_owner(get_owner()); #endif } void GIProbe::_debug_bake() { bake(NULL,true); } Rect3 GIProbe::get_aabb() const { return Rect3(-extents,extents*2); } PoolVector<Face3> GIProbe::get_faces(uint32_t p_usage_flags) const { return PoolVector<Face3>(); } void GIProbe::_bind_methods() { ClassDB::bind_method(_MD("set_probe_data","data"),&GIProbe::set_probe_data); ClassDB::bind_method(_MD("get_probe_data"),&GIProbe::get_probe_data); ClassDB::bind_method(_MD("set_subdiv","subdiv"),&GIProbe::set_subdiv); ClassDB::bind_method(_MD("get_subdiv"),&GIProbe::get_subdiv); ClassDB::bind_method(_MD("set_extents","extents"),&GIProbe::set_extents); ClassDB::bind_method(_MD("get_extents"),&GIProbe::get_extents); ClassDB::bind_method(_MD("set_dynamic_range","max"),&GIProbe::set_dynamic_range); ClassDB::bind_method(_MD("get_dynamic_range"),&GIProbe::get_dynamic_range); ClassDB::bind_method(_MD("set_energy","max"),&GIProbe::set_energy); ClassDB::bind_method(_MD("get_energy"),&GIProbe::get_energy); ClassDB::bind_method(_MD("set_interior","enable"),&GIProbe::set_interior); ClassDB::bind_method(_MD("is_interior"),&GIProbe::is_interior); ClassDB::bind_method(_MD("set_compress","enable"),&GIProbe::set_compress); ClassDB::bind_method(_MD("is_compressed"),&GIProbe::is_compressed); ClassDB::bind_method(_MD("bake","from_node","create_visual_debug"),&GIProbe::bake,DEFVAL(Variant()),DEFVAL(false)); ClassDB::bind_method(_MD("debug_bake"),&GIProbe::_debug_bake); ClassDB::set_method_flags(get_class_static(),_SCS("debug_bake"),METHOD_FLAGS_DEFAULT|METHOD_FLAG_EDITOR); ADD_PROPERTY( PropertyInfo(Variant::INT,"subdiv",PROPERTY_HINT_ENUM,"64,128,256,512"),_SCS("set_subdiv"),_SCS("get_subdiv")); ADD_PROPERTY( PropertyInfo(Variant::VECTOR3,"extents"),_SCS("set_extents"),_SCS("get_extents")); ADD_PROPERTY( PropertyInfo(Variant::INT,"dynamic_range",PROPERTY_HINT_RANGE,"1,16,1"),_SCS("set_dynamic_range"),_SCS("get_dynamic_range")); ADD_PROPERTY( PropertyInfo(Variant::REAL,"energy",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_energy"),_SCS("get_energy")); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"interior"),_SCS("set_interior"),_SCS("is_interior")); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"compress"),_SCS("set_compress"),_SCS("is_compressed")); ADD_PROPERTY( PropertyInfo(Variant::OBJECT,"data",PROPERTY_HINT_RESOURCE_TYPE,"GIProbeData"),_SCS("set_probe_data"),_SCS("get_probe_data")); BIND_CONSTANT( SUBDIV_64 ); BIND_CONSTANT( SUBDIV_128 ); BIND_CONSTANT( SUBDIV_256 ); BIND_CONSTANT( SUBDIV_MAX ); } GIProbe::GIProbe() { subdiv=SUBDIV_128; dynamic_range=4; energy=1.0; extents=Vector3(10,10,10); color_scan_cell_width=4; bake_texture_size=128; interior=false; compress=false; gi_probe = VS::get_singleton()->gi_probe_create(); } GIProbe::~GIProbe() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio_server.cpp
1,174
/*************************************************************************/ /* audio_server.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "audio_server.h" #include "globals.h" #include "os/os.h" #include "servers/audio/effects/audio_effect_compressor.h" #include "io/resource_loader.h" #include "os/file_access.h" #ifdef TOOLS_ENABLED #define MARK_EDITED set_edited(true); #else #define MARK_EDITED #endif AudioDriver *AudioDriver::singleton=NULL; AudioDriver *AudioDriver::get_singleton() { return singleton; } void AudioDriver::set_singleton() { singleton=this; } void AudioDriver::audio_server_process(int p_frames,int32_t *p_buffer,bool p_update_mix_time) { if (p_update_mix_time) update_mix_time(p_frames); if (AudioServer::get_singleton()) AudioServer::get_singleton()->_driver_process(p_frames,p_buffer); } void AudioDriver::update_mix_time(int p_frames) { _mix_amount+=p_frames; _last_mix_time=OS::get_singleton()->get_ticks_usec(); } double AudioDriver::get_mix_time() const { double total = (OS::get_singleton()->get_ticks_usec() - _last_mix_time) / 1000000.0; total+=_mix_amount/(double)get_mix_rate(); return total; } AudioDriver::AudioDriver() { _last_mix_time=0; _mix_amount=0; } AudioDriver *AudioDriverManager::drivers[MAX_DRIVERS]; int AudioDriverManager::driver_count=0; void AudioDriverManager::add_driver(AudioDriver *p_driver) { ERR_FAIL_COND(driver_count>=MAX_DRIVERS); drivers[driver_count++]=p_driver; } int AudioDriverManager::get_driver_count() { return driver_count; } AudioDriver *AudioDriverManager::get_driver(int p_driver) { ERR_FAIL_INDEX_V(p_driver,driver_count,NULL); return drivers[p_driver]; } ////////////////////////////////////////////// ////////////////////////////////////////////// ////////////////////////////////////////////// ////////////////////////////////////////////// void AudioServer::_driver_process(int p_frames,int32_t* p_buffer) { int todo=p_frames; while(todo) { if (to_mix==0) { _mix_step(); } int to_copy = MIN(to_mix,todo); Bus *master = buses[0]; int from = buffer_size-to_mix; int from_buf=p_frames-todo; //master master, send to output int cs = master->channels.size(); for(int k=0;k<cs;k++) { if (master->channels[k].active) { AudioFrame *buf = master->channels[k].buffer.ptr(); for(int j=0;j<to_copy;j++) { float l = CLAMP(buf[from+j].l,-1.0,1.0); int32_t vl = l*((1<<20)-1); p_buffer[(from_buf+j)*(cs*2)+k*2+0]=vl<<11; float r = CLAMP(buf[from+j].r,-1.0,1.0); int32_t vr = r*((1<<20)-1); p_buffer[(from_buf+j)*(cs*2)+k*2+1]=vr<<11; } } else { for(int j=0;j<to_copy;j++) { p_buffer[(from_buf+j)*(cs*2)+k*2+0]=0; p_buffer[(from_buf+j)*(cs*2)+k*2+1]=0; } } } todo-=to_copy; to_mix-=to_copy; } } void AudioServer::_mix_step() { for(int i=0;i<buses.size();i++) { Bus *bus = buses[i]; bus->index_cache=i; //might be moved around by editor, so.. for(int k=0;k<bus->channels.size();k++) { bus->channels[k].used=false; } } //make callbacks for mixing the audio for (Set<CallbackItem>::Element *E=callbacks.front();E;E=E->next()) { E->get().callback(E->get().userdata); } for(int i=buses.size()-1;i>=0;i--) { //go bus by bus Bus *bus = buses[i]; for(int k=0;k<bus->channels.size();k++) { if (bus->channels[k].active && !bus->channels[k].used) { //buffer was not used, but it's still active, so it must be cleaned AudioFrame *buf = bus->channels[k].buffer.ptr(); for(uint32_t j=0;j<buffer_size;j++) { buf[j]=AudioFrame(0,0); } } } //process effects for(int j=0;j<bus->effects.size();j++) { if (!bus->effects[j].enabled) continue; for(int k=0;k<bus->channels.size();k++) { if (!bus->channels[k].active) continue; bus->channels[k].effect_instances[j]->process(bus->channels[k].buffer.ptr(),temp_buffer[k].ptr(),buffer_size); } //swap buffers, so internal buffer always has the right data for(int k=0;k<bus->channels.size();k++) { if (!buses[i]->channels[k].active) continue; SWAP(bus->channels[k].buffer,temp_buffer[k]); } } //process send Bus *send=NULL; if (i>0) { //everything has a send save for master bus if (!bus_map.has(bus->send)) { send=buses[0]; } else { send=bus_map[bus->send]; if (send->index_cache>=bus->index_cache) { //invalid, send to master send=buses[0]; } } } for(int k=0;k<bus->channels.size();k++) { if (!bus->channels[k].active) continue; AudioFrame *buf = bus->channels[k].buffer.ptr(); AudioFrame peak = AudioFrame(0,0); for(uint32_t j=0;j<buffer_size;j++) { float l = ABS(buf[j].l); if (l>peak.l) { peak.l=l; } float r = ABS(buf[j].r); if (r>peak.r) { peak.r=r; } } bus->channels[k].peak_volume=AudioFrame(Math::linear2db(peak.l+0.0000000001),Math::linear2db(peak.r+0.0000000001)); if (!bus->channels[k].used) { //see if any audio is contained, because channel was not used if (MAX(peak.r,peak.l) > Math::db2linear(channel_disable_treshold_db)) { bus->channels[k].last_mix_with_audio=mix_frames; } else if (mix_frames-bus->channels[k].last_mix_with_audio > channel_disable_frames ) { bus->channels[k].active=false; continue; //went inactive, dont mix. } } if (send) { //if not master bus, send AudioFrame *target_buf = thread_get_channel_mix_buffer(send->index_cache,k); for(uint32_t j=0;j<buffer_size;j++) { target_buf[j]+=buf[j]; } } } } mix_frames+=buffer_size; to_mix=buffer_size; } AudioFrame *AudioServer::thread_get_channel_mix_buffer(int p_bus,int p_buffer) { ERR_FAIL_INDEX_V(p_bus,buses.size(),NULL); ERR_FAIL_INDEX_V(p_buffer,buses[p_bus]->channels.size(),NULL); AudioFrame *data = buses[p_bus]->channels[p_buffer].buffer.ptr(); if (!buses[p_bus]->channels[p_buffer].used) { buses[p_bus]->channels[p_buffer].used=true; buses[p_bus]->channels[p_buffer].active=true; buses[p_bus]->channels[p_buffer].last_mix_with_audio=mix_frames; for(uint32_t i=0;i<buffer_size;i++) { data[i]=AudioFrame(0,0); } } return data; } int AudioServer::thread_get_mix_buffer_size() const { return buffer_size; } int AudioServer::thread_find_bus_index(const StringName& p_name) { if (bus_map.has(p_name)) { return bus_map[p_name]->index_cache; } else { return 0; } } void AudioServer::set_bus_count(int p_count) { ERR_FAIL_COND(p_count<1); ERR_FAIL_INDEX(p_count,256); MARK_EDITED lock(); int cb = buses.size(); if (p_count<buses.size()) { for(int i=p_count;i<buses.size();i++) { bus_map.erase(buses[i]->name); memdelete(buses[i]); } } buses.resize(p_count); for(int i=cb;i<buses.size();i++) { String attempt="New Bus"; int attempts=1; while(true) { bool name_free=true; for(int j=0;j<i;j++) { if (buses[j]->name==attempt) { name_free=false; break; } } if (!name_free) { attempts++; attempt="New Bus " +itos(attempts); } else { break; } } buses[i]=memnew(Bus); buses[i]->channels.resize(_get_channel_count()); for(int j=0;j<_get_channel_count();j++) { buses[i]->channels[j].buffer.resize(buffer_size); } buses[i]->name=attempt; buses[i]->solo=false; buses[i]->mute=false; buses[i]->bypass=false; buses[i]->volume_db=0; if (i>0) { buses[i]->send="Master"; } bus_map[attempt]=buses[i]; } unlock(); emit_signal("bus_layout_changed"); } void AudioServer::remove_bus(int p_index) { ERR_FAIL_INDEX(p_index,buses.size()); ERR_FAIL_COND(p_index==0); MARK_EDITED lock(); bus_map.erase(buses[p_index]->name); memdelete(buses[p_index]); buses.remove(p_index); unlock(); } void AudioServer::add_bus(int p_at_pos) { MARK_EDITED if (p_at_pos>=buses.size()) { p_at_pos=-1; } else if (p_at_pos==0) { if (buses.size()>1) p_at_pos=1; else p_at_pos=-1; } String attempt="New Bus"; int attempts=1; while(true) { bool name_free=true; for(int j=0;j<buses.size();j++) { if (buses[j]->name==attempt) { name_free=false; break; } } if (!name_free) { attempts++; attempt="New Bus " +itos(attempts); } else { break; } } Bus* bus =memnew(Bus); bus->channels.resize(_get_channel_count()); for(int j=0;j<_get_channel_count();j++) { bus->channels[j].buffer.resize(buffer_size); } bus->name=attempt; bus->solo=false; bus->mute=false; bus->bypass=false; bus->volume_db=0; bus_map[attempt]=bus; if (p_at_pos==-1) buses.push_back(bus); else buses.insert(p_at_pos,bus); } void AudioServer::move_bus(int p_bus,int p_to_pos) { ERR_FAIL_COND(p_bus<1 || p_bus>=buses.size()); ERR_FAIL_COND(p_to_pos!=-1 && (p_to_pos<1 || p_to_pos>buses.size())); MARK_EDITED if (p_bus==p_to_pos) return; Bus *bus = buses[p_bus]; buses.remove(p_bus); if (p_to_pos==-1) { buses.push_back(bus); } else if (p_to_pos<p_bus) { buses.insert(p_to_pos,bus); } else { buses.insert(p_to_pos-1,bus); } } int AudioServer::get_bus_count() const { return buses.size(); } void AudioServer::set_bus_name(int p_bus,const String& p_name) { ERR_FAIL_INDEX(p_bus,buses.size()); if (p_bus==0 && p_name!="Master") return; //bus 0 is always master MARK_EDITED lock(); if (buses[p_bus]->name==p_name) { unlock(); return; } String attempt=p_name; int attempts=1; while(true) { bool name_free=true; for(int i=0;i<buses.size();i++) { if (buses[i]->name==attempt) { name_free=false; break; } } if (name_free) { break; } attempts++; attempt=p_name+" "+itos(attempts); } bus_map.erase(buses[p_bus]->name); buses[p_bus]->name=attempt; bus_map[attempt]=buses[p_bus]; unlock(); emit_signal("bus_layout_changed"); } String AudioServer::get_bus_name(int p_bus) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),String()); return buses[p_bus]->name; } void AudioServer::set_bus_volume_db(int p_bus,float p_volume_db) { ERR_FAIL_INDEX(p_bus,buses.size()); MARK_EDITED buses[p_bus]->volume_db=p_volume_db; } float AudioServer::get_bus_volume_db(int p_bus) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),0); return buses[p_bus]->volume_db; } void AudioServer::set_bus_send(int p_bus,const StringName& p_send) { ERR_FAIL_INDEX(p_bus,buses.size()); MARK_EDITED buses[p_bus]->send=p_send; } StringName AudioServer::get_bus_send(int p_bus) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),StringName()); return buses[p_bus]->send; } void AudioServer::set_bus_solo(int p_bus,bool p_enable) { ERR_FAIL_INDEX(p_bus,buses.size()); MARK_EDITED buses[p_bus]->solo=p_enable; } bool AudioServer::is_bus_solo(int p_bus) const{ ERR_FAIL_INDEX_V(p_bus,buses.size(),false); return buses[p_bus]->solo; } void AudioServer::set_bus_mute(int p_bus,bool p_enable){ ERR_FAIL_INDEX(p_bus,buses.size()); MARK_EDITED buses[p_bus]->mute=p_enable; } bool AudioServer::is_bus_mute(int p_bus) const{ ERR_FAIL_INDEX_V(p_bus,buses.size(),false); return buses[p_bus]->mute; } void AudioServer::set_bus_bypass_effects(int p_bus,bool p_enable){ ERR_FAIL_INDEX(p_bus,buses.size()); MARK_EDITED buses[p_bus]->bypass=p_enable; } bool AudioServer::is_bus_bypassing_effects(int p_bus) const{ ERR_FAIL_INDEX_V(p_bus,buses.size(),false); return buses[p_bus]->bypass; } void AudioServer::_update_bus_effects(int p_bus) { for(int i=0;i<buses[p_bus]->channels.size();i++) { buses[p_bus]->channels[i].effect_instances.resize(buses[p_bus]->effects.size()); for(int j=0;j<buses[p_bus]->effects.size();j++) { Ref<AudioEffectInstance> fx = buses[p_bus]->effects[j].effect->instance(); if (fx->cast_to<AudioEffectCompressorInstance>()) { fx->cast_to<AudioEffectCompressorInstance>()->set_current_channel(i); } buses[p_bus]->channels[i].effect_instances[j]=fx; } } } void AudioServer::add_bus_effect(int p_bus,const Ref<AudioEffect>& p_effect,int p_at_pos) { ERR_FAIL_COND(p_effect.is_null()); ERR_FAIL_INDEX(p_bus,buses.size()); MARK_EDITED lock(); Bus::Effect fx; fx.effect=p_effect; //fx.instance=p_effect->instance(); fx.enabled=true; if (p_at_pos>=buses[p_bus]->effects.size() || p_at_pos<0) { buses[p_bus]->effects.push_back(fx); } else { buses[p_bus]->effects.insert(p_at_pos,fx); } _update_bus_effects(p_bus); unlock(); } void AudioServer::remove_bus_effect(int p_bus,int p_effect) { ERR_FAIL_INDEX(p_bus,buses.size()); MARK_EDITED lock(); buses[p_bus]->effects.remove(p_effect); _update_bus_effects(p_bus); unlock(); } int AudioServer::get_bus_effect_count(int p_bus) { ERR_FAIL_INDEX_V(p_bus,buses.size(),0); return buses[p_bus]->effects.size(); } Ref<AudioEffect> AudioServer::get_bus_effect(int p_bus,int p_effect) { ERR_FAIL_INDEX_V(p_bus,buses.size(),Ref<AudioEffect>()); ERR_FAIL_INDEX_V(p_effect,buses[p_bus]->effects.size(),Ref<AudioEffect>()); return buses[p_bus]->effects[p_effect].effect; } void AudioServer::swap_bus_effects(int p_bus,int p_effect,int p_by_effect) { ERR_FAIL_INDEX(p_bus,buses.size()); ERR_FAIL_INDEX(p_effect,buses[p_bus]->effects.size()); ERR_FAIL_INDEX(p_by_effect,buses[p_bus]->effects.size()); MARK_EDITED lock(); SWAP( buses[p_bus]->effects[p_effect], buses[p_bus]->effects[p_by_effect] ); _update_bus_effects(p_bus); unlock(); } void AudioServer::set_bus_effect_enabled(int p_bus,int p_effect,bool p_enabled) { ERR_FAIL_INDEX(p_bus,buses.size()); ERR_FAIL_INDEX(p_effect,buses[p_bus]->effects.size()); MARK_EDITED buses[p_bus]->effects[p_effect].enabled=p_enabled; } bool AudioServer::is_bus_effect_enabled(int p_bus,int p_effect) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),false); ERR_FAIL_INDEX_V(p_effect,buses[p_bus]->effects.size(),false); return buses[p_bus]->effects[p_effect].enabled; } float AudioServer::get_bus_peak_volume_left_db(int p_bus,int p_channel) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),0); ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),0); return buses[p_bus]->channels[p_channel].peak_volume.l; } float AudioServer::get_bus_peak_volume_right_db(int p_bus,int p_channel) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),0); ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),0); return buses[p_bus]->channels[p_channel].peak_volume.r; } bool AudioServer::is_bus_channel_active(int p_bus,int p_channel) const { ERR_FAIL_INDEX_V(p_bus,buses.size(),false); ERR_FAIL_INDEX_V(p_channel,buses[p_bus]->channels.size(),false); return buses[p_bus]->channels[p_channel].active; } void AudioServer::init() { channel_disable_treshold_db=GLOBAL_DEF("audio/channel_disable_treshold_db",-60.0); channel_disable_frames=float(GLOBAL_DEF("audio/channel_disable_time",2.0))*get_mix_rate(); buffer_size=1024; //harcoded for now switch( get_speaker_mode() ) { case SPEAKER_MODE_STEREO: { temp_buffer.resize(1); } break; case SPEAKER_SURROUND_51: { temp_buffer.resize(3); } break; case SPEAKER_SURROUND_71: { temp_buffer.resize(4); } break; } for(int i=0;i<temp_buffer.size();i++) { temp_buffer[i].resize(buffer_size); } mix_count=0; set_bus_count(1);; set_bus_name(0,"Master"); if (AudioDriver::get_singleton()) AudioDriver::get_singleton()->start(); #ifdef TOOLS_ENABLED set_edited(false); //avoid editors from thinking this was edited #endif } void AudioServer::load_default_bus_layout() { if (FileAccess::exists("res://default_bus_layout.tres")) { Ref<AudioBusLayout> default_layout = ResourceLoader::load("res://default_bus_layout.tres"); if (default_layout.is_valid()) { set_bus_layout(default_layout); } } } void AudioServer::finish() { for(int i=0;i<buses.size();i++) { memdelete(buses[i]); } buses.clear(); } void AudioServer::update() { } /* MISC config */ void AudioServer::lock() { AudioDriver::get_singleton()->lock(); } void AudioServer::unlock() { AudioDriver::get_singleton()->unlock(); } AudioServer::SpeakerMode AudioServer::get_speaker_mode() const { return (AudioServer::SpeakerMode)AudioDriver::get_singleton()->get_speaker_mode(); } float AudioServer::get_mix_rate() const { return AudioDriver::get_singleton()->get_mix_rate(); } float AudioServer::read_output_peak_db() const { return 0; } AudioServer *AudioServer::get_singleton() { return singleton; } double AudioServer::get_mix_time() const { return 0; } double AudioServer::get_output_delay() const { return 0; } AudioServer* AudioServer::singleton=NULL; void* AudioServer::audio_data_alloc(uint32_t p_data_len,const uint8_t *p_from_data) { void * ad = memalloc( p_data_len ); ERR_FAIL_COND_V(!ad,NULL); if (p_from_data) { copymem(ad,p_from_data,p_data_len); } audio_data_lock->lock(); audio_data[ad]=p_data_len; audio_data_total_mem+=p_data_len; audio_data_max_mem=MAX(audio_data_total_mem,audio_data_max_mem); audio_data_lock->unlock(); return ad; } void AudioServer::audio_data_free(void* p_data) { audio_data_lock->lock(); if (!audio_data.has(p_data)) { audio_data_lock->unlock(); ERR_FAIL(); } audio_data_total_mem-=audio_data[p_data]; audio_data.erase(p_data); memfree(p_data); audio_data_lock->unlock(); } size_t AudioServer::audio_data_get_total_memory_usage() const{ return audio_data_total_mem; } size_t AudioServer::audio_data_get_max_memory_usage() const{ return audio_data_max_mem; } void AudioServer::add_callback(AudioCallback p_callback,void *p_userdata) { lock(); CallbackItem ci; ci.callback=p_callback; ci.userdata=p_userdata; callbacks.insert(ci); unlock(); } void AudioServer::remove_callback(AudioCallback p_callback,void *p_userdata) { lock(); CallbackItem ci; ci.callback=p_callback; ci.userdata=p_userdata; callbacks.erase(ci); unlock(); } void AudioServer::set_bus_layout(const Ref<AudioBusLayout> &p_state) { ERR_FAIL_COND(p_state.is_null() || p_state->buses.size()==0); lock(); for(int i=0;i<buses.size();i++) { memdelete(buses[i]); } buses.resize(p_state->buses.size()); bus_map.clear(); for(int i=0;i<p_state->buses.size();i++) { Bus * bus = memnew(Bus); if (i==0) { bus->name="Master"; } else { bus->name=p_state->buses[i].name; bus->send=p_state->buses[i].send; } bus->solo=p_state->buses[i].solo; bus->mute=p_state->buses[i].mute; bus->bypass=p_state->buses[i].bypass; bus->volume_db=p_state->buses[i].volume_db; for(int j=0;j<p_state->buses[i].effects.size();j++) { Ref<AudioEffect> fx = p_state->buses[i].effects[j].effect; if (fx.is_valid()) { Bus::Effect bfx; bfx.effect=fx; bfx.enabled=p_state->buses[i].effects[j].enabled; bus->effects.push_back(bfx); } } bus_map[bus->name]=bus; buses[i]=bus; buses[i]->channels.resize(_get_channel_count()); for(int j=0;j<_get_channel_count();j++) { buses[i]->channels[j].buffer.resize(buffer_size); } _update_bus_effects(i); } #ifdef TOOLS_ENABLED set_edited(false); #endif unlock(); } Ref<AudioBusLayout> AudioServer::generate_bus_layout() const { Ref<AudioBusLayout> state; state.instance(); state->buses.resize( buses.size() ); for(int i=0;i<buses.size();i++) { state->buses[i].name=buses[i]->name; state->buses[i].send=buses[i]->send; state->buses[i].mute=buses[i]->mute; state->buses[i].solo=buses[i]->solo; state->buses[i].bypass=buses[i]->bypass; state->buses[i].volume_db=buses[i]->volume_db; for(int j=0;j<buses[i]->effects.size();j++) { AudioBusLayout::Bus::Effect fx; fx.effect=buses[i]->effects[j].effect; fx.enabled=buses[i]->effects[j].enabled; state->buses[i].effects.push_back(fx); } } return state; } void AudioServer::_bind_methods() { ClassDB::bind_method(_MD("set_bus_count","amount"),&AudioServer::set_bus_count); ClassDB::bind_method(_MD("get_bus_count"),&AudioServer::get_bus_count); ClassDB::bind_method(_MD("remove_bus","index"),&AudioServer::remove_bus); ClassDB::bind_method(_MD("add_bus","at_pos"),&AudioServer::add_bus,DEFVAL(-1)); ClassDB::bind_method(_MD("move_bus","index","to_index"),&AudioServer::move_bus); ClassDB::bind_method(_MD("set_bus_name","bus_idx","name"),&AudioServer::set_bus_name); ClassDB::bind_method(_MD("get_bus_name","bus_idx"),&AudioServer::get_bus_name); ClassDB::bind_method(_MD("set_bus_volume_db","bus_idx","volume_db"),&AudioServer::set_bus_volume_db); ClassDB::bind_method(_MD("get_bus_volume_db","bus_idx"),&AudioServer::get_bus_volume_db); ClassDB::bind_method(_MD("set_bus_send","bus_idx","send"),&AudioServer::set_bus_send); ClassDB::bind_method(_MD("get_bus_send","bus_idx"),&AudioServer::get_bus_send); ClassDB::bind_method(_MD("set_bus_solo","bus_idx","enable"),&AudioServer::set_bus_solo); ClassDB::bind_method(_MD("is_bus_solo","bus_idx"),&AudioServer::is_bus_solo); ClassDB::bind_method(_MD("set_bus_mute","bus_idx","enable"),&AudioServer::set_bus_mute); ClassDB::bind_method(_MD("is_bus_mute","bus_idx"),&AudioServer::is_bus_mute); ClassDB::bind_method(_MD("set_bus_bypass_effects","bus_idx","enable"),&AudioServer::set_bus_bypass_effects); ClassDB::bind_method(_MD("is_bus_bypassing_effects","bus_idx"),&AudioServer::is_bus_bypassing_effects); ClassDB::bind_method(_MD("add_bus_effect","bus_idx","effect:AudioEffect"),&AudioServer::add_bus_effect,DEFVAL(-1)); ClassDB::bind_method(_MD("remove_bus_effect","bus_idx","effect_idx"),&AudioServer::remove_bus_effect); ClassDB::bind_method(_MD("get_bus_effect_count","bus_idx"),&AudioServer::add_bus_effect); ClassDB::bind_method(_MD("get_bus_effect:AudioEffect","bus_idx","effect_idx"),&AudioServer::get_bus_effect); ClassDB::bind_method(_MD("swap_bus_effects","bus_idx","effect_idx","by_effect_idx"),&AudioServer::swap_bus_effects); ClassDB::bind_method(_MD("set_bus_effect_enabled","bus_idx","effect_idx","enabled"),&AudioServer::set_bus_effect_enabled); ClassDB::bind_method(_MD("is_bus_effect_enabled","bus_idx","effect_idx"),&AudioServer::is_bus_effect_enabled); ClassDB::bind_method(_MD("get_bus_peak_volume_left_db","bus_idx","channel"),&AudioServer::get_bus_peak_volume_left_db); ClassDB::bind_method(_MD("get_bus_peak_volume_right_db","bus_idx","channel"),&AudioServer::get_bus_peak_volume_right_db); ClassDB::bind_method(_MD("lock"),&AudioServer::lock); ClassDB::bind_method(_MD("unlock"),&AudioServer::unlock); ClassDB::bind_method(_MD("get_speaker_mode"),&AudioServer::get_speaker_mode); ClassDB::bind_method(_MD("get_mix_rate"),&AudioServer::get_mix_rate); ClassDB::bind_method(_MD("set_state","state:AudioServerState"),&AudioServer::set_bus_layout); ClassDB::bind_method(_MD("generate_state:AudioServerState"),&AudioServer::generate_bus_layout); ADD_SIGNAL(MethodInfo("bus_layout_changed") ); } AudioServer::AudioServer() { singleton=this; audio_data_total_mem=0; audio_data_max_mem=0; audio_data_lock=Mutex::create(); mix_frames=0; to_mix=0; } AudioServer::~AudioServer() { memdelete(audio_data_lock); } ///////////////////////////////// bool AudioBusLayout::_set(const StringName& p_name, const Variant& p_value) { String s = p_name; if (s.begins_with("bus/")) { int index = s.get_slice("/",1).to_int(); if (buses.size()<=index) { buses.resize(index+1); } Bus &bus = buses[index]; String what = s.get_slice("/",2); if (what=="name") { bus.name=p_value; } else if (what=="solo") { bus.solo=p_value; } else if (what=="mute") { bus.mute=p_value; } else if (what=="bypass_fx") { bus.bypass=p_value; } else if (what=="volume_db") { bus.volume_db=p_value; } else if (what=="send") { bus.send=p_value; } else if (what=="effect") { int which = s.get_slice("/",3).to_int(); if (bus.effects.size()<=which) { bus.effects.resize(which+1); } Bus::Effect &fx = bus.effects[which]; String fxwhat = s.get_slice("/",4); if (fxwhat=="effect") { fx.effect=p_value; } else if (fxwhat=="enabled") { fx.enabled=p_value; } else { return false; } return true; } else { return false; } return true; } return false; } bool AudioBusLayout::_get(const StringName& p_name,Variant &r_ret) const{ String s = p_name; if (s.begins_with("bus/")) { int index = s.get_slice("/",1).to_int(); if (index<0 || index>=buses.size()) return false; const Bus &bus = buses[index]; String what = s.get_slice("/",2); if (what=="name") { r_ret=bus.name; } else if (what=="solo") { r_ret=bus.solo; } else if (what=="mute") { r_ret=bus.mute; } else if (what=="bypass_fx") { r_ret=bus.bypass; } else if (what=="volume_db") { r_ret=bus.volume_db; } else if (what=="send") { r_ret=bus.send; } else if (what=="effect") { int which = s.get_slice("/",3).to_int(); if (which<0 || which>=bus.effects.size()) { return false; } const Bus::Effect &fx = bus.effects[which]; String fxwhat = s.get_slice("/",4); if (fxwhat=="effect") { r_ret=fx.effect; } else if (fxwhat=="enabled") { r_ret=fx.enabled; } else { return false; } return true; } else { return false; } return true; } return false; } void AudioBusLayout::_get_property_list( List<PropertyInfo> *p_list) const{ for(int i=0;i<buses.size();i++) { p_list->push_back(PropertyInfo(Variant::STRING,"bus/"+itos(i)+"/name",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/solo",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/mute",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/bypass_fx",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::REAL,"bus/"+itos(i)+"/volume_db",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::REAL,"bus/"+itos(i)+"/send",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); for(int j=0;j<buses[i].effects.size();j++) { p_list->push_back(PropertyInfo(Variant::OBJECT,"bus/"+itos(i)+"/effect/"+itos(j)+"/effect",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); p_list->push_back(PropertyInfo(Variant::BOOL,"bus/"+itos(i)+"/effect/"+itos(j)+"/enabled",PROPERTY_HINT_NONE,"",PROPERTY_USAGE_NOEDITOR)); } } } AudioBusLayout::AudioBusLayout() { buses.resize(1); buses[0].name="Master"; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/visual/shader_types.cpp
182
#include "shader_types.h" const Map< StringName, Map<StringName,ShaderLanguage::DataType> >& ShaderTypes::get_functions(VS::ShaderMode p_mode) { return shader_modes[p_mode].functions; } const Set<String>& ShaderTypes::get_modes(VS::ShaderMode p_mode) { return shader_modes[p_mode].modes; } ShaderTypes *ShaderTypes::singleton=NULL; ShaderTypes::ShaderTypes() { singleton=this; /*************** SPATIAL ***********************/ shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_VERTEX"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_NORMAL"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_TANGENT"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_BONES"]=ShaderLanguage::TYPE_IVEC4; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["SRC_WEIGHTS"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POSITION"]=ShaderLanguage::TYPE_VEC4 ; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VERTEX"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TANGENT"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["BINORMAL"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["UV2"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["COLOR"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["POINT_SIZE"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INSTANCE_ID"]=ShaderLanguage::TYPE_INT; //builtins shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["INV_CAMERA_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["vertex"]["VIEWPORT_SIZE"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VERTEX"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRAGCOORD"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["FRONT_FACING"]=ShaderLanguage::TYPE_BOOL; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TANGENT"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["BINORMAL"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMALMAP_DEPTH"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["UV2"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["COLOR"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALBEDO"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ALPHA"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECULAR"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ROUGHNESS"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["RIM_TINT"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["CLEARCOAT_GLOSS"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["ANISOTROPY_FLOW"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SSS_STRENGTH"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["AO"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["EMISSION"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SPECIAL"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["DISCARD"]=ShaderLanguage::TYPE_BOOL; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["INV_CAMERA_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["TIME"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_SPATIAL].functions["fragment"]["VIEWPORT_SIZE"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_mix"); shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_add"); shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_sub"); shader_modes[VS::SHADER_SPATIAL].modes.insert("blend_mul"); shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_draw_opaque"); shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_draw_always"); shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_draw_never"); shader_modes[VS::SHADER_SPATIAL].modes.insert("depth_draw_alpha_prepass"); shader_modes[VS::SHADER_SPATIAL].modes.insert("cull_front"); shader_modes[VS::SHADER_SPATIAL].modes.insert("cull_back"); shader_modes[VS::SHADER_SPATIAL].modes.insert("cull_disabled"); shader_modes[VS::SHADER_SPATIAL].modes.insert("unshaded"); shader_modes[VS::SHADER_SPATIAL].modes.insert("ontop"); shader_modes[VS::SHADER_SPATIAL].modes.insert("skip_transform"); /************ CANVAS ITEM **************************/ shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["SRC_VERTEX"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["VERTEX_COLOR"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["POINT_SIZE"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["WORLD_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["PROJECTION_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["EXTRA_MATRIX"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SRC_COLOR"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POSITION"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["NORMALMAP_DEPTH"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["COLOR"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE"]=ShaderLanguage::TYPE_SAMPLER2D; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TEXTURE_PIXEL_SIZE"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["fragment"]["TIME"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POSITION"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["NORMAL"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["COLOR"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE"]=ShaderLanguage::TYPE_SAMPLER2D; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TEXTURE_PIXEL_SIZE"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR1"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["VAR2"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_VEC"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_HEIGHT"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_COLOR"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_UV"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT_SHADOW"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["LIGHT"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["SHADOW"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["POINT_COORD"]=ShaderLanguage::TYPE_VEC2; shader_modes[VS::SHADER_CANVAS_ITEM].functions["light"]["TIME"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("skip_transform"); shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_mix"); shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_add"); shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_sub"); shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_mul"); shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("blend_premul_alpha"); shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("unshaded"); shader_modes[VS::SHADER_CANVAS_ITEM].modes.insert("light_only"); /************ PARTICLES **************************/ shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["COLOR"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["VELOCITY"]=ShaderLanguage::TYPE_VEC3; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["MASS"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ACTIVE"]=ShaderLanguage::TYPE_BOOL; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["RESTART"]=ShaderLanguage::TYPE_BOOL; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["CUSTOM"]=ShaderLanguage::TYPE_VEC4; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TRANSFORM"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["TIME"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["LIFETIME"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["DELTA"]=ShaderLanguage::TYPE_FLOAT; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["SEED"]=ShaderLanguage::TYPE_BOOL; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["ORIGIN"]=ShaderLanguage::TYPE_MAT4; shader_modes[VS::SHADER_PARTICLES].functions["vertex"]["INDEX"]=ShaderLanguage::TYPE_INT; shader_modes[VS::SHADER_PARTICLES].modes.insert("billboard"); shader_modes[VS::SHADER_PARTICLES].modes.insert("disable_force"); shader_modes[VS::SHADER_PARTICLES].modes.insert("disable_velocity"); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_stereo_enhance.cpp
135
#include "audio_effect_stereo_enhance.h" #include "servers/audio_server.h" void AudioEffectStereoEnhanceInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { float intensity=base->pan_pullout; bool surround_mode=base->surround>0; float surround_amount=base->surround; unsigned int delay_frames=(base->time_pullout/1000.0)*AudioServer::get_singleton()->get_mix_rate(); for (int i=0;i<p_frame_count;i++) { float l=p_src_frames[i].l; float r=p_src_frames[i].r; float center=(l+r)/2.0f; l=( center+(l-center)*intensity ); r=( center+(r-center)*intensity ); if (surround_mode) { float val=(l+r)/2.0; delay_ringbuff[ringbuff_pos&ringbuff_mask]=val; float out=delay_ringbuff[(ringbuff_pos-delay_frames)&ringbuff_mask]*surround_amount; l+=out; r+=-out; } else { float val=r; delay_ringbuff[ringbuff_pos&ringbuff_mask]=val; //r is delayed r=delay_ringbuff[(ringbuff_pos-delay_frames)&ringbuff_mask];; } p_dst_frames[i].l=l; p_dst_frames[i].r=r; ringbuff_pos++; } } AudioEffectStereoEnhanceInstance::~AudioEffectStereoEnhanceInstance() { memdelete_arr(delay_ringbuff); } Ref<AudioEffectInstance> AudioEffectStereoEnhance::instance() { Ref<AudioEffectStereoEnhanceInstance> ins; ins.instance(); ins->base=Ref<AudioEffectStereoEnhance>(this); float ring_buffer_max_size=AudioEffectStereoEnhanceInstance::MAX_DELAY_MS+2; ring_buffer_max_size/=1000.0;//convert to seconds ring_buffer_max_size*=AudioServer::get_singleton()->get_mix_rate(); int ringbuff_size=(int)ring_buffer_max_size; int bits=0; while(ringbuff_size>0) { bits++; ringbuff_size/=2; } ringbuff_size=1<<bits; ins->ringbuff_mask=ringbuff_size-1; ins->ringbuff_pos=0; ins->delay_ringbuff = memnew_arr(float,ringbuff_size ); return ins; } void AudioEffectStereoEnhance::set_pan_pullout(float p_amount) { pan_pullout=p_amount; } float AudioEffectStereoEnhance::get_pan_pullout() const { return pan_pullout; } void AudioEffectStereoEnhance::set_time_pullout(float p_amount) { time_pullout=p_amount; } float AudioEffectStereoEnhance::get_time_pullout() const { return time_pullout; } void AudioEffectStereoEnhance::set_surround(float p_amount) { surround=p_amount; } float AudioEffectStereoEnhance::get_surround() const { return surround; } void AudioEffectStereoEnhance::_bind_methods() { ClassDB::bind_method(_MD("set_pan_pullout","amount"),&AudioEffectStereoEnhance::set_pan_pullout); ClassDB::bind_method(_MD("get_pan_pullout"),&AudioEffectStereoEnhance::get_pan_pullout); ClassDB::bind_method(_MD("set_time_pullout","amount"),&AudioEffectStereoEnhance::set_time_pullout); ClassDB::bind_method(_MD("get_time_pullout"),&AudioEffectStereoEnhance::get_time_pullout); ClassDB::bind_method(_MD("set_surround","amount"),&AudioEffectStereoEnhance::set_surround); ClassDB::bind_method(_MD("get_surround"),&AudioEffectStereoEnhance::get_surround); ADD_PROPERTY(PropertyInfo(Variant::REAL,"pan_pullout",PROPERTY_HINT_RANGE,"0,4,0.01"),_SCS("set_pan_pullout"),_SCS("get_pan_pullout")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"time_pullout_ms",PROPERTY_HINT_RANGE,"0,50,0.01"),_SCS("set_time_pullout"),_SCS("get_time_pullout")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"surround",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_surround"),_SCS("get_surround")); } AudioEffectStereoEnhance::AudioEffectStereoEnhance() { pan_pullout=1; time_pullout=0; surround=0; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_reverb.cpp
182
#include "audio_effect_reverb.h" #include "servers/audio_server.h" void AudioEffectReverbInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { for(int i=0;i<2;i++) { Reverb &r=reverb[i]; r.set_predelay( base->predelay); r.set_predelay_feedback( base->predelay_fb ); r.set_highpass( base->hpf ); r.set_room_size( base->room_size ); r.set_damp( base->damping ); r.set_extra_spread( base->spread ); r.set_wet( base->wet ); r.set_dry( base->dry ); } int todo = p_frame_count; int offset=0; while(todo) { int to_mix = MIN(todo,Reverb::INPUT_BUFFER_MAX_SIZE); for(int j=0;j<to_mix;j++) { tmp_src[j]=p_src_frames[offset+j].l; } reverb[0].process(tmp_src,tmp_dst,to_mix); for(int j=0;j<to_mix;j++) { p_dst_frames[offset+j].l=tmp_dst[j]; tmp_src[j]=p_src_frames[offset+j].r; } reverb[1].process(tmp_src,tmp_dst,to_mix); for(int j=0;j<to_mix;j++) { p_dst_frames[offset+j].r=tmp_dst[j]; } offset+=to_mix; todo-=to_mix; } } AudioEffectReverbInstance::AudioEffectReverbInstance() { reverb[0].set_mix_rate( AudioServer::get_singleton()->get_mix_rate() ); reverb[0].set_extra_spread_base(0); reverb[1].set_mix_rate( AudioServer::get_singleton()->get_mix_rate() ); reverb[1].set_extra_spread_base(0.000521); //for stereo effect } Ref<AudioEffectInstance> AudioEffectReverb::instance() { Ref<AudioEffectReverbInstance> ins; ins.instance(); ins->base=Ref<AudioEffectReverb>(this); return ins; } void AudioEffectReverb::set_predelay_msec(float p_msec) { predelay=p_msec; } void AudioEffectReverb::set_predelay_feedback(float p_feedback){ predelay_fb=p_feedback; } void AudioEffectReverb::set_room_size(float p_size){ room_size=p_size; } void AudioEffectReverb::set_damping(float p_damping){ damping=p_damping; } void AudioEffectReverb::set_spread(float p_spread){ spread=p_spread; } void AudioEffectReverb::set_dry(float p_dry){ dry=p_dry; } void AudioEffectReverb::set_wet(float p_wet){ wet=p_wet; } void AudioEffectReverb::set_hpf(float p_hpf) { hpf=p_hpf; } float AudioEffectReverb::get_predelay_msec() const { return predelay; } float AudioEffectReverb::get_predelay_feedback() const { return predelay_fb; } float AudioEffectReverb::get_room_size() const { return room_size; } float AudioEffectReverb::get_damping() const { return damping; } float AudioEffectReverb::get_spread() const { return spread; } float AudioEffectReverb::get_dry() const { return dry; } float AudioEffectReverb::get_wet() const { return wet; } float AudioEffectReverb::get_hpf() const { return hpf; } void AudioEffectReverb::_bind_methods() { ClassDB::bind_method(_MD("set_predelay_msec","msec"),&AudioEffectReverb::set_predelay_msec); ClassDB::bind_method(_MD("get_predelay_msec"),&AudioEffectReverb::get_predelay_msec); ClassDB::bind_method(_MD("set_predelay_feedback","feedback"),&AudioEffectReverb::set_predelay_feedback); ClassDB::bind_method(_MD("get_predelay_feedback"),&AudioEffectReverb::get_predelay_feedback); ClassDB::bind_method(_MD("set_room_size","size"),&AudioEffectReverb::set_room_size); ClassDB::bind_method(_MD("get_room_size"),&AudioEffectReverb::get_room_size); ClassDB::bind_method(_MD("set_damping","amount"),&AudioEffectReverb::set_damping); ClassDB::bind_method(_MD("get_damping"),&AudioEffectReverb::get_damping); ClassDB::bind_method(_MD("set_spread","amount"),&AudioEffectReverb::set_spread); ClassDB::bind_method(_MD("get_spread"),&AudioEffectReverb::get_spread); ClassDB::bind_method(_MD("set_dry","amount"),&AudioEffectReverb::set_dry); ClassDB::bind_method(_MD("get_dry"),&AudioEffectReverb::get_dry); ClassDB::bind_method(_MD("set_wet","amount"),&AudioEffectReverb::set_wet); ClassDB::bind_method(_MD("get_wet"),&AudioEffectReverb::get_wet); ClassDB::bind_method(_MD("set_hpf","amount"),&AudioEffectReverb::set_hpf); ClassDB::bind_method(_MD("get_hpf"),&AudioEffectReverb::get_hpf); ADD_GROUP("Predelay","predelay_"); ADD_PROPERTY(PropertyInfo(Variant::REAL,"predelay_msec",PROPERTY_HINT_RANGE,"20,500,1"),_SCS("set_predelay_msec"),_SCS("get_predelay_msec")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"predelay_feedback",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_predelay_msec"),_SCS("get_predelay_msec")); ADD_GROUP("",""); ADD_PROPERTY(PropertyInfo(Variant::REAL,"room_size",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_room_size"),_SCS("get_room_size")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"damping",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_damping"),_SCS("get_damping")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"spread",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_spread"),_SCS("get_spread")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"hipass",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_hpf"),_SCS("get_hpf")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dry",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_dry"),_SCS("get_dry")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"wet",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_wet"),_SCS("get_wet")); } AudioEffectReverb::AudioEffectReverb() { predelay=150; predelay_fb=0.4; hpf=0; room_size=0.8; damping=0.5; spread=1.0; dry=1.0; wet=0.5; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
drivers/gles3/shader_gles3.cpp
839
/*************************************************************************/ /* shader_gles2.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "shader_gles3.h" #include "print_string.h" //#define DEBUG_OPENGL #ifdef DEBUG_OPENGL #define DEBUG_TEST_ERROR(m_section)\ {\ uint32_t err = glGetError();\ if (err) {\ print_line("OpenGL Error #"+itos(err)+" at: "+m_section);\ }\ } #else #define DEBUG_TEST_ERROR(m_section) #endif ShaderGLES3 *ShaderGLES3::active=NULL; //#define DEBUG_SHADER #ifdef DEBUG_SHADER #define DEBUG_PRINT(m_text) print_line(m_text); #else #define DEBUG_PRINT(m_text) #endif void ShaderGLES3::bind_uniforms() { if (!uniforms_dirty) { return; }; // upload default uniforms const Map<uint32_t,Variant>::Element *E =uniform_defaults.front(); while(E) { int idx=E->key(); int location=version->uniform_location[idx]; if (location<0) { E=E->next(); continue; } const Variant &v=E->value(); _set_uniform_variant(location, v); //print_line("uniform "+itos(location)+" value "+v+ " type "+Variant::get_type_name(v.get_type())); E=E->next(); }; const Map<uint32_t,CameraMatrix>::Element* C = uniform_cameras.front(); while (C) { int location = version->uniform_location[C->key()]; if (location<0) { C=C->next(); continue; } glUniformMatrix4fv(location,1,false,&(C->get().matrix[0][0])); C = C->next(); }; uniforms_dirty = false; }; GLint ShaderGLES3::get_uniform_location(int p_idx) const { ERR_FAIL_COND_V(!version, -1); return version->uniform_location[p_idx]; }; bool ShaderGLES3::bind() { if (active!=this || !version || new_conditional_version.key!=conditional_version.key) { conditional_version=new_conditional_version; version = get_current_version(); } else { return false; } ERR_FAIL_COND_V(!version,false); glUseProgram( version->id ); DEBUG_TEST_ERROR("Use Program"); active=this; uniforms_dirty = true; /* * why on earth is this code here? for (int i=0;i<texunit_pair_count;i++) { glUniform1i(texunit_pairs[i].location, texunit_pairs[i].index); DEBUG_TEST_ERROR("Uniform 1 i"); } */ return true; } void ShaderGLES3::unbind() { version=NULL; glUseProgram(0); uniforms_dirty = true; active=NULL; } static void _display_error_with_code(const String& p_error,const Vector<const char*>& p_code) { int line=1; String total_code; for(int i=0;i<p_code.size();i++) { total_code+=String(p_code[i]); } Vector<String> lines = String(total_code).split("\n"); for(int j=0;j<lines.size();j++) { print_line(itos(line)+": "+lines[j]); line++; } ERR_PRINTS(p_error); } ShaderGLES3::Version* ShaderGLES3::get_current_version() { Version *_v=version_map.getptr(conditional_version); if (_v) { if (conditional_version.code_version!=0) { CustomCode *cc=custom_code_map.getptr(conditional_version.code_version); ERR_FAIL_COND_V(!cc,_v); if (cc->version==_v->code_version) return _v; } else { return _v; } } if (!_v) version_map[conditional_version]=Version(); Version &v = version_map[conditional_version]; if (!_v) { v.uniform_location = memnew_arr( GLint, uniform_count ); } else { if (v.ok) { //bye bye shaders glDeleteShader( v.vert_id ); glDeleteShader( v.frag_id ); glDeleteProgram( v.id ); v.id=0; } } v.ok=false; /* SETUP CONDITIONALS */ Vector<const char*> strings; #ifdef GLES_OVER_GL strings.push_back("#version 330\n"); #else strings.push_back("#version 300 es\n"); #endif int define_line_ofs=1; for(int i=0;i<custom_defines.size();i++) { strings.push_back(custom_defines[i].get_data()); define_line_ofs++; } for(int j=0;j<conditional_count;j++) { bool enable=((1<<j)&conditional_version.version); strings.push_back(enable?conditional_defines[j]:""); if (enable) define_line_ofs++; if (enable) { DEBUG_PRINT(conditional_defines[j]); } } //keep them around during the function CharString code_string; CharString code_string2; CharString code_globals; CharString material_string; //print_line("code version? "+itos(conditional_version.code_version)); CustomCode *cc=NULL; if ( conditional_version.code_version>0 ) { //do custom code related stuff ERR_FAIL_COND_V( !custom_code_map.has( conditional_version.code_version ), NULL ); cc=&custom_code_map[conditional_version.code_version]; v.code_version=cc->version; define_line_ofs+=2; } /* CREATE PROGRAM */ v.id = glCreateProgram(); ERR_FAIL_COND_V(v.id==0, NULL); /* VERTEX SHADER */ if (cc) { for(int i=0;i<cc->custom_defines.size();i++) { strings.push_back(cc->custom_defines[i].get_data()); DEBUG_PRINT("CD #"+itos(i)+": "+String(cc->custom_defines[i])); } } int strings_base_size=strings.size(); //vertex precision is high strings.push_back("precision highp float;\n"); strings.push_back("precision highp int;\n"); #if 0 if (cc) { String _code_string = "#define VERTEX_SHADER_CODE "+cc->vertex+"\n"; String _code_globals = "#define VERTEX_SHADER_GLOBALS "+cc->vertex_globals+"\n"; code_string=_code_string.ascii(); code_globals=_code_globals.ascii(); DEBUG_PRINT( code_globals.get_data() ); DEBUG_PRINT( code_string.get_data() ); strings.push_back(code_globals); strings.push_back(code_string); } #endif strings.push_back(vertex_code0.get_data()); if (cc) { code_globals=cc->vertex_globals.ascii(); strings.push_back(code_globals.get_data()); } strings.push_back(vertex_code1.get_data()); if (cc) { material_string=cc->uniforms.ascii(); strings.push_back(material_string.get_data()); } strings.push_back(vertex_code2.get_data()); if (cc) { code_string=cc->vertex.ascii(); strings.push_back(code_string.get_data()); } strings.push_back(vertex_code3.get_data()); #ifdef DEBUG_SHADER DEBUG_PRINT("\nVertex Code:\n\n"+String(code_string.get_data())); for(int i=0;i<strings.size();i++) { //print_line("vert strings "+itos(i)+":"+String(strings[i])); } #endif v.vert_id = glCreateShader(GL_VERTEX_SHADER); glShaderSource(v.vert_id,strings.size(),&strings[0],NULL); glCompileShader(v.vert_id); GLint status; glGetShaderiv(v.vert_id,GL_COMPILE_STATUS,&status); if (status==GL_FALSE) { // error compiling GLsizei iloglen; glGetShaderiv(v.vert_id,GL_INFO_LOG_LENGTH,&iloglen); if (iloglen<0) { glDeleteShader(v.vert_id); glDeleteProgram( v.id ); v.id=0; ERR_PRINT("NO LOG, WTF"); } else { if (iloglen==0) { iloglen = 4096; //buggy driver (Adreno 220+....) } char *ilogmem = (char*)memalloc(iloglen+1); ilogmem[iloglen]=0; glGetShaderInfoLog(v.vert_id, iloglen, &iloglen, ilogmem); String err_string=get_shader_name()+": Vertex Program Compilation Failed:\n"; err_string+=ilogmem; _display_error_with_code(err_string,strings); memfree(ilogmem); glDeleteShader(v.vert_id); glDeleteProgram( v.id ); v.id=0; } ERR_FAIL_V(NULL); } /* FRAGMENT SHADER */ strings.resize(strings_base_size); //fragment precision is medium strings.push_back("precision highp float;\n"); strings.push_back("precision highp int;\n"); #if 0 if (cc) { String _code_string = "#define FRAGMENT_SHADER_CODE "+cc->fragment+"\n"; String _code_globals = "#define FRAGMENT_SHADER_GLOBALS "+cc->fragment_globals+"\n"; code_string=_code_string.ascii(); code_globals=_code_globals.ascii(); DEBUG_PRINT( code_globals.get_data() ); DEBUG_PRINT( code_string.get_data() ); strings.push_back(code_globals); strings.push_back(code_string); } #endif strings.push_back(fragment_code0.get_data()); if (cc) { code_globals=cc->fragment_globals.ascii(); strings.push_back(code_globals.get_data()); } strings.push_back(fragment_code1.get_data()); if (cc) { material_string=cc->uniforms.ascii(); strings.push_back(material_string.get_data()); } strings.push_back(fragment_code2.get_data()); if (cc) { code_string=cc->fragment.ascii(); strings.push_back(code_string.get_data()); } strings.push_back(fragment_code3.get_data()); if (cc) { code_string2=cc->light.ascii(); strings.push_back(code_string2.get_data()); } strings.push_back(fragment_code4.get_data()); #ifdef DEBUG_SHADER DEBUG_PRINT("\nFragment Code:\n\n"+String(code_string.get_data())); for(int i=0;i<strings.size();i++) { //print_line("frag strings "+itos(i)+":"+String(strings[i])); } #endif v.frag_id = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(v.frag_id,strings.size(),&strings[0],NULL); glCompileShader(v.frag_id); glGetShaderiv(v.frag_id,GL_COMPILE_STATUS,&status); if (status==GL_FALSE) { // error compiling GLsizei iloglen; glGetShaderiv(v.frag_id,GL_INFO_LOG_LENGTH,&iloglen); if (iloglen<0) { glDeleteShader(v.frag_id); glDeleteShader(v.vert_id); glDeleteProgram( v.id ); v.id=0; ERR_PRINT("NO LOG, WTF"); } else { if (iloglen==0) { iloglen = 4096; //buggy driver (Adreno 220+....) } char *ilogmem = (char*)memalloc(iloglen+1); ilogmem[iloglen]=0; glGetShaderInfoLog(v.frag_id, iloglen, &iloglen, ilogmem); String err_string=get_shader_name()+": Fragment Program Compilation Failed:\n"; err_string+=ilogmem; _display_error_with_code(err_string,strings); ERR_PRINT(err_string.ascii().get_data()); memfree(ilogmem); glDeleteShader(v.frag_id); glDeleteShader(v.vert_id); glDeleteProgram( v.id ); v.id=0; } ERR_FAIL_V( NULL ); } glAttachShader(v.id,v.frag_id); glAttachShader(v.id,v.vert_id); // bind attributes before linking for (int i=0;i<attribute_pair_count;i++) { glBindAttribLocation(v.id, attribute_pairs[i].index, attribute_pairs[i].name ); } //if feedback exists, set it up if (feedback_count) { Vector<const char*> feedback; for(int i=0;i<feedback_count;i++) { if (feedbacks[i].conditional==-1 || (1<<feedbacks[i].conditional)&conditional_version.version) { //conditional for this feedback is enabled print_line("tf varying: "+itos(feedback.size())+" "+String(feedbacks[i].name)); feedback.push_back(feedbacks[i].name); } } if (feedback.size()) { glTransformFeedbackVaryings(v.id,feedback.size(),feedback.ptr(),GL_INTERLEAVED_ATTRIBS ); } } glLinkProgram(v.id); glGetProgramiv(v.id, GL_LINK_STATUS, &status); if (status==GL_FALSE) { // error linking GLsizei iloglen; glGetProgramiv(v.id,GL_INFO_LOG_LENGTH,&iloglen); if (iloglen<0) { glDeleteShader(v.frag_id); glDeleteShader(v.vert_id); glDeleteProgram( v.id ); v.id=0; ERR_FAIL_COND_V(iloglen<=0, NULL); } if (iloglen==0) { iloglen = 4096; //buggy driver (Adreno 220+....) } char *ilogmem = (char*)Memory::alloc_static(iloglen+1); ilogmem[iloglen]=0; glGetProgramInfoLog(v.id, iloglen, &iloglen, ilogmem); String err_string=get_shader_name()+": Program LINK FAILED:\n"; err_string+=ilogmem; _display_error_with_code(err_string,strings); ERR_PRINT(err_string.ascii().get_data()); Memory::free_static(ilogmem); glDeleteShader(v.frag_id); glDeleteShader(v.vert_id); glDeleteProgram( v.id ); v.id=0; ERR_FAIL_V(NULL); } /* UNIFORMS */ glUseProgram(v.id); //print_line("uniforms: "); for(int j=0;j<uniform_count;j++) { v.uniform_location[j]=glGetUniformLocation(v.id,uniform_names[j]); //print_line("uniform "+String(uniform_names[j])+" location "+itos(v.uniform_location[j])); } // set texture uniforms for (int i=0;i<texunit_pair_count;i++) { GLint loc = glGetUniformLocation(v.id,texunit_pairs[i].name); if (loc>=0) { if (texunit_pairs[i].index<0) { glUniform1i(loc,max_image_units+texunit_pairs[i].index); //negative, goes down } else { glUniform1i(loc,texunit_pairs[i].index); } } } // assign uniform block bind points for (int i=0;i<ubo_count;i++) { GLint loc = glGetUniformBlockIndex(v.id,ubo_pairs[i].name); if (loc>=0) glUniformBlockBinding(v.id,loc,ubo_pairs[i].index); } if ( cc ) { v.texture_uniform_locations.resize(cc->texture_uniforms.size()); for(int i=0;i<cc->texture_uniforms.size();i++) { v.texture_uniform_locations[i]=glGetUniformLocation(v.id,String(cc->texture_uniforms[i]).ascii().get_data()); glUniform1i(v.texture_uniform_locations[i],i+base_material_tex_index); } } glUseProgram(0); v.ok=true; return &v; } GLint ShaderGLES3::get_uniform_location(const String& p_name) const { ERR_FAIL_COND_V(!version,-1); return glGetUniformLocation(version->id,p_name.ascii().get_data()); } void ShaderGLES3::setup(const char** p_conditional_defines, int p_conditional_count,const char** p_uniform_names,int p_uniform_count, const AttributePair* p_attribute_pairs, int p_attribute_count, const TexUnitPair *p_texunit_pairs, int p_texunit_pair_count, const UBOPair *p_ubo_pairs, int p_ubo_pair_count, const Feedback* p_feedback, int p_feedback_count,const char*p_vertex_code, const char *p_fragment_code,int p_vertex_code_start,int p_fragment_code_start) { ERR_FAIL_COND(version); conditional_version.key=0; new_conditional_version.key=0; uniform_count=p_uniform_count; conditional_count=p_conditional_count; conditional_defines=p_conditional_defines; uniform_names=p_uniform_names; vertex_code=p_vertex_code; fragment_code=p_fragment_code; texunit_pairs=p_texunit_pairs; texunit_pair_count=p_texunit_pair_count; vertex_code_start=p_vertex_code_start; fragment_code_start=p_fragment_code_start; attribute_pairs=p_attribute_pairs; attribute_pair_count=p_attribute_count; ubo_pairs=p_ubo_pairs; ubo_count=p_ubo_pair_count; feedbacks=p_feedback; feedback_count=p_feedback_count; //split vertex and shader code (thank you, retarded shader compiler programmers from you know what company). { String globals_tag="\nVERTEX_SHADER_GLOBALS"; String material_tag="\nMATERIAL_UNIFORMS"; String code_tag="\nVERTEX_SHADER_CODE"; String code = vertex_code; int cpos = code.find(globals_tag); if (cpos==-1) { vertex_code0=code.ascii(); } else { vertex_code0=code.substr(0,cpos).ascii(); code = code.substr(cpos+globals_tag.length(),code.length()); cpos = code.find(material_tag); if (cpos==-1) { vertex_code1=code.ascii(); } else { vertex_code1=code.substr(0,cpos).ascii(); String code2 = code.substr(cpos+material_tag.length(),code.length()); cpos = code2.find(code_tag); if (cpos==-1) { vertex_code2=code2.ascii(); } else { vertex_code2=code2.substr(0,cpos).ascii(); vertex_code3 = code2.substr(cpos+code_tag.length(),code2.length()).ascii(); } } } } { String globals_tag="\nFRAGMENT_SHADER_GLOBALS"; String material_tag="\nMATERIAL_UNIFORMS"; String code_tag="\nFRAGMENT_SHADER_CODE"; String light_code_tag="\nLIGHT_SHADER_CODE"; String code = fragment_code; int cpos = code.find(globals_tag); if (cpos==-1) { fragment_code0=code.ascii(); } else { fragment_code0=code.substr(0,cpos).ascii(); //print_line("CODE0:\n"+String(fragment_code0.get_data())); code = code.substr(cpos+globals_tag.length(),code.length()); cpos = code.find(material_tag); if (cpos==-1) { fragment_code1=code.ascii(); } else { fragment_code1=code.substr(0,cpos).ascii(); //print_line("CODE1:\n"+String(fragment_code1.get_data())); String code2 = code.substr(cpos+material_tag.length(),code.length()); cpos = code2.find(code_tag); if (cpos==-1) { fragment_code2=code2.ascii(); } else { fragment_code2=code2.substr(0,cpos).ascii(); //print_line("CODE2:\n"+String(fragment_code2.get_data())); String code3 = code2.substr(cpos+code_tag.length(),code2.length()); cpos = code3.find(light_code_tag); if (cpos==-1) { fragment_code3=code3.ascii(); } else { fragment_code3=code3.substr(0,cpos).ascii(); //print_line("CODE3:\n"+String(fragment_code3.get_data())); fragment_code4 = code3.substr(cpos+light_code_tag.length(),code3.length()).ascii(); //print_line("CODE4:\n"+String(fragment_code4.get_data())); } } } } } glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS,&max_image_units); } void ShaderGLES3::finish() { const VersionKey *V=NULL; while((V=version_map.next(V))) { Version &v=version_map[*V]; glDeleteShader( v.vert_id ); glDeleteShader( v.frag_id ); glDeleteProgram( v.id ); memdelete_arr( v.uniform_location ); } } void ShaderGLES3::clear_caches() { const VersionKey *V=NULL; while((V=version_map.next(V))) { Version &v=version_map[*V]; glDeleteShader( v.vert_id ); glDeleteShader( v.frag_id ); glDeleteProgram( v.id ); memdelete_arr( v.uniform_location ); } version_map.clear(); custom_code_map.clear(); version=NULL; last_custom_code=1; uniforms_dirty = true; } uint32_t ShaderGLES3::create_custom_shader() { custom_code_map[last_custom_code]=CustomCode(); custom_code_map[last_custom_code].version=1; return last_custom_code++; } void ShaderGLES3::set_custom_shader_code(uint32_t p_code_id, const String& p_vertex, const String& p_vertex_globals, const String& p_fragment, const String& p_light, const String& p_fragment_globals, const String &p_uniforms, const Vector<StringName> &p_texture_uniforms, const Vector<CharString> &p_custom_defines) { ERR_FAIL_COND(!custom_code_map.has(p_code_id)); CustomCode *cc=&custom_code_map[p_code_id]; cc->vertex=p_vertex; cc->vertex_globals=p_vertex_globals; cc->fragment=p_fragment; cc->fragment_globals=p_fragment_globals; cc->light=p_light; cc->texture_uniforms=p_texture_uniforms; cc->uniforms=p_uniforms; cc->custom_defines=p_custom_defines; cc->version++; } void ShaderGLES3::set_custom_shader(uint32_t p_code_id) { new_conditional_version.code_version=p_code_id; } void ShaderGLES3::free_custom_shader(uint32_t p_code_id) { /* if (! custom_code_map.has( p_code_id )) { print_line("no code id "+itos(p_code_id)); } else { print_line("freed code id "+itos(p_code_id)); }*/ ERR_FAIL_COND(! custom_code_map.has( p_code_id )); if (conditional_version.code_version==p_code_id) conditional_version.code_version=0; //bye custom_code_map.erase(p_code_id); } void ShaderGLES3::set_base_material_tex_index(int p_idx) { base_material_tex_index=p_idx; } ShaderGLES3::ShaderGLES3() { version=NULL; last_custom_code=1; uniforms_dirty = true; base_material_tex_index=0; } ShaderGLES3::~ShaderGLES3() { finish(); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
modules/stb_vorbis/audio_stream_ogg_vorbis.cpp
236
#include "audio_stream_ogg_vorbis.h" #include "thirdparty/stb_vorbis/stb_vorbis.c" #include "os/file_access.h" void AudioStreamPlaybackOGGVorbis::_mix_internal(AudioFrame* p_buffer,int p_frames) { ERR_FAIL_COND(!active); int todo=p_frames; while(todo) { int mixed = stb_vorbis_get_samples_float_interleaved(ogg_stream,2,(float*)p_buffer,todo*2); todo-=mixed; if (todo) { //end of file! if (false) { //loop seek_pos(0); loops++; } else { for(int i=mixed;i<p_frames;i++) { p_buffer[i]=AudioFrame(0,0); } active=false; } } } } float AudioStreamPlaybackOGGVorbis::get_stream_sampling_rate() { return vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::start(float p_from_pos) { seek_pos(p_from_pos); active=true; loops=0; _begin_resample(); } void AudioStreamPlaybackOGGVorbis::stop() { active=false; } bool AudioStreamPlaybackOGGVorbis::is_playing() const { return active; } int AudioStreamPlaybackOGGVorbis::get_loop_count() const { return loops; } float AudioStreamPlaybackOGGVorbis::get_pos() const { return float(frames_mixed)/vorbis_stream->sample_rate; } void AudioStreamPlaybackOGGVorbis::seek_pos(float p_time) { if (!active) return; stb_vorbis_seek(ogg_stream, uint32_t(p_time*vorbis_stream->sample_rate)); } float AudioStreamPlaybackOGGVorbis::get_length() const { return vorbis_stream->length; } AudioStreamPlaybackOGGVorbis::~AudioStreamPlaybackOGGVorbis() { if (ogg_alloc.alloc_buffer) { AudioServer::get_singleton()->audio_data_free(ogg_alloc.alloc_buffer); stb_vorbis_close(ogg_stream); } } Ref<AudioStreamPlayback> AudioStreamOGGVorbis::instance_playback() { Ref<AudioStreamPlaybackOGGVorbis> ovs; printf("instance at %p, data %p\n",this,data); ERR_FAIL_COND_V(data==NULL,ovs); ovs.instance(); ovs->vorbis_stream=Ref<AudioStreamOGGVorbis>(this); ovs->ogg_alloc.alloc_buffer=(char*)AudioServer::get_singleton()->audio_data_alloc(decode_mem_size); ovs->ogg_alloc.alloc_buffer_length_in_bytes=decode_mem_size; ovs->frames_mixed=0; ovs->active=false; ovs->loops=0; int error ; ovs->ogg_stream = stb_vorbis_open_memory( (const unsigned char*)data, data_len, &error, &ovs->ogg_alloc ); if (!ovs->ogg_stream) { AudioServer::get_singleton()->audio_data_free(ovs->ogg_alloc.alloc_buffer); ovs->ogg_alloc.alloc_buffer=NULL; ERR_FAIL_COND_V(!ovs->ogg_stream,Ref<AudioStreamPlaybackOGGVorbis>()); } return ovs; } String AudioStreamOGGVorbis::get_stream_name() const { return "";//return stream_name; } Error AudioStreamOGGVorbis::setup(const uint8_t *p_data,uint32_t p_data_len) { #define MAX_TEST_MEM (1<<20) uint32_t alloc_try=1024; PoolVector<char> alloc_mem; PoolVector<char>::Write w; stb_vorbis * ogg_stream=NULL; stb_vorbis_alloc ogg_alloc; while(alloc_try<MAX_TEST_MEM) { alloc_mem.resize(alloc_try); w = alloc_mem.write(); ogg_alloc.alloc_buffer=w.ptr(); ogg_alloc.alloc_buffer_length_in_bytes=alloc_try; int error; ogg_stream = stb_vorbis_open_memory( (const unsigned char*)p_data, p_data_len, &error, &ogg_alloc ); if (!ogg_stream && error==VORBIS_outofmem) { w = PoolVector<char>::Write(); alloc_try*=2; } else { break; } } ERR_FAIL_COND_V(alloc_try==MAX_TEST_MEM,ERR_OUT_OF_MEMORY); ERR_FAIL_COND_V(ogg_stream==NULL,ERR_FILE_CORRUPT); stb_vorbis_info info = stb_vorbis_get_info(ogg_stream); channels = info.channels; sample_rate = info.sample_rate; decode_mem_size = alloc_try; //does this work? (it's less mem..) //decode_mem_size = ogg_alloc.alloc_buffer_length_in_bytes + info.setup_memory_required + info.temp_memory_required + info.max_frame_size; //print_line("succeded "+itos(ogg_alloc.alloc_buffer_length_in_bytes)+" setup "+itos(info.setup_memory_required)+" setup temp "+itos(info.setup_temp_memory_required)+" temp "+itos(info.temp_memory_required)+" maxframe"+itos(info.max_frame_size)); length=stb_vorbis_stream_length_in_seconds(ogg_stream); stb_vorbis_close(ogg_stream); data = AudioServer::get_singleton()->audio_data_alloc(p_data_len,p_data); data_len=p_data_len; printf("create at %p, data %p\n",this,data); return OK; } AudioStreamOGGVorbis::AudioStreamOGGVorbis() { data=NULL; length=0; sample_rate=1; channels=1; decode_mem_size=0; } RES ResourceFormatLoaderAudioStreamOGGVorbis::load(const String &p_path, const String& p_original_path, Error *r_error) { if (r_error) *r_error=OK; FileAccess *f = FileAccess::open(p_path,FileAccess::READ); if (!f) { *r_error=ERR_CANT_OPEN; ERR_FAIL_COND_V(!f,RES()); } size_t len = f->get_len(); PoolVector<uint8_t> data; data.resize(len); PoolVector<uint8_t>::Write w = data.write(); f->get_buffer(w.ptr(),len); memdelete(f); Ref<AudioStreamOGGVorbis> ogg_stream; ogg_stream.instance(); Error err = ogg_stream->setup(w.ptr(),len); if (err!=OK) { *r_error=err; ogg_stream.unref(); ERR_FAIL_V(RES()); } return ogg_stream; } void ResourceFormatLoaderAudioStreamOGGVorbis::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("ogg"); } String ResourceFormatLoaderAudioStreamOGGVorbis::get_resource_type(const String &p_path) const { if (p_path.get_extension().to_lower()=="ogg") return "AudioStreamOGGVorbis"; return ""; } bool ResourceFormatLoaderAudioStreamOGGVorbis::handles_type(const String& p_type) const { return (p_type=="AudioStream" || p_type=="AudioStreamOGG" || p_type=="AudioStreamOGGVorbis"); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
scene/3d/reflection_probe.cpp
268
#include "reflection_probe.h" void ReflectionProbe::set_intensity(float p_intensity) { intensity=p_intensity; VS::get_singleton()->reflection_probe_set_intensity(probe,p_intensity); } float ReflectionProbe::get_intensity() const{ return intensity; } void ReflectionProbe::set_interior_ambient(Color p_ambient) { interior_ambient=p_ambient; VS::get_singleton()->reflection_probe_set_interior_ambient(probe,p_ambient); } void ReflectionProbe::set_interior_ambient_energy(float p_energy) { interior_ambient_energy=p_energy; VS::get_singleton()->reflection_probe_set_interior_ambient_energy(probe,p_energy); } float ReflectionProbe::get_interior_ambient_energy() const{ return interior_ambient_energy; } Color ReflectionProbe::get_interior_ambient() const{ return interior_ambient; } void ReflectionProbe::set_interior_ambient_probe_contribution(float p_contribution) { interior_ambient_probe_contribution=p_contribution; VS::get_singleton()->reflection_probe_set_interior_ambient_probe_contribution(probe,p_contribution); } float ReflectionProbe::get_interior_ambient_probe_contribution() const{ return interior_ambient_probe_contribution; } void ReflectionProbe::set_max_distance(float p_distance){ max_distance=p_distance; VS::get_singleton()->reflection_probe_set_max_distance(probe,p_distance); } float ReflectionProbe::get_max_distance() const{ return max_distance; } void ReflectionProbe::set_extents(const Vector3& p_extents){ extents=p_extents; for(int i=0;i<3;i++) { if (extents[i]<0.01) { extents[i]=0.01; } if (extents[i]-0.01<ABS(origin_offset[i])) { origin_offset[i]=SGN(origin_offset[i])*(extents[i]-0.01); _change_notify("origin_offset"); } } VS::get_singleton()->reflection_probe_set_extents(probe,extents); VS::get_singleton()->reflection_probe_set_origin_offset(probe,origin_offset); _change_notify("extents"); update_gizmo(); } Vector3 ReflectionProbe::get_extents() const{ return extents; } void ReflectionProbe::set_origin_offset(const Vector3& p_extents){ origin_offset=p_extents; for(int i=0;i<3;i++) { if (extents[i]-0.01<ABS(origin_offset[i])) { origin_offset[i]=SGN(origin_offset[i])*(extents[i]-0.01); } } VS::get_singleton()->reflection_probe_set_extents(probe,extents); VS::get_singleton()->reflection_probe_set_origin_offset(probe,origin_offset); _change_notify("origin_offset"); update_gizmo(); } Vector3 ReflectionProbe::get_origin_offset() const{ return origin_offset; } void ReflectionProbe::set_enable_box_projection(bool p_enable){ box_projection=p_enable; VS::get_singleton()->reflection_probe_set_enable_box_projection(probe,p_enable); } bool ReflectionProbe::is_box_projection_enabled() const{ return box_projection; } void ReflectionProbe::set_as_interior(bool p_enable) { interior=p_enable; VS::get_singleton()->reflection_probe_set_as_interior(probe,interior); _change_notify(); } bool ReflectionProbe::is_set_as_interior() const { return interior; } void ReflectionProbe::set_enable_shadows(bool p_enable) { enable_shadows=p_enable; VS::get_singleton()->reflection_probe_set_enable_shadows(probe,p_enable); } bool ReflectionProbe::are_shadows_enabled() const { return enable_shadows; } void ReflectionProbe::set_cull_mask(uint32_t p_layers) { cull_mask=p_layers; VS::get_singleton()->reflection_probe_set_enable_shadows(probe,p_layers); } uint32_t ReflectionProbe::get_cull_mask() const { return cull_mask; } void ReflectionProbe::set_update_mode(UpdateMode p_mode) { update_mode=p_mode; VS::get_singleton()->reflection_probe_set_update_mode(probe,VS::ReflectionProbeUpdateMode(p_mode)); } ReflectionProbe::UpdateMode ReflectionProbe::get_update_mode() const { return update_mode; } Rect3 ReflectionProbe::get_aabb() const { Rect3 aabb; aabb.pos=-origin_offset; aabb.size=origin_offset+extents; return aabb; } PoolVector<Face3> ReflectionProbe::get_faces(uint32_t p_usage_flags) const { return PoolVector<Face3>(); } void ReflectionProbe::_validate_property(PropertyInfo& property) const { if (property.name=="interior/ambient_color" || property.name=="interior/ambient_energy" || property.name=="interior/ambient_contrib") { if (!interior) { property.usage=PROPERTY_USAGE_NOEDITOR; } } } void ReflectionProbe::_bind_methods() { ClassDB::bind_method(_MD("set_intensity","intensity"),&ReflectionProbe::set_intensity); ClassDB::bind_method(_MD("get_intensity"),&ReflectionProbe::get_intensity); ClassDB::bind_method(_MD("set_interior_ambient","ambient"),&ReflectionProbe::set_interior_ambient); ClassDB::bind_method(_MD("get_interior_ambient"),&ReflectionProbe::get_interior_ambient); ClassDB::bind_method(_MD("set_interior_ambient_energy","ambient_energy"),&ReflectionProbe::set_interior_ambient_energy); ClassDB::bind_method(_MD("get_interior_ambient_energy"),&ReflectionProbe::get_interior_ambient_energy); ClassDB::bind_method(_MD("set_interior_ambient_probe_contribution","ambient_probe_contribution"),&ReflectionProbe::set_interior_ambient_probe_contribution); ClassDB::bind_method(_MD("get_interior_ambient_probe_contribution"),&ReflectionProbe::get_interior_ambient_probe_contribution); ClassDB::bind_method(_MD("set_max_distance","max_distance"),&ReflectionProbe::set_max_distance); ClassDB::bind_method(_MD("get_max_distance"),&ReflectionProbe::get_max_distance); ClassDB::bind_method(_MD("set_extents","extents"),&ReflectionProbe::set_extents); ClassDB::bind_method(_MD("get_extents"),&ReflectionProbe::get_extents); ClassDB::bind_method(_MD("set_origin_offset","origin_offset"),&ReflectionProbe::set_origin_offset); ClassDB::bind_method(_MD("get_origin_offset"),&ReflectionProbe::get_origin_offset); ClassDB::bind_method(_MD("set_as_interior","enable"),&ReflectionProbe::set_as_interior); ClassDB::bind_method(_MD("is_set_as_interior"),&ReflectionProbe::is_set_as_interior); ClassDB::bind_method(_MD("set_enable_box_projection","enable"),&ReflectionProbe::set_enable_box_projection); ClassDB::bind_method(_MD("is_box_projection_enabled"),&ReflectionProbe::is_box_projection_enabled); ClassDB::bind_method(_MD("set_enable_shadows","enable"),&ReflectionProbe::set_enable_shadows); ClassDB::bind_method(_MD("are_shadows_enabled"),&ReflectionProbe::are_shadows_enabled); ClassDB::bind_method(_MD("set_cull_mask","layers"),&ReflectionProbe::set_cull_mask); ClassDB::bind_method(_MD("get_cull_mask"),&ReflectionProbe::get_cull_mask); ClassDB::bind_method(_MD("set_update_mode","mode"),&ReflectionProbe::set_update_mode); ClassDB::bind_method(_MD("get_update_mode"),&ReflectionProbe::get_update_mode); ADD_PROPERTY( PropertyInfo(Variant::INT,"update_mode",PROPERTY_HINT_ENUM,"Once,Always"),_SCS("set_update_mode"),_SCS("get_update_mode")); ADD_PROPERTY( PropertyInfo(Variant::REAL,"intensity",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_intensity"),_SCS("get_intensity")); ADD_PROPERTY( PropertyInfo(Variant::REAL,"max_distance",PROPERTY_HINT_RANGE,"0,16384,0.1"),_SCS("set_max_distance"),_SCS("get_max_distance")); ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"extents"),_SCS("set_extents"),_SCS("get_extents")); ADD_PROPERTY( PropertyInfo(Variant::VECTOR2,"origin_offset"),_SCS("set_origin_offset"),_SCS("get_origin_offset")); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"box_projection"),_SCS("set_enable_box_projection"),_SCS("is_box_projection_enabled")); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"enable_shadows"),_SCS("set_enable_shadows"),_SCS("are_shadows_enabled")); ADD_PROPERTY( PropertyInfo(Variant::INT,"cull_mask",PROPERTY_HINT_LAYERS_3D_RENDER),_SCS("set_cull_mask"),_SCS("get_cull_mask")); ADD_GROUP("Interior","interior_"); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"interior_enable"),_SCS("set_as_interior"),_SCS("is_set_as_interior")); ADD_PROPERTY( PropertyInfo(Variant::COLOR,"interior_ambient_color",PROPERTY_HINT_COLOR_NO_ALPHA),_SCS("set_interior_ambient"),_SCS("get_interior_ambient")); ADD_PROPERTY( PropertyInfo(Variant::REAL,"interior_ambient_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_interior_ambient_energy"),_SCS("get_interior_ambient_energy")); ADD_PROPERTY( PropertyInfo(Variant::REAL,"interior_ambient_contrib",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_interior_ambient_probe_contribution"),_SCS("get_interior_ambient_probe_contribution")); BIND_CONSTANT( UPDATE_ONCE ); BIND_CONSTANT( UPDATE_ALWAYS ); } ReflectionProbe::ReflectionProbe() { intensity=1.0; interior_ambient=Color(0,0,0); interior_ambient_probe_contribution=0; interior_ambient_energy=1.0; max_distance=0; extents=Vector3(1,1,1); origin_offset=Vector3(0,0,0); box_projection=false; interior=false; enable_shadows=false; cull_mask=(1<<20)-1; update_mode=UPDATE_ONCE; probe=VisualServer::get_singleton()->reflection_probe_create(); VS::get_singleton()->instance_set_base(get_instance(),probe); } ReflectionProbe::~ReflectionProbe() { VS::get_singleton()->free(probe); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
drivers/gles3/shader_compiler_gles3.cpp
738
#include "shader_compiler_gles3.h" #include "os/os.h" #define SL ShaderLanguage static String _mktab(int p_level) { String tb; for(int i=0;i<p_level;i++) { tb+="\t"; } return tb; } static String _typestr(SL::DataType p_type) { return ShaderLanguage::get_datatype_name(p_type); } static int _get_datatype_size(SL::DataType p_type) { switch(p_type) { case SL::TYPE_VOID: return 0; case SL::TYPE_BOOL: return 4; case SL::TYPE_BVEC2: return 8; case SL::TYPE_BVEC3: return 16; case SL::TYPE_BVEC4: return 16; case SL::TYPE_INT: return 4; case SL::TYPE_IVEC2: return 8; case SL::TYPE_IVEC3: return 16; case SL::TYPE_IVEC4: return 16; case SL::TYPE_UINT: return 4; case SL::TYPE_UVEC2: return 8; case SL::TYPE_UVEC3: return 16; case SL::TYPE_UVEC4: return 16; case SL::TYPE_FLOAT: return 4; case SL::TYPE_VEC2: return 8; case SL::TYPE_VEC3: return 16; case SL::TYPE_VEC4: return 16; case SL::TYPE_MAT2: return 16; case SL::TYPE_MAT3: return 48; case SL::TYPE_MAT4: return 64; case SL::TYPE_SAMPLER2D: return 16; case SL::TYPE_ISAMPLER2D: return 16; case SL::TYPE_USAMPLER2D: return 16; case SL::TYPE_SAMPLERCUBE: return 16; } ERR_FAIL_V(0); } static String _prestr(SL::DataPrecision p_pres) { switch(p_pres) { case SL::PRECISION_LOWP: return "lowp "; case SL::PRECISION_MEDIUMP: return "mediump "; case SL::PRECISION_HIGHP: return "highp "; case SL::PRECISION_DEFAULT: return ""; } return ""; } static String _opstr(SL::Operator p_op) { return SL::get_operator_text(p_op); } static String _mkid(const String& p_id) { return "m_"+p_id; } static String f2sp0(float p_float) { if (int(p_float)==p_float) return itos(p_float)+".0"; else return rtoss(p_float); } static String get_constant_text(SL::DataType p_type, const Vector<SL::ConstantNode::Value>& p_values) { switch(p_type) { case SL::TYPE_BOOL: return p_values[0].boolean?"true":"false"; case SL::TYPE_BVEC2: case SL::TYPE_BVEC3: case SL::TYPE_BVEC4: { String text="bvec"+itos(p_type-SL::TYPE_BOOL+1)+"("; for(int i=0;i<p_values.size();i++) { if (i>0) text+=","; text+=p_values[i].boolean?"true":"false"; } text+=")"; return text; } case SL::TYPE_INT: return itos(p_values[0].sint); case SL::TYPE_IVEC2: case SL::TYPE_IVEC3: case SL::TYPE_IVEC4: { String text="ivec"+itos(p_type-SL::TYPE_INT+1)+"("; for(int i=0;i<p_values.size();i++) { if (i>0) text+=","; text+=itos(p_values[i].sint); } text+=")"; return text; } break; case SL::TYPE_UINT: return itos(p_values[0].uint)+"u"; case SL::TYPE_UVEC2: case SL::TYPE_UVEC3: case SL::TYPE_UVEC4: { String text="uvec"+itos(p_type-SL::TYPE_UINT+1)+"("; for(int i=0;i<p_values.size();i++) { if (i>0) text+=","; text+=itos(p_values[i].uint)+"u"; } text+=")"; return text; } break; case SL::TYPE_FLOAT: return f2sp0(p_values[0].real)+"f"; case SL::TYPE_VEC2: case SL::TYPE_VEC3: case SL::TYPE_VEC4: { String text="vec"+itos(p_type-SL::TYPE_FLOAT+1)+"("; for(int i=0;i<p_values.size();i++) { if (i>0) text+=","; text+=f2sp0(p_values[i].real); } text+=")"; return text; } break; default: ERR_FAIL_V(String()); } } void ShaderCompilerGLES3::_dump_function_deps(SL::ShaderNode* p_node, const StringName& p_for_func, const Map<StringName,String>& p_func_code, String& r_to_add, Set<StringName> &added) { int fidx=-1; for(int i=0;i<p_node->functions.size();i++) { if (p_node->functions[i].name==p_for_func) { fidx=i; break; } } ERR_FAIL_COND(fidx==-1); for (Set<StringName>::Element *E=p_node->functions[fidx].uses_function.front();E;E=E->next()) { if (added.has(E->get())) { continue; //was added already } _dump_function_deps(p_node,E->get(),p_func_code,r_to_add,added); SL::FunctionNode *fnode=NULL; for(int i=0;i<p_node->functions.size();i++) { if (p_node->functions[i].name==E->get()) { fnode=p_node->functions[i].function; break; } } ERR_FAIL_COND(!fnode); r_to_add+="\n"; String header; header=_typestr(fnode->return_type)+" "+_mkid(fnode->name)+"("; for(int i=0;i<fnode->arguments.size();i++) { if (i>0) header+=", "; header+=_prestr(fnode->arguments[i].precision)+_typestr(fnode->arguments[i].type)+" "+_mkid(fnode->arguments[i].name); } header+=")\n"; r_to_add+=header; r_to_add+=p_func_code[E->get()]; added.insert(E->get()); } } String ShaderCompilerGLES3::_dump_node_code(SL::Node *p_node, int p_level, GeneratedCode& r_gen_code, IdentifierActions &p_actions, const DefaultIdentifierActions &p_default_actions) { String code; switch(p_node->type) { case SL::Node::TYPE_SHADER: { SL::ShaderNode *pnode=(SL::ShaderNode*)p_node; for(int i=0;i<pnode->render_modes.size();i++) { if (p_default_actions.render_mode_defines.has(pnode->render_modes[i]) && !used_rmode_defines.has(pnode->render_modes[i])) { r_gen_code.defines.push_back(p_default_actions.render_mode_defines[pnode->render_modes[i]].utf8()); used_rmode_defines.insert(pnode->render_modes[i]); } if (p_actions.render_mode_flags.has(pnode->render_modes[i])) { *p_actions.render_mode_flags[pnode->render_modes[i]]=true; } if (p_actions.render_mode_values.has(pnode->render_modes[i])) { Pair<int*,int> &p = p_actions.render_mode_values[pnode->render_modes[i]]; *p.first=p.second; } } int max_texture_uniforms=0; int max_uniforms=0; for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) { if (SL::is_sampler_type(E->get().type)) max_texture_uniforms++; else max_uniforms++; } r_gen_code.texture_uniforms.resize(max_texture_uniforms); r_gen_code.texture_hints.resize(max_texture_uniforms); Vector<int> uniform_sizes; Vector<int> uniform_alignments; Vector<StringName> uniform_defines; uniform_sizes.resize(max_uniforms); uniform_alignments.resize(max_uniforms); uniform_defines.resize(max_uniforms); for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) { String ucode; if (SL::is_sampler_type(E->get().type)) { ucode="uniform "; } ucode+=_prestr(E->get().precission); ucode+=_typestr(E->get().type); ucode+=" "+_mkid(E->key()); ucode+=";\n"; if (SL::is_sampler_type(E->get().type)) { r_gen_code.vertex_global+=ucode; r_gen_code.fragment_global+=ucode; r_gen_code.texture_uniforms[E->get().texture_order]=_mkid(E->key()); r_gen_code.texture_hints[E->get().texture_order]=E->get().hint; } else { if (r_gen_code.uniforms.empty()) { r_gen_code.defines.push_back(String("#define USE_MATERIAL\n").ascii()); } uniform_defines[E->get().order]=ucode; uniform_sizes[E->get().order]=_get_datatype_size(E->get().type); uniform_alignments[E->get().order]=MIN(16,_get_datatype_size(E->get().type)); } p_actions.uniforms->insert(E->key(),E->get()); } for(int i=0;i<max_uniforms;i++) { r_gen_code.uniforms+=uniform_defines[i]; } // add up for(int i=0;i<uniform_sizes.size();i++) { if (i>0) { int align = uniform_sizes[i-1] % uniform_alignments[i]; if (align!=0) { uniform_sizes[i-1]+=uniform_alignments[i]-align; } uniform_sizes[i]=uniform_sizes[i]+uniform_sizes[i-1]; } } //offset r_gen_code.uniform_offsets.resize(uniform_sizes.size()); for(int i=0;i<uniform_sizes.size();i++) { if (i>0) r_gen_code.uniform_offsets[i]=uniform_sizes[i-1]; else r_gen_code.uniform_offsets[i]=0; } /* for(Map<StringName,SL::ShaderNode::Uniform>::Element *E=pnode->uniforms.front();E;E=E->next()) { if (SL::is_sampler_type(E->get().type)) { continue; } print_line("u - "+String(E->key())+" offset: "+itos(r_gen_code.uniform_offsets[E->get().order])); } */ if (uniform_sizes.size()) { r_gen_code.uniform_total_size=uniform_sizes[ uniform_sizes.size() -1 ]; } else { r_gen_code.uniform_total_size=0; } for(Map<StringName,SL::ShaderNode::Varying>::Element *E=pnode->varyings.front();E;E=E->next()) { String vcode; vcode+=_prestr(E->get().precission); vcode+=_typestr(E->get().type); vcode+=" "+String(E->key()); vcode+=";\n"; r_gen_code.vertex_global+="out "+vcode; r_gen_code.fragment_global+="in "+vcode; } Map<StringName,String> function_code; //code for functions for(int i=0;i<pnode->functions.size();i++) { SL::FunctionNode *fnode=pnode->functions[i].function; function_code[fnode->name]=_dump_node_code(fnode->body,p_level+1,r_gen_code,p_actions,p_default_actions); } //place functions in actual code Set<StringName> added_vtx; Set<StringName> added_fragment; //share for light for(int i=0;i<pnode->functions.size();i++) { SL::FunctionNode *fnode=pnode->functions[i].function; current_func_name=fnode->name; if (fnode->name=="vertex") { _dump_function_deps(pnode,fnode->name,function_code,r_gen_code.vertex_global,added_vtx); r_gen_code.vertex=function_code["vertex"]; } if (fnode->name=="fragment") { _dump_function_deps(pnode,fnode->name,function_code,r_gen_code.fragment_global,added_fragment); r_gen_code.fragment=function_code["fragment"]; } if (fnode->name=="light") { _dump_function_deps(pnode,fnode->name,function_code,r_gen_code.fragment_global,added_fragment); r_gen_code.light=function_code["light"]; } } //code+=dump_node_code(pnode->body,p_level); } break; case SL::Node::TYPE_FUNCTION: { } break; case SL::Node::TYPE_BLOCK: { SL::BlockNode *bnode=(SL::BlockNode*)p_node; //variables code+=_mktab(p_level-1)+"{\n"; for(Map<StringName,SL::BlockNode::Variable>::Element *E=bnode->variables.front();E;E=E->next()) { code+=_mktab(p_level)+_prestr(E->get().precision)+_typestr(E->get().type)+" "+_mkid(E->key())+";\n"; } for(int i=0;i<bnode->statements.size();i++) { String scode = _dump_node_code(bnode->statements[i],p_level,r_gen_code,p_actions,p_default_actions); if (bnode->statements[i]->type==SL::Node::TYPE_CONTROL_FLOW || bnode->statements[i]->type==SL::Node::TYPE_CONTROL_FLOW) { code+=scode; //use directly } else { code+=_mktab(p_level)+scode+";\n"; } } code+=_mktab(p_level-1)+"}\n"; } break; case SL::Node::TYPE_VARIABLE: { SL::VariableNode *vnode=(SL::VariableNode*)p_node; if (p_default_actions.usage_defines.has(vnode->name) && !used_name_defines.has(vnode->name)) { String define = p_default_actions.usage_defines[vnode->name]; if (define.begins_with("@")) { define = p_default_actions.usage_defines[define.substr(1,define.length())]; } r_gen_code.defines.push_back(define.utf8()); used_name_defines.insert(vnode->name); } if (p_actions.usage_flag_pointers.has(vnode->name) && !used_flag_pointers.has(vnode->name)) { *p_actions.usage_flag_pointers[vnode->name]=true; used_flag_pointers.insert(vnode->name); } if (p_default_actions.renames.has(vnode->name)) code=p_default_actions.renames[vnode->name]; else code=_mkid(vnode->name); if (vnode->name==time_name) { if (current_func_name==vertex_name) { r_gen_code.uses_vertex_time=true; } if (current_func_name==fragment_name) { r_gen_code.uses_fragment_time=true; } } } break; case SL::Node::TYPE_CONSTANT: { SL::ConstantNode *cnode=(SL::ConstantNode*)p_node; return get_constant_text(cnode->datatype,cnode->values); } break; case SL::Node::TYPE_OPERATOR: { SL::OperatorNode *onode=(SL::OperatorNode*)p_node; switch(onode->op) { case SL::OP_ASSIGN: case SL::OP_ASSIGN_ADD: case SL::OP_ASSIGN_SUB: case SL::OP_ASSIGN_MUL: case SL::OP_ASSIGN_DIV: case SL::OP_ASSIGN_SHIFT_LEFT: case SL::OP_ASSIGN_SHIFT_RIGHT: case SL::OP_ASSIGN_MOD: case SL::OP_ASSIGN_BIT_AND: case SL::OP_ASSIGN_BIT_OR: case SL::OP_ASSIGN_BIT_XOR: code=_dump_node_code(onode->arguments[0],p_level,r_gen_code,p_actions,p_default_actions)+_opstr(onode->op)+_dump_node_code(onode->arguments[1],p_level,r_gen_code,p_actions,p_default_actions); break; case SL::OP_BIT_INVERT: case SL::OP_NEGATE: case SL::OP_NOT: case SL::OP_DECREMENT: case SL::OP_INCREMENT: code=_opstr(onode->op)+_dump_node_code(onode->arguments[0],p_level,r_gen_code,p_actions,p_default_actions); break; case SL::OP_POST_DECREMENT: case SL::OP_POST_INCREMENT: code=_dump_node_code(onode->arguments[0],p_level,r_gen_code,p_actions,p_default_actions)+_opstr(onode->op); break; case SL::OP_CALL: case SL::OP_CONSTRUCT: { ERR_FAIL_COND_V(onode->arguments[0]->type!=SL::Node::TYPE_VARIABLE,String()); SL::VariableNode *vnode=(SL::VariableNode*)onode->arguments[0]; if (onode->op==SL::OP_CONSTRUCT) { code+=String(vnode->name); } else { if (internal_functions.has(vnode->name)) { code+=vnode->name; } else if (p_default_actions.renames.has(vnode->name)) { code+=p_default_actions.renames[vnode->name]; } else { code+=_mkid(vnode->name); } } code+="("; for(int i=1;i<onode->arguments.size();i++) { if (i>1) code+=", "; code+=_dump_node_code(onode->arguments[i],p_level,r_gen_code,p_actions,p_default_actions); } code+=")"; } break; default: { code="("+_dump_node_code(onode->arguments[0],p_level,r_gen_code,p_actions,p_default_actions)+_opstr(onode->op)+_dump_node_code(onode->arguments[1],p_level,r_gen_code,p_actions,p_default_actions)+")"; break; } } } break; case SL::Node::TYPE_CONTROL_FLOW: { SL::ControlFlowNode *cfnode=(SL::ControlFlowNode*)p_node; if (cfnode->flow_op==SL::FLOW_OP_IF) { code+=_mktab(p_level)+"if ("+_dump_node_code(cfnode->expressions[0],p_level,r_gen_code,p_actions,p_default_actions)+")\n"; code+=_dump_node_code(cfnode->blocks[0],p_level+1,r_gen_code,p_actions,p_default_actions); if (cfnode->blocks.size()==2) { code+=_mktab(p_level)+"else\n"; code+=_dump_node_code(cfnode->blocks[1],p_level+1,r_gen_code,p_actions,p_default_actions); } } else if (cfnode->flow_op==SL::FLOW_OP_RETURN) { if (cfnode->blocks.size()) { code="return "+_dump_node_code(cfnode->blocks[0],p_level,r_gen_code,p_actions,p_default_actions); } else { code="return"; } } } break; case SL::Node::TYPE_MEMBER: { SL::MemberNode *mnode=(SL::MemberNode*)p_node; code=_dump_node_code(mnode->owner,p_level,r_gen_code,p_actions,p_default_actions)+"."+mnode->name; } break; } return code; } Error ShaderCompilerGLES3::compile(VS::ShaderMode p_mode, const String& p_code, IdentifierActions* p_actions, const String &p_path,GeneratedCode& r_gen_code) { Error err = parser.compile(p_code,ShaderTypes::get_singleton()->get_functions(p_mode),ShaderTypes::get_singleton()->get_modes(p_mode)); if (err!=OK) { #if 1 Vector<String> shader = p_code.split("\n"); for(int i=0;i<shader.size();i++) { print_line(itos(i)+" "+shader[i]); } #endif _err_print_error(NULL,p_path.utf8().get_data(),parser.get_error_line(),parser.get_error_text().utf8().get_data(),ERR_HANDLER_SHADER); return err; } r_gen_code.defines.clear(); r_gen_code.vertex=String(); r_gen_code.vertex_global=String(); r_gen_code.fragment=String(); r_gen_code.fragment_global=String(); r_gen_code.light=String(); r_gen_code.uses_fragment_time=false; r_gen_code.uses_vertex_time=false; used_name_defines.clear(); used_rmode_defines.clear(); _dump_node_code(parser.get_shader(),1,r_gen_code,*p_actions,actions[p_mode]); return OK; } ShaderCompilerGLES3::ShaderCompilerGLES3() { /** CANVAS ITEM SHADER **/ actions[VS::SHADER_CANVAS_ITEM].renames["SRC_VERTEX"]="vertex"; actions[VS::SHADER_CANVAS_ITEM].renames["VERTEX"]="outvec.xy"; actions[VS::SHADER_CANVAS_ITEM].renames["VERTEX_COLOR"]="vertex_color"; actions[VS::SHADER_CANVAS_ITEM].renames["UV"]="uv_interp"; actions[VS::SHADER_CANVAS_ITEM].renames["POINT_SIZE"]="gl_PointSize"; actions[VS::SHADER_CANVAS_ITEM].renames["WORLD_MATRIX"]="modelview_matrix"; actions[VS::SHADER_CANVAS_ITEM].renames["PROJECTION_MATRIX"]="projection_matrix"; actions[VS::SHADER_CANVAS_ITEM].renames["EXTRA_MATRIX"]=="extra_matrix"; actions[VS::SHADER_CANVAS_ITEM].renames["TIME"]="time"; actions[VS::SHADER_CANVAS_ITEM].renames["COLOR"]="color"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMAL"]="normal"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP"]="normal_map"; actions[VS::SHADER_CANVAS_ITEM].renames["NORMALMAP_DEPTH"]="normal_depth"; actions[VS::SHADER_CANVAS_ITEM].renames["UV"]="uv_interp"; actions[VS::SHADER_CANVAS_ITEM].renames["COLOR"]="color"; actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE"]="color_texture"; actions[VS::SHADER_CANVAS_ITEM].renames["TEXTURE_PIXEL_SIZE"]="color_texpixel_size"; actions[VS::SHADER_CANVAS_ITEM].renames["SCREEN_UV"]="screen_uv"; actions[VS::SHADER_CANVAS_ITEM].renames["SCREEN_TEXTURE"]="screen_texture"; actions[VS::SHADER_CANVAS_ITEM].renames["POINT_COORD"]="gl_PointCoord"; actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_VEC"]="light_vec"; actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_HEIGHT"]="light_height"; actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_COLOR"]="light_color"; actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_UV"]="light_uv"; //actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT_SHADOW_COLOR"]="light_shadow_color"; actions[VS::SHADER_CANVAS_ITEM].renames["LIGHT"]="light"; actions[VS::SHADER_CANVAS_ITEM].renames["SHADOW_COLOR"]="shadow_color"; actions[VS::SHADER_CANVAS_ITEM].usage_defines["COLOR"]="#define COLOR_USED\n"; actions[VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_TEXTURE"]="#define SCREEN_TEXTURE_USED\n"; actions[VS::SHADER_CANVAS_ITEM].usage_defines["SCREEN_UV"]="#define SCREEN_UV_USED\n"; actions[VS::SHADER_CANVAS_ITEM].usage_defines["NORMAL"]="#define NORMAL_USED\n"; actions[VS::SHADER_CANVAS_ITEM].usage_defines["NORMALMAP"]="#define NORMALMAP_USED\n"; actions[VS::SHADER_CANVAS_ITEM].usage_defines["SHADOW_COLOR"]="#define SHADOW_COLOR_USED\n"; actions[VS::SHADER_CANVAS_ITEM].render_mode_defines["skip_transform"]="#define SKIP_TRANSFORM_USED\n"; /** SPATIAL SHADER **/ actions[VS::SHADER_SPATIAL].renames["WORLD_MATRIX"]="world_transform"; actions[VS::SHADER_SPATIAL].renames["INV_CAMERA_MATRIX"]="camera_inverse_matrix"; actions[VS::SHADER_SPATIAL].renames["PROJECTION_MATRIX"]="projection_matrix"; actions[VS::SHADER_SPATIAL].renames["VERTEX"]="vertex.xyz"; actions[VS::SHADER_SPATIAL].renames["NORMAL"]="normal"; actions[VS::SHADER_SPATIAL].renames["TANGENT"]="tangent"; actions[VS::SHADER_SPATIAL].renames["BINORMAL"]="binormal"; actions[VS::SHADER_SPATIAL].renames["UV"]="uv_interp"; actions[VS::SHADER_SPATIAL].renames["UV2"]="uv2_interp"; actions[VS::SHADER_SPATIAL].renames["COLOR"]="color_interp"; actions[VS::SHADER_SPATIAL].renames["POINT_SIZE"]="gl_PointSize"; //actions[VS::SHADER_SPATIAL].renames["INSTANCE_ID"]=ShaderLanguage::TYPE_INT; //builtins actions[VS::SHADER_SPATIAL].renames["TIME"]="time"; //actions[VS::SHADER_SPATIAL].renames["VIEWPORT_SIZE"]=ShaderLanguage::TYPE_VEC2; actions[VS::SHADER_SPATIAL].renames["FRAGCOORD"]="gl_FragCoord"; actions[VS::SHADER_SPATIAL].renames["FRONT_FACING"]="gl_FrotFacing"; actions[VS::SHADER_SPATIAL].renames["NORMALMAP"]="normalmap"; actions[VS::SHADER_SPATIAL].renames["NORMALMAP_DEPTH"]="normaldepth"; actions[VS::SHADER_SPATIAL].renames["ALBEDO"]="albedo"; actions[VS::SHADER_SPATIAL].renames["ALPHA"]="alpha"; actions[VS::SHADER_SPATIAL].renames["SPECULAR"]="specular"; actions[VS::SHADER_SPATIAL].renames["ROUGHNESS"]="roughness"; actions[VS::SHADER_SPATIAL].renames["RIM"]="rim"; actions[VS::SHADER_SPATIAL].renames["RIM_TINT"]="rim_tint"; actions[VS::SHADER_SPATIAL].renames["CLEARCOAT"]="clearcoat"; actions[VS::SHADER_SPATIAL].renames["CLEARCOAT_GLOSS"]="clearcoat_gloss"; actions[VS::SHADER_SPATIAL].renames["ANISOTROPY"]="anisotropy"; actions[VS::SHADER_SPATIAL].renames["ANISOTROPY_FLOW"]="anisotropy_flow"; actions[VS::SHADER_SPATIAL].renames["SSS_SPREAD"]="sss_spread"; actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"]="sss_strength"; actions[VS::SHADER_SPATIAL].renames["AO"]="ao"; actions[VS::SHADER_SPATIAL].renames["EMISSION"]="emission"; actions[VS::SHADER_SPATIAL].renames["DISCARD"]="_discard"; //actions[VS::SHADER_SPATIAL].renames["SCREEN_UV"]=ShaderLanguage::TYPE_VEC2; actions[VS::SHADER_SPATIAL].renames["POINT_COORD"]="gl_PointCoord"; actions[VS::SHADER_SPATIAL].usage_defines["TANGENT"]="#define ENABLE_TANGENT_INTERP\n"; actions[VS::SHADER_SPATIAL].usage_defines["BINORMAL"]="@TANGENT"; actions[VS::SHADER_SPATIAL].usage_defines["RIM"]="#define LIGHT_USE_RIM\n"; actions[VS::SHADER_SPATIAL].usage_defines["RIM_TINT"]="@RIM"; actions[VS::SHADER_SPATIAL].usage_defines["CLEARCOAT"]="#define LIGHT_USE_CLEARCOAT\n"; actions[VS::SHADER_SPATIAL].usage_defines["CLEARCOAT_GLOSS"]="@CLEARCOAT"; actions[VS::SHADER_SPATIAL].usage_defines["ANISOTROPY"]="#define LIGHT_USE_ANISOTROPY\n"; actions[VS::SHADER_SPATIAL].usage_defines["ANISOTROPY_FLOW"]="@ANISOTROPY"; actions[VS::SHADER_SPATIAL].usage_defines["AO"]="#define ENABLE_AO\n"; actions[VS::SHADER_SPATIAL].usage_defines["UV"]="#define ENABLE_UV_INTERP\n"; actions[VS::SHADER_SPATIAL].usage_defines["UV2"]="#define ENABLE_UV2_INTERP\n"; actions[VS::SHADER_SPATIAL].usage_defines["NORMALMAP"]="#define ENABLE_NORMALMAP\n"; actions[VS::SHADER_SPATIAL].usage_defines["NORMALMAP_DEPTH"]="@NORMALMAP"; actions[VS::SHADER_SPATIAL].usage_defines["COLOR"]="#define ENABLE_COLOR_INTERP\n"; actions[VS::SHADER_SPATIAL].usage_defines["SSS_STRENGTH"]="#define ENABLE_SSS_MOTION\n"; actions[VS::SHADER_SPATIAL].renames["SSS_STRENGTH"]="sss_strength"; actions[VS::SHADER_SPATIAL].render_mode_defines["skip_transform"]="#define SKIP_TRANSFORM_USED\n"; /* PARTICLES SHADER */ actions[VS::SHADER_PARTICLES].renames["COLOR"]="color"; actions[VS::SHADER_PARTICLES].renames["VELOCITY"]="out_velocity_active.xyz"; actions[VS::SHADER_PARTICLES].renames["MASS"]="mass"; actions[VS::SHADER_PARTICLES].renames["ACTIVE"]="active"; actions[VS::SHADER_PARTICLES].renames["RESTART"]="restart"; actions[VS::SHADER_PARTICLES].renames["CUSTOM"]="out_custom"; actions[VS::SHADER_PARTICLES].renames["TRANSFORM"]="xform"; actions[VS::SHADER_PARTICLES].renames["TIME"]="time"; actions[VS::SHADER_PARTICLES].renames["LIFETIME"]="lifetime"; actions[VS::SHADER_PARTICLES].renames["DELTA"]="delta"; actions[VS::SHADER_PARTICLES].renames["SEED"]="seed"; actions[VS::SHADER_PARTICLES].renames["ORIGIN"]="origin"; actions[VS::SHADER_PARTICLES].renames["INDEX"]="index"; actions[VS::SHADER_SPATIAL].render_mode_defines["disable_force"]="#define DISABLE_FORCE\n"; actions[VS::SHADER_SPATIAL].render_mode_defines["disable_velocity"]="#define DISABLE_VELOCITY\n"; vertex_name="vertex"; fragment_name="fragment"; time_name="TIME"; List<String> func_list; ShaderLanguage::get_builtin_funcs(&func_list); for (List<String>::Element *E=func_list.front();E;E=E->next()) { internal_functions.insert(E->get()); } }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
tools/editor/editor_path.cpp
108
/*************************************************************************/ /* editor_path.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "editor_path.h" #include "editor_scale.h" #include "editor_node.h" void EditorPath::_add_children_to_popup(Object* p_obj,int p_depth) { if (p_depth>8) return; List<PropertyInfo> pinfo; p_obj->get_property_list(&pinfo); for (List<PropertyInfo>::Element *E=pinfo.front();E;E=E->next()) { if (!(E->get().usage&PROPERTY_USAGE_EDITOR)) continue; if (E->get().hint!=PROPERTY_HINT_RESOURCE_TYPE) continue; Variant value = p_obj->get(E->get().name); if (value.get_type()!=Variant::OBJECT) continue; Object *obj = value; if (!obj) continue; Ref<Texture> icon; if (has_icon(obj->get_class(),"EditorIcons")) icon=get_icon(obj->get_class(),"EditorIcons"); else icon=get_icon("Object","EditorIcons"); int index = popup->get_item_count(); popup->add_icon_item(icon,E->get().name.capitalize(),objects.size()); popup->set_item_h_offset(index,p_depth*10*EDSCALE); objects.push_back(obj->get_instance_ID()); _add_children_to_popup(obj,p_depth+1); } } void EditorPath::_gui_input(const InputEvent& p_event) { if (p_event.type==InputEvent::MOUSE_BUTTON && p_event.mouse_button.button_index==BUTTON_LEFT && p_event.mouse_button.pressed) { Object *obj = ObjectDB::get_instance(history->get_path_object( history->get_path_size()-1)); if (!obj) return; objects.clear(); popup->clear(); _add_children_to_popup(obj); popup->set_pos( get_global_pos() + Vector2(0,get_size().height)); popup->set_size( Size2(get_size().width,1)); popup->popup(); } } void EditorPath::_notification(int p_what) { switch(p_what) { case NOTIFICATION_MOUSE_ENTER: { mouse_over=true; update(); } break; case NOTIFICATION_MOUSE_EXIT: { mouse_over=false; update(); } break; case NOTIFICATION_DRAW: { RID ci=get_canvas_item(); Ref<Font> label_font = get_font("font","Label"); Size2i size = get_size(); Ref<Texture> sn = get_icon("SmallNext","EditorIcons"); Ref<StyleBox> sb = get_stylebox("pressed","Button"); int ofs=sb->get_margin(MARGIN_LEFT); if (mouse_over) { draw_style_box(sb,Rect2(Point2(),get_size())); } for(int i=0;i<history->get_path_size();i++) { Object *obj = ObjectDB::get_instance(history->get_path_object(i)); if (!obj) continue; String type = obj->get_class(); Ref<Texture> icon; if (has_icon(obj->get_class(),"EditorIcons")) icon=get_icon(obj->get_class(),"EditorIcons"); else icon=get_icon("Object","EditorIcons"); icon->draw(ci,Point2i(ofs,(size.height-icon->get_height())/2)); ofs+=icon->get_width(); if (i==history->get_path_size()-1) { //add name ofs+=4; int left = size.width - ofs; if (left<0) continue; String name; if (obj->cast_to<Resource>()) { Resource *r = obj->cast_to<Resource>(); if (r->get_path().is_resource_file()) name=r->get_path().get_file(); else name=r->get_name(); if (name=="") name=r->get_class(); } else if (obj->cast_to<Node>()) { name=obj->cast_to<Node>()->get_name(); } else if (obj->cast_to<Resource>() && obj->cast_to<Resource>()->get_name()!="") { name=obj->cast_to<Resource>()->get_name(); } else { name=obj->get_class(); } set_tooltip(obj->get_class()); label_font->draw(ci,Point2i(ofs,(size.height-label_font->get_height())/2+label_font->get_ascent()),name,Color(1,1,1),left); } else { //add arrow //sn->draw(ci,Point2i(ofs,(size.height-sn->get_height())/2)); //ofs+=sn->get_width(); ofs+=5; //just looks better! somehow } } } break; } } void EditorPath::update_path() { update(); } void EditorPath::_popup_select(int p_idx) { ERR_FAIL_INDEX(p_idx,objects.size()); Object* obj = ObjectDB::get_instance(objects[p_idx]); if (!obj) return; EditorNode::get_singleton()->push_item(obj); } void EditorPath::_bind_methods() { ClassDB::bind_method("_gui_input",&EditorPath::_gui_input); ClassDB::bind_method("_popup_select",&EditorPath::_popup_select); } EditorPath::EditorPath(EditorHistory *p_history) { history=p_history; mouse_over=false; popup = memnew( PopupMenu ); popup->connect("id_pressed",this,"_popup_select"); add_child(popup); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
scene/resources/environment.cpp
1,006
/*************************************************************************/ /* environment.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "environment.h" #include "texture.h" #include "globals.h" #include "servers/visual_server.h" RID Environment::get_rid() const { return environment; } void Environment::set_background(BGMode p_bg) { bg_mode=p_bg; VS::get_singleton()->environment_set_background(environment,VS::EnvironmentBG(p_bg)); _change_notify(); } void Environment::set_skybox(const Ref<SkyBox> &p_skybox){ bg_skybox=p_skybox; RID sb_rid; if (bg_skybox.is_valid()) sb_rid=bg_skybox->get_rid(); VS::get_singleton()->environment_set_skybox(environment,sb_rid); } void Environment::set_skybox_scale(float p_scale) { bg_skybox_scale=p_scale; VS::get_singleton()->environment_set_skybox_scale(environment,p_scale); } void Environment::set_bg_color(const Color& p_color){ bg_color=p_color; VS::get_singleton()->environment_set_bg_color(environment,p_color); } void Environment::set_bg_energy(float p_energy){ bg_energy=p_energy; VS::get_singleton()->environment_set_bg_energy(environment,p_energy); } void Environment::set_canvas_max_layer(int p_max_layer){ bg_canvas_max_layer=p_max_layer; VS::get_singleton()->environment_set_canvas_max_layer(environment,p_max_layer); } void Environment::set_ambient_light_color(const Color& p_color){ ambient_color=p_color; VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution); } void Environment::set_ambient_light_energy(float p_energy){ ambient_energy=p_energy; VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution); } void Environment::set_ambient_light_skybox_contribution(float p_energy){ ambient_skybox_contribution=p_energy; VS::get_singleton()->environment_set_ambient_light(environment,ambient_color,ambient_energy,ambient_skybox_contribution); } Environment::BGMode Environment::get_background() const{ return bg_mode; } Ref<SkyBox> Environment::get_skybox() const{ return bg_skybox; } float Environment::get_skybox_scale() const { return bg_skybox_scale; } Color Environment::get_bg_color() const{ return bg_color; } float Environment::get_bg_energy() const{ return bg_energy; } int Environment::get_canvas_max_layer() const{ return bg_canvas_max_layer; } Color Environment::get_ambient_light_color() const{ return ambient_color; } float Environment::get_ambient_light_energy() const{ return ambient_energy; } float Environment::get_ambient_light_skybox_contribution() const{ return ambient_skybox_contribution; } void Environment::set_tonemapper(ToneMapper p_tone_mapper) { tone_mapper=p_tone_mapper; VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); } Environment::ToneMapper Environment::get_tonemapper() const{ return tone_mapper; } void Environment::set_tonemap_exposure(float p_exposure){ tonemap_exposure=p_exposure; VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); } float Environment::get_tonemap_exposure() const{ return tonemap_exposure; } void Environment::set_tonemap_white(float p_white){ tonemap_white=p_white; VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); } float Environment::get_tonemap_white() const { return tonemap_white; } void Environment::set_tonemap_auto_exposure(bool p_enabled) { tonemap_auto_exposure=p_enabled; VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); } bool Environment::get_tonemap_auto_exposure() const { return tonemap_auto_exposure; } void Environment::set_tonemap_auto_exposure_max(float p_auto_exposure_max) { tonemap_auto_exposure_max=p_auto_exposure_max; VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); } float Environment::get_tonemap_auto_exposure_max() const { return tonemap_auto_exposure_max; } void Environment::set_tonemap_auto_exposure_min(float p_auto_exposure_min) { tonemap_auto_exposure_min=p_auto_exposure_min; VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); } float Environment::get_tonemap_auto_exposure_min() const { return tonemap_auto_exposure_min; } void Environment::set_tonemap_auto_exposure_speed(float p_auto_exposure_speed) { tonemap_auto_exposure_speed=p_auto_exposure_speed; VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); } float Environment::get_tonemap_auto_exposure_speed() const { return tonemap_auto_exposure_speed; } void Environment::set_tonemap_auto_exposure_grey(float p_auto_exposure_grey) { tonemap_auto_exposure_grey=p_auto_exposure_grey; VS::get_singleton()->environment_set_tonemap(environment,VS::EnvironmentToneMapper(tone_mapper),tonemap_exposure,tonemap_white,tonemap_auto_exposure,tonemap_auto_exposure_min,tonemap_auto_exposure_max,tonemap_auto_exposure_speed,tonemap_auto_exposure_grey); } float Environment::get_tonemap_auto_exposure_grey() const { return tonemap_auto_exposure_grey; } void Environment::set_adjustment_enable(bool p_enable) { adjustment_enabled=p_enable; VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); } bool Environment::is_adjustment_enabled() const { return adjustment_enabled; } void Environment::set_adjustment_brightness(float p_brightness) { adjustment_brightness=p_brightness; VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); } float Environment::get_adjustment_brightness() const { return adjustment_brightness; } void Environment::set_adjustment_contrast(float p_contrast) { adjustment_contrast=p_contrast; VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); } float Environment::get_adjustment_contrast() const { return adjustment_contrast; } void Environment::set_adjustment_saturation(float p_saturation) { adjustment_saturation=p_saturation; VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); } float Environment::get_adjustment_saturation() const { return adjustment_saturation; } void Environment::set_adjustment_color_correction(const Ref<Texture>& p_ramp) { adjustment_color_correction=p_ramp; VS::get_singleton()->environment_set_adjustment(environment,adjustment_enabled,adjustment_brightness,adjustment_contrast,adjustment_saturation,adjustment_color_correction.is_valid()?adjustment_color_correction->get_rid():RID()); } Ref<Texture> Environment::get_adjustment_color_correction() const { return adjustment_color_correction; } void Environment::_validate_property(PropertyInfo& property) const { if (property.name=="background/skybox" || property.name=="background/skybox_scale" || property.name=="ambient_light/skybox_contribution") { if (bg_mode!=BG_SKYBOX) { property.usage=PROPERTY_USAGE_NOEDITOR; } } if (property.name=="background/color") { if (bg_mode!=BG_COLOR) { property.usage=PROPERTY_USAGE_NOEDITOR; } } if (property.name=="background/canvas_max_layer") { if (bg_mode!=BG_CANVAS) { property.usage=PROPERTY_USAGE_NOEDITOR; } } } void Environment::set_ssr_enabled(bool p_enable) { ssr_enabled=p_enable; VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); } bool Environment::is_ssr_enabled() const{ return ssr_enabled; } void Environment::set_ssr_max_steps(int p_steps){ ssr_max_steps=p_steps; VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); } int Environment::get_ssr_max_steps() const { return ssr_max_steps; } void Environment::set_ssr_accel(float p_accel) { ssr_accel=p_accel; VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); } float Environment::get_ssr_accel() const { return ssr_accel; } void Environment::set_ssr_fade(float p_fade) { ssr_fade=p_fade; VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); } float Environment::get_ssr_fade() const { return ssr_fade; } void Environment::set_ssr_depth_tolerance(float p_depth_tolerance) { ssr_depth_tolerance=p_depth_tolerance; VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); } float Environment::get_ssr_depth_tolerance() const { return ssr_depth_tolerance; } void Environment::set_ssr_smooth(bool p_enable) { ssr_smooth=p_enable; VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); } bool Environment::is_ssr_smooth() const { return ssr_smooth; } void Environment::set_ssr_rough(bool p_enable) { ssr_roughness=p_enable; VS::get_singleton()->environment_set_ssr(environment,ssr_enabled,ssr_max_steps,ssr_accel,ssr_fade,ssr_depth_tolerance,ssr_smooth,ssr_roughness); } bool Environment::is_ssr_rough() const { return ssr_roughness; } void Environment::set_ssao_enabled(bool p_enable) { ssao_enabled=p_enable; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } bool Environment::is_ssao_enabled() const{ return ssao_enabled; } void Environment::set_ssao_radius(float p_radius){ ssao_radius=p_radius; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } float Environment::get_ssao_radius() const{ return ssao_radius; } void Environment::set_ssao_intensity(float p_intensity){ ssao_intensity=p_intensity; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } float Environment::get_ssao_intensity() const{ return ssao_intensity; } void Environment::set_ssao_radius2(float p_radius){ ssao_radius2=p_radius; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } float Environment::get_ssao_radius2() const{ return ssao_radius2; } void Environment::set_ssao_intensity2(float p_intensity){ ssao_intensity2=p_intensity; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } float Environment::get_ssao_intensity2() const{ return ssao_intensity2; } void Environment::set_ssao_bias(float p_bias){ ssao_bias=p_bias; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } float Environment::get_ssao_bias() const{ return ssao_bias; } void Environment::set_ssao_direct_light_affect(float p_direct_light_affect){ ssao_direct_light_affect=p_direct_light_affect; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } float Environment::get_ssao_direct_light_affect() const{ return ssao_direct_light_affect; } void Environment::set_ssao_color(const Color& p_color) { ssao_color=p_color; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } Color Environment::get_ssao_color() const { return ssao_color; } void Environment::set_ssao_blur(bool p_enable) { ssao_blur=p_enable; VS::get_singleton()->environment_set_ssao(environment,ssao_enabled,ssao_radius,ssao_intensity,ssao_radius2,ssao_intensity2,ssao_bias,ssao_direct_light_affect,ssao_color,ssao_blur); } bool Environment::is_ssao_blur_enabled() const { return ssao_blur; } void Environment::set_glow_enabled(bool p_enabled) { glow_enabled=p_enabled; VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } bool Environment::is_glow_enabled() const{ return glow_enabled; } void Environment::set_glow_level(int p_level,bool p_enabled){ ERR_FAIL_INDEX(p_level,VS::MAX_GLOW_LEVELS); if (p_enabled) glow_levels|=(1<<p_level); else glow_levels&=~(1<<p_level); VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } bool Environment::is_glow_level_enabled(int p_level) const{ ERR_FAIL_INDEX_V(p_level,VS::MAX_GLOW_LEVELS,false); return glow_levels&(1<<p_level); } void Environment::set_glow_intensity(float p_intensity){ glow_intensity=p_intensity; VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } float Environment::get_glow_intensity() const{ return glow_intensity; } void Environment::set_glow_strength(float p_strength){ glow_strength=p_strength; VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } float Environment::get_glow_strength() const{ return glow_strength; } void Environment::set_glow_bloom(float p_treshold){ glow_bloom=p_treshold; VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } float Environment::get_glow_bloom() const{ return glow_bloom; } void Environment::set_glow_blend_mode(GlowBlendMode p_mode){ glow_blend_mode=p_mode; VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } Environment::GlowBlendMode Environment::get_glow_blend_mode() const{ return glow_blend_mode; } void Environment::set_glow_hdr_bleed_treshold(float p_treshold){ glow_hdr_bleed_treshold=p_treshold; VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } float Environment::get_glow_hdr_bleed_treshold() const{ return glow_hdr_bleed_treshold; } void Environment::set_glow_hdr_bleed_scale(float p_scale){ glow_hdr_bleed_scale=p_scale; VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } float Environment::get_glow_hdr_bleed_scale() const{ return glow_hdr_bleed_scale; } void Environment::set_glow_bicubic_upscale(bool p_enable) { glow_bicubic_upscale=p_enable; VS::get_singleton()->environment_set_glow(environment,glow_enabled,glow_levels,glow_intensity,glow_strength,glow_bloom,VS::EnvironmentGlowBlendMode(glow_blend_mode),glow_hdr_bleed_treshold,glow_hdr_bleed_treshold,glow_bicubic_upscale); } bool Environment::is_glow_bicubic_upscale_enabled() const { return glow_bicubic_upscale; } void Environment::set_dof_blur_far_enabled(bool p_enable) { dof_blur_far_enabled=p_enable; VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } bool Environment::is_dof_blur_far_enabled() const{ return dof_blur_far_enabled; } void Environment::set_dof_blur_far_distance(float p_distance){ dof_blur_far_distance=p_distance; VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } float Environment::get_dof_blur_far_distance() const{ return dof_blur_far_distance; } void Environment::set_dof_blur_far_transition(float p_distance){ dof_blur_far_transition=p_distance; VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } float Environment::get_dof_blur_far_transition() const{ return dof_blur_far_transition; } void Environment::set_dof_blur_far_amount(float p_amount){ dof_blur_far_amount=p_amount; VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } float Environment::get_dof_blur_far_amount() const{ return dof_blur_far_amount; } void Environment::set_dof_blur_far_quality(DOFBlurQuality p_quality) { dof_blur_far_quality=p_quality; VS::get_singleton()->environment_set_dof_blur_far(environment,dof_blur_far_enabled,dof_blur_far_distance,dof_blur_far_transition,dof_blur_far_amount,VS::EnvironmentDOFBlurQuality(dof_blur_far_quality)); } Environment::DOFBlurQuality Environment::get_dof_blur_far_quality() const { return dof_blur_far_quality; } void Environment::set_dof_blur_near_enabled(bool p_enable) { dof_blur_near_enabled=p_enable; VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } bool Environment::is_dof_blur_near_enabled() const{ return dof_blur_near_enabled; } void Environment::set_dof_blur_near_distance(float p_distance){ dof_blur_near_distance=p_distance; VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } float Environment::get_dof_blur_near_distance() const{ return dof_blur_near_distance; } void Environment::set_dof_blur_near_transition(float p_distance){ dof_blur_near_transition=p_distance; VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } float Environment::get_dof_blur_near_transition() const{ return dof_blur_near_transition; } void Environment::set_dof_blur_near_amount(float p_amount){ dof_blur_near_amount=p_amount; VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } float Environment::get_dof_blur_near_amount() const{ return dof_blur_near_amount; } void Environment::set_dof_blur_near_quality(DOFBlurQuality p_quality) { dof_blur_near_quality=p_quality; VS::get_singleton()->environment_set_dof_blur_near(environment,dof_blur_near_enabled,dof_blur_near_distance,dof_blur_near_transition,dof_blur_near_amount,VS::EnvironmentDOFBlurQuality(dof_blur_near_quality)); } Environment::DOFBlurQuality Environment::get_dof_blur_near_quality() const { return dof_blur_near_quality; } void Environment::_bind_methods() { ClassDB::bind_method(_MD("set_background","mode"),&Environment::set_background); ClassDB::bind_method(_MD("set_skybox","skybox:CubeMap"),&Environment::set_skybox); ClassDB::bind_method(_MD("set_skybox_scale","scale"),&Environment::set_skybox_scale); ClassDB::bind_method(_MD("set_bg_color","color"),&Environment::set_bg_color); ClassDB::bind_method(_MD("set_bg_energy","energy"),&Environment::set_bg_energy); ClassDB::bind_method(_MD("set_canvas_max_layer","layer"),&Environment::set_canvas_max_layer); ClassDB::bind_method(_MD("set_ambient_light_color","color"),&Environment::set_ambient_light_color); ClassDB::bind_method(_MD("set_ambient_light_energy","energy"),&Environment::set_ambient_light_energy); ClassDB::bind_method(_MD("set_ambient_light_skybox_contribution","energy"),&Environment::set_ambient_light_skybox_contribution); ClassDB::bind_method(_MD("get_background"),&Environment::get_background); ClassDB::bind_method(_MD("get_skybox:CubeMap"),&Environment::get_skybox); ClassDB::bind_method(_MD("get_skybox_scale"),&Environment::get_skybox_scale); ClassDB::bind_method(_MD("get_bg_color"),&Environment::get_bg_color); ClassDB::bind_method(_MD("get_bg_energy"),&Environment::get_bg_energy); ClassDB::bind_method(_MD("get_canvas_max_layer"),&Environment::get_canvas_max_layer); ClassDB::bind_method(_MD("get_ambient_light_color"),&Environment::get_ambient_light_color); ClassDB::bind_method(_MD("get_ambient_light_energy"),&Environment::get_ambient_light_energy); ClassDB::bind_method(_MD("get_ambient_light_skybox_contribution"),&Environment::get_ambient_light_skybox_contribution); ADD_GROUP("Background","background_"); ADD_PROPERTY(PropertyInfo(Variant::INT,"background_mode",PROPERTY_HINT_ENUM,"Clear Color,Custom Color,Skybox,Canvas,Keep"),_SCS("set_background"),_SCS("get_background") ); ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"background_skybox",PROPERTY_HINT_RESOURCE_TYPE,"SkyBox"),_SCS("set_skybox"),_SCS("get_skybox") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"background_skybox_scale",PROPERTY_HINT_RANGE,"0,32,0.01"),_SCS("set_skybox_scale"),_SCS("get_skybox_scale") ); ADD_PROPERTY(PropertyInfo(Variant::COLOR,"background_color"),_SCS("set_bg_color"),_SCS("get_bg_color") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"background_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_bg_energy"),_SCS("get_bg_energy") ); ADD_PROPERTY(PropertyInfo(Variant::INT,"background_canvas_max_layer",PROPERTY_HINT_RANGE,"-1000,1000,1"),_SCS("set_canvas_max_layer"),_SCS("get_canvas_max_layer") ); ADD_GROUP("Ambient Light","ambient_light_"); ADD_PROPERTY(PropertyInfo(Variant::COLOR,"ambient_light_color"),_SCS("set_ambient_light_color"),_SCS("get_ambient_light_color") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ambient_light_energy",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_ambient_light_energy"),_SCS("get_ambient_light_energy") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ambient_light_skybox_contribution",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_ambient_light_skybox_contribution"),_SCS("get_ambient_light_skybox_contribution") ); ClassDB::bind_method(_MD("set_ssr_enabled","enabled"),&Environment::set_ssr_enabled); ClassDB::bind_method(_MD("is_ssr_enabled"),&Environment::is_ssr_enabled); ClassDB::bind_method(_MD("set_ssr_max_steps","max_steps"),&Environment::set_ssr_max_steps); ClassDB::bind_method(_MD("get_ssr_max_steps"),&Environment::get_ssr_max_steps); ClassDB::bind_method(_MD("set_ssr_accel","accel"),&Environment::set_ssr_accel); ClassDB::bind_method(_MD("get_ssr_accel"),&Environment::get_ssr_accel); ClassDB::bind_method(_MD("set_ssr_fade","fade"),&Environment::set_ssr_fade); ClassDB::bind_method(_MD("get_ssr_fade"),&Environment::get_ssr_fade); ClassDB::bind_method(_MD("set_ssr_depth_tolerance","depth_tolerance"),&Environment::set_ssr_depth_tolerance); ClassDB::bind_method(_MD("get_ssr_depth_tolerance"),&Environment::get_ssr_depth_tolerance); ClassDB::bind_method(_MD("set_ssr_smooth","smooth"),&Environment::set_ssr_smooth); ClassDB::bind_method(_MD("is_ssr_smooth"),&Environment::is_ssr_smooth); ClassDB::bind_method(_MD("set_ssr_rough","rough"),&Environment::set_ssr_rough); ClassDB::bind_method(_MD("is_ssr_rough"),&Environment::is_ssr_rough); ADD_GROUP("SS Reflections","ss_reflections_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_enabled"),_SCS("set_ssr_enabled"),_SCS("is_ssr_enabled") ); ADD_PROPERTY(PropertyInfo(Variant::INT,"ss_reflections_max_steps",PROPERTY_HINT_RANGE,"1,512,1"),_SCS("set_ssr_max_steps"),_SCS("get_ssr_max_steps") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_accel",PROPERTY_HINT_RANGE,"0,4,0.01"),_SCS("set_ssr_accel"),_SCS("get_ssr_accel") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_fade",PROPERTY_HINT_EXP_EASING),_SCS("set_ssr_fade"),_SCS("get_ssr_fade") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ss_reflections_depth_tolerance",PROPERTY_HINT_RANGE,"0.1,128,0.1"),_SCS("set_ssr_depth_tolerance"),_SCS("get_ssr_depth_tolerance") ); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_accel_smooth"),_SCS("set_ssr_smooth"),_SCS("is_ssr_smooth") ); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ss_reflections_roughness"),_SCS("set_ssr_rough"),_SCS("is_ssr_rough") ); ClassDB::bind_method(_MD("set_ssao_enabled","enabled"),&Environment::set_ssao_enabled); ClassDB::bind_method(_MD("is_ssao_enabled"),&Environment::is_ssao_enabled); ClassDB::bind_method(_MD("set_ssao_radius","radius"),&Environment::set_ssao_radius); ClassDB::bind_method(_MD("get_ssao_radius"),&Environment::get_ssao_radius); ClassDB::bind_method(_MD("set_ssao_intensity","intensity"),&Environment::set_ssao_intensity); ClassDB::bind_method(_MD("get_ssao_intensity"),&Environment::get_ssao_intensity); ClassDB::bind_method(_MD("set_ssao_radius2","radius"),&Environment::set_ssao_radius2); ClassDB::bind_method(_MD("get_ssao_radius2"),&Environment::get_ssao_radius2); ClassDB::bind_method(_MD("set_ssao_intensity2","intensity"),&Environment::set_ssao_intensity2); ClassDB::bind_method(_MD("get_ssao_intensity2"),&Environment::get_ssao_intensity2); ClassDB::bind_method(_MD("set_ssao_bias","bias"),&Environment::set_ssao_bias); ClassDB::bind_method(_MD("get_ssao_bias"),&Environment::get_ssao_bias); ClassDB::bind_method(_MD("set_ssao_direct_light_affect","amount"),&Environment::set_ssao_direct_light_affect); ClassDB::bind_method(_MD("get_ssao_direct_light_affect"),&Environment::get_ssao_direct_light_affect); ClassDB::bind_method(_MD("set_ssao_color","color"),&Environment::set_ssao_color); ClassDB::bind_method(_MD("get_ssao_color"),&Environment::get_ssao_color); ClassDB::bind_method(_MD("set_ssao_blur","enabled"),&Environment::set_ssao_blur); ClassDB::bind_method(_MD("is_ssao_blur_enabled"),&Environment::is_ssao_blur_enabled); ADD_GROUP("SSAO","ssao_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ssao_enabled"),_SCS("set_ssao_enabled"),_SCS("is_ssao_enabled") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_radius",PROPERTY_HINT_RANGE,"0.1,16,0.1"),_SCS("set_ssao_radius"),_SCS("get_ssao_radius") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_intensity",PROPERTY_HINT_RANGE,"0.0,9,0.1"),_SCS("set_ssao_intensity"),_SCS("get_ssao_intensity") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_radius2",PROPERTY_HINT_RANGE,"0.0,16,0.1"),_SCS("set_ssao_radius2"),_SCS("get_ssao_radius2") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_intensity2",PROPERTY_HINT_RANGE,"0.0,9,0.1"),_SCS("set_ssao_intensity2"),_SCS("get_ssao_intensity2") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_bias",PROPERTY_HINT_RANGE,"0.001,8,0.001"),_SCS("set_ssao_bias"),_SCS("get_ssao_bias") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ssao_light_affect",PROPERTY_HINT_RANGE,"0.00,1,0.01"),_SCS("set_ssao_direct_light_affect"),_SCS("get_ssao_direct_light_affect") ); ADD_PROPERTY(PropertyInfo(Variant::COLOR,"ssao_color",PROPERTY_HINT_COLOR_NO_ALPHA),_SCS("set_ssao_color"),_SCS("get_ssao_color") ); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"ssao_blur"),_SCS("set_ssao_blur"),_SCS("is_ssao_blur_enabled") ); ClassDB::bind_method(_MD("set_dof_blur_far_enabled","enabled"),&Environment::set_dof_blur_far_enabled); ClassDB::bind_method(_MD("is_dof_blur_far_enabled"),&Environment::is_dof_blur_far_enabled); ClassDB::bind_method(_MD("set_dof_blur_far_distance","intensity"),&Environment::set_dof_blur_far_distance); ClassDB::bind_method(_MD("get_dof_blur_far_distance"),&Environment::get_dof_blur_far_distance); ClassDB::bind_method(_MD("set_dof_blur_far_transition","intensity"),&Environment::set_dof_blur_far_transition); ClassDB::bind_method(_MD("get_dof_blur_far_transition"),&Environment::get_dof_blur_far_transition); ClassDB::bind_method(_MD("set_dof_blur_far_amount","intensity"),&Environment::set_dof_blur_far_amount); ClassDB::bind_method(_MD("get_dof_blur_far_amount"),&Environment::get_dof_blur_far_amount); ClassDB::bind_method(_MD("set_dof_blur_far_quality","intensity"),&Environment::set_dof_blur_far_quality); ClassDB::bind_method(_MD("get_dof_blur_far_quality"),&Environment::get_dof_blur_far_quality); ClassDB::bind_method(_MD("set_dof_blur_near_enabled","enabled"),&Environment::set_dof_blur_near_enabled); ClassDB::bind_method(_MD("is_dof_blur_near_enabled"),&Environment::is_dof_blur_near_enabled); ClassDB::bind_method(_MD("set_dof_blur_near_distance","intensity"),&Environment::set_dof_blur_near_distance); ClassDB::bind_method(_MD("get_dof_blur_near_distance"),&Environment::get_dof_blur_near_distance); ClassDB::bind_method(_MD("set_dof_blur_near_transition","intensity"),&Environment::set_dof_blur_near_transition); ClassDB::bind_method(_MD("get_dof_blur_near_transition"),&Environment::get_dof_blur_near_transition); ClassDB::bind_method(_MD("set_dof_blur_near_amount","intensity"),&Environment::set_dof_blur_near_amount); ClassDB::bind_method(_MD("get_dof_blur_near_amount"),&Environment::get_dof_blur_near_amount); ClassDB::bind_method(_MD("set_dof_blur_near_quality","level"),&Environment::set_dof_blur_near_quality); ClassDB::bind_method(_MD("get_dof_blur_near_quality"),&Environment::get_dof_blur_near_quality); ADD_GROUP("DOF Far Blur","dof_blur_far_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"dof_blur_far_enabled"),_SCS("set_dof_blur_far_enabled"),_SCS("is_dof_blur_far_enabled") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_distance",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),_SCS("set_dof_blur_far_distance"),_SCS("get_dof_blur_far_distance") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_transition",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),_SCS("set_dof_blur_far_transition"),_SCS("get_dof_blur_far_transition") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_far_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_dof_blur_far_amount"),_SCS("get_dof_blur_far_amount") ); ADD_PROPERTY(PropertyInfo(Variant::INT,"dof_blur_far_quality",PROPERTY_HINT_ENUM,"Low,Medium,High"),_SCS("set_dof_blur_far_quality"),_SCS("get_dof_blur_far_quality") ); ADD_GROUP("DOF Far Near","dof_blur_near_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"dof_blur_near_enabled"),_SCS("set_dof_blur_near_enabled"),_SCS("is_dof_blur_near_enabled") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_distance",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),_SCS("set_dof_blur_near_distance"),_SCS("get_dof_blur_near_distance") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_transition",PROPERTY_HINT_EXP_RANGE,"0.01,8192,0.01"),_SCS("set_dof_blur_near_transition"),_SCS("get_dof_blur_near_transition") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"dof_blur_near_amount",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_dof_blur_near_amount"),_SCS("get_dof_blur_near_amount") ); ADD_PROPERTY(PropertyInfo(Variant::INT,"dof_blur_near_quality",PROPERTY_HINT_ENUM,"Low,Medium,High"),_SCS("set_dof_blur_near_quality"),_SCS("get_dof_blur_near_quality") ); ClassDB::bind_method(_MD("set_glow_enabled","enabled"),&Environment::set_glow_enabled); ClassDB::bind_method(_MD("is_glow_enabled"),&Environment::is_glow_enabled); ClassDB::bind_method(_MD("set_glow_level","idx","enabled"),&Environment::set_glow_level); ClassDB::bind_method(_MD("is_glow_level_enabled","idx"),&Environment::is_glow_level_enabled); ClassDB::bind_method(_MD("set_glow_intensity","intensity"),&Environment::set_glow_intensity); ClassDB::bind_method(_MD("get_glow_intensity"),&Environment::get_glow_intensity); ClassDB::bind_method(_MD("set_glow_strength","strength"),&Environment::set_glow_strength); ClassDB::bind_method(_MD("get_glow_strength"),&Environment::get_glow_strength); ClassDB::bind_method(_MD("set_glow_bloom","amount"),&Environment::set_glow_bloom); ClassDB::bind_method(_MD("get_glow_bloom"),&Environment::get_glow_bloom); ClassDB::bind_method(_MD("set_glow_blend_mode","mode"),&Environment::set_glow_blend_mode); ClassDB::bind_method(_MD("get_glow_blend_mode"),&Environment::get_glow_blend_mode); ClassDB::bind_method(_MD("set_glow_hdr_bleed_treshold","treshold"),&Environment::set_glow_hdr_bleed_treshold); ClassDB::bind_method(_MD("get_glow_hdr_bleed_treshold"),&Environment::get_glow_hdr_bleed_treshold); ClassDB::bind_method(_MD("set_glow_hdr_bleed_scale","scale"),&Environment::set_glow_hdr_bleed_scale); ClassDB::bind_method(_MD("get_glow_hdr_bleed_scale"),&Environment::get_glow_hdr_bleed_scale); ClassDB::bind_method(_MD("set_glow_bicubic_upscale","enabled"),&Environment::set_glow_bicubic_upscale); ClassDB::bind_method(_MD("is_glow_bicubic_upscale_enabled"),&Environment::is_glow_bicubic_upscale_enabled); ADD_GROUP("Glow","glow_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"glow_enabled"),_SCS("set_glow_enabled"),_SCS("is_glow_enabled") ); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/1"),_SCS("set_glow_level"),_SCS("is_glow_level_enabled"),0 ); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/2"),_SCS("set_glow_level"),_SCS("is_glow_level_enabled"),1 ); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/3"),_SCS("set_glow_level"),_SCS("is_glow_level_enabled"),2 ); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/4"),_SCS("set_glow_level"),_SCS("is_glow_level_enabled"),3 ); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/5"),_SCS("set_glow_level"),_SCS("is_glow_level_enabled"),4 ); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/6"),_SCS("set_glow_level"),_SCS("is_glow_level_enabled"),5 ); ADD_PROPERTYI(PropertyInfo(Variant::BOOL,"glow_levels/7"),_SCS("set_glow_level"),_SCS("is_glow_level_enabled"),6 ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_intensity",PROPERTY_HINT_RANGE,"0.0,8.0,0.01"),_SCS("set_glow_intensity"),_SCS("get_glow_intensity") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_strength",PROPERTY_HINT_RANGE,"0.0,2.0,0.01"),_SCS("set_glow_strength"),_SCS("get_glow_strength") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_bloom",PROPERTY_HINT_RANGE,"0.0,1.0,0.01"),_SCS("set_glow_bloom"),_SCS("get_glow_bloom") ); ADD_PROPERTY(PropertyInfo(Variant::INT,"glow_blend_mode",PROPERTY_HINT_ENUM,"Additive,Screen,Softlight,Replace"),_SCS("set_glow_blend_mode"),_SCS("get_glow_blend_mode") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_hdr_treshold",PROPERTY_HINT_RANGE,"0.0,4.0,0.01"),_SCS("set_glow_hdr_bleed_treshold"),_SCS("get_glow_hdr_bleed_treshold") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"glow_hdr_scale",PROPERTY_HINT_RANGE,"0.0,4.0,0.01"),_SCS("set_glow_hdr_bleed_scale"),_SCS("get_glow_hdr_bleed_scale") ); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"glow_bicubic_upscale"),_SCS("set_glow_bicubic_upscale"),_SCS("is_glow_bicubic_upscale_enabled") ); ClassDB::bind_method(_MD("set_tonemapper","mode"),&Environment::set_tonemapper); ClassDB::bind_method(_MD("get_tonemapper"),&Environment::get_tonemapper); ClassDB::bind_method(_MD("set_tonemap_exposure","exposure"),&Environment::set_tonemap_exposure); ClassDB::bind_method(_MD("get_tonemap_exposure"),&Environment::get_tonemap_exposure); ClassDB::bind_method(_MD("set_tonemap_white","white"),&Environment::set_tonemap_white); ClassDB::bind_method(_MD("get_tonemap_white"),&Environment::get_tonemap_white); ClassDB::bind_method(_MD("set_tonemap_auto_exposure","auto_exposure"),&Environment::set_tonemap_auto_exposure); ClassDB::bind_method(_MD("get_tonemap_auto_exposure"),&Environment::get_tonemap_auto_exposure); ClassDB::bind_method(_MD("set_tonemap_auto_exposure_max","exposure_max"),&Environment::set_tonemap_auto_exposure_max); ClassDB::bind_method(_MD("get_tonemap_auto_exposure_max"),&Environment::get_tonemap_auto_exposure_max); ClassDB::bind_method(_MD("set_tonemap_auto_exposure_min","exposure_min"),&Environment::set_tonemap_auto_exposure_min); ClassDB::bind_method(_MD("get_tonemap_auto_exposure_min"),&Environment::get_tonemap_auto_exposure_min); ClassDB::bind_method(_MD("set_tonemap_auto_exposure_speed","exposure_speed"),&Environment::set_tonemap_auto_exposure_speed); ClassDB::bind_method(_MD("get_tonemap_auto_exposure_speed"),&Environment::get_tonemap_auto_exposure_speed); ClassDB::bind_method(_MD("set_tonemap_auto_exposure_grey","exposure_grey"),&Environment::set_tonemap_auto_exposure_grey); ClassDB::bind_method(_MD("get_tonemap_auto_exposure_grey"),&Environment::get_tonemap_auto_exposure_grey); ADD_GROUP("Tonemap","tonemap_"); ADD_PROPERTY(PropertyInfo(Variant::INT,"tonemap_mode",PROPERTY_HINT_ENUM,"Linear,Reindhart,Filmic,Aces"),_SCS("set_tonemapper"),_SCS("get_tonemapper") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"tonemap_exposure",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_tonemap_exposure"),_SCS("get_tonemap_exposure") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"tonemap_white",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_tonemap_white"),_SCS("get_tonemap_white") ); ADD_GROUP("Auto Exposure","auto_exposure_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"auto_expoure_enabled"),_SCS("set_tonemap_auto_exposure"),_SCS("get_tonemap_auto_exposure") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_scale",PROPERTY_HINT_RANGE,"0.01,64,0.01"),_SCS("set_tonemap_auto_exposure_grey"),_SCS("get_tonemap_auto_exposure_grey") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_min_luma",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_tonemap_auto_exposure_min"),_SCS("get_tonemap_auto_exposure_min") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_max_luma",PROPERTY_HINT_RANGE,"0,16,0.01"),_SCS("set_tonemap_auto_exposure_max"),_SCS("get_tonemap_auto_exposure_max") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"auto_expoure_speed",PROPERTY_HINT_RANGE,"0.01,64,0.01"),_SCS("set_tonemap_auto_exposure_speed"),_SCS("get_tonemap_auto_exposure_speed") ); ClassDB::bind_method(_MD("set_adjustment_enable","enabled"),&Environment::set_adjustment_enable); ClassDB::bind_method(_MD("is_adjustment_enabled"),&Environment::is_adjustment_enabled); ClassDB::bind_method(_MD("set_adjustment_brightness","brightness"),&Environment::set_adjustment_brightness); ClassDB::bind_method(_MD("get_adjustment_brightness"),&Environment::get_adjustment_brightness); ClassDB::bind_method(_MD("set_adjustment_contrast","contrast"),&Environment::set_adjustment_contrast); ClassDB::bind_method(_MD("get_adjustment_contrast"),&Environment::get_adjustment_contrast); ClassDB::bind_method(_MD("set_adjustment_saturation","saturation"),&Environment::set_adjustment_saturation); ClassDB::bind_method(_MD("get_adjustment_saturation"),&Environment::get_adjustment_saturation); ClassDB::bind_method(_MD("set_adjustment_color_correction","color_correction"),&Environment::set_adjustment_color_correction); ClassDB::bind_method(_MD("get_adjustment_color_correction"),&Environment::get_adjustment_color_correction); ADD_GROUP("Adjustments","adjustment_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL,"adjustment_enabled"),_SCS("set_adjustment_enable"),_SCS("is_adjustment_enabled") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_brightness",PROPERTY_HINT_RANGE,"0.01,8,0.01"),_SCS("set_adjustment_brightness"),_SCS("get_adjustment_brightness") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_contrast",PROPERTY_HINT_RANGE,"0.01,8,0.01"),_SCS("set_adjustment_contrast"),_SCS("get_adjustment_contrast") ); ADD_PROPERTY(PropertyInfo(Variant::REAL,"adjustment_saturation",PROPERTY_HINT_RANGE,"0.01,8,0.01"),_SCS("set_adjustment_saturation"),_SCS("get_adjustment_saturation") ); ADD_PROPERTY(PropertyInfo(Variant::OBJECT,"adjustment_color_correction",PROPERTY_HINT_RESOURCE_TYPE,"Texture"),_SCS("set_adjustment_color_correction"),_SCS("get_adjustment_color_correction") ); GLOBAL_DEF("rendering/skybox/irradiance_cube_resolution",256); BIND_CONSTANT(BG_KEEP); BIND_CONSTANT(BG_CLEAR_COLOR); BIND_CONSTANT(BG_COLOR); BIND_CONSTANT(BG_SKYBOX); BIND_CONSTANT(BG_CANVAS); BIND_CONSTANT(BG_MAX); BIND_CONSTANT(GLOW_BLEND_MODE_ADDITIVE); BIND_CONSTANT(GLOW_BLEND_MODE_SCREEN); BIND_CONSTANT(GLOW_BLEND_MODE_SOFTLIGHT); BIND_CONSTANT(GLOW_BLEND_MODE_REPLACE); BIND_CONSTANT(TONE_MAPPER_LINEAR); BIND_CONSTANT(TONE_MAPPER_REINHARDT); BIND_CONSTANT(TONE_MAPPER_FILMIC); BIND_CONSTANT(TONE_MAPPER_ACES); BIND_CONSTANT(DOF_BLUR_QUALITY_LOW); BIND_CONSTANT(DOF_BLUR_QUALITY_MEDIUM); BIND_CONSTANT(DOF_BLUR_QUALITY_HIGH); } Environment::Environment() { bg_mode=BG_CLEAR_COLOR; bg_skybox_scale=1.0; bg_energy=1.0; bg_canvas_max_layer=0; ambient_energy=1.0; ambient_skybox_contribution=0; tone_mapper=TONE_MAPPER_LINEAR; tonemap_exposure=1.0; tonemap_white=1.0; tonemap_auto_exposure=false; tonemap_auto_exposure_max=8; tonemap_auto_exposure_min=0.05; tonemap_auto_exposure_speed=0.5; tonemap_auto_exposure_grey=0.4; set_tonemapper(tone_mapper); //update adjustment_enabled=false; adjustment_contrast=1.0; adjustment_saturation=1.0; adjustment_brightness=1.0; set_adjustment_enable(adjustment_enabled); //update environment = VS::get_singleton()->environment_create(); ssr_enabled=false; ssr_max_steps=64; ssr_accel=0.04; ssr_fade=2.0; ssr_depth_tolerance=0.2; ssr_smooth=true; ssr_roughness=true; ssao_enabled=false; ssao_radius=1; ssao_intensity=1; ssao_radius2=0; ssao_intensity2=1; ssao_bias=0.01; ssao_direct_light_affect=false; ssao_blur=true; glow_enabled=false; glow_levels=(1<<2)|(1<<4); glow_intensity=0.8; glow_strength=1.0; glow_bloom=0.0; glow_blend_mode=GLOW_BLEND_MODE_SOFTLIGHT; glow_hdr_bleed_treshold=1.0; glow_hdr_bleed_scale=2.0; glow_bicubic_upscale=false; dof_blur_far_enabled=false; dof_blur_far_distance=10; dof_blur_far_transition=5; dof_blur_far_amount=0.1; dof_blur_far_quality=DOF_BLUR_QUALITY_MEDIUM; dof_blur_near_enabled=false; dof_blur_near_distance=2; dof_blur_near_transition=1; dof_blur_near_amount=0.1; dof_blur_near_quality=DOF_BLUR_QUALITY_MEDIUM; } Environment::~Environment() { VS::get_singleton()->free(environment); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/eq.cpp
219
// // C++ Interface: eq // // Description: // // // Author: reduzio@gmail.com (C) 2006 // // Copyright: See COPYING file that comes with this distribution // // #include "eq.h" #include <math.h> #include "error_macros.h" #include "math_funcs.h" #define POW2(v) ((v)*(v)) /* Helper */ static int solve_quadratic(double a,double b,double c,double *r1, double *r2) { //solves quadractic and returns number of roots double base=2*a; if (base == 0.0f) return 0; double squared=b*b-4*a*c; if (squared<0.0) return 0; squared=sqrt(squared); *r1=(-b+squared)/base; *r2=(-b-squared)/base; if (*r1==*r2) return 1; else return 2; } EQ::BandProcess::BandProcess() { c1=c2=c3=history.a1=history.a2=history.a3=0; history.b1=history.b2=history.b3=0; } void EQ::recalculate_band_coefficients() { #define BAND_LOG( m_f ) ( log((m_f)) / log(2) ) for (int i=0;i<band.size();i++) { double octave_size; double frq=band[i].freq; if (i==0) { octave_size=BAND_LOG(band[1].freq)-BAND_LOG(frq); } else if (i==(band.size()-1)) { octave_size=BAND_LOG(frq)-BAND_LOG(band[i-1].freq); } else { double next=BAND_LOG(band[i+1].freq)-BAND_LOG(frq); double prev=BAND_LOG(frq)-BAND_LOG(band[i-1].freq); octave_size=(next+prev)/2.0; } double frq_l=round(frq/pow(2.0,octave_size/2.0)); double side_gain2=POW2(Math_SQRT12); double th=2.0*Math_PI*frq/mix_rate; double th_l=2.0*Math_PI*frq_l/mix_rate; double c2a=side_gain2 * POW2(cos(th)) - 2.0 * side_gain2 * cos(th_l) * cos(th) + side_gain2 - POW2(sin(th_l)); double c2b=2.0 * side_gain2 * POW2(cos(th_l)) + side_gain2 * POW2(cos(th)) - 2.0 * side_gain2 * cos(th_l) * cos(th) - side_gain2 + POW2(sin(th_l)); double c2c=0.25 * side_gain2 * POW2(cos(th)) - 0.5 * side_gain2 * cos(th_l) * cos(th) + 0.25 * side_gain2 - 0.25 * POW2(sin(th_l)); //printf("band %i, precoefs = %f,%f,%f\n",i,c2a,c2b,c2c); double r1,r2; //roots int roots=solve_quadratic(c2a,c2b,c2c,&r1,&r2); ERR_CONTINUE( roots==0 ); band[i].c1=2.0 * ((0.5-r1)/2.0); band[i].c2=2.0 * r1; band[i].c3=2.0 * (0.5+r1) * cos(th); //printf("band %i, coefs = %f,%f,%f\n",i,(float)bands[i].c1,(float)bands[i].c2,(float)bands[i].c3); } } void EQ::set_preset_band_mode(Preset p_preset) { band.clear(); #define PUSH_BANDS(m_bands) \ for (int i=0;i<m_bands;i++) { \ Band b; \ b.freq=bands[i];\ band.push_back(b);\ } switch (p_preset) { case PRESET_6_BANDS: { static const double bands[] = { 32 , 100 , 320 , 1e3, 3200, 10e3 }; PUSH_BANDS(6); } break; case PRESET_8_BANDS: { static const double bands[] = { 32,72,192,512,1200,3000,7500,16e3 }; PUSH_BANDS(8); } break; case PRESET_10_BANDS: { static const double bands[] = { 31.25, 62.5, 125 , 250 , 500 , 1e3, 2e3, 4e3, 8e3, 16e3 }; PUSH_BANDS(10); } break; case PRESET_21_BANDS: { static const double bands[] = { 22 , 32 , 44 , 63 , 90 , 125 , 175 , 250 , 350 , 500 , 700 , 1e3, 1400 , 2e3, 2800 , 4e3, 5600 , 8e3, 11e3, 16e3, 22e3 }; PUSH_BANDS(21); } break; case PRESET_31_BANDS: { static const double bands[] = { 20, 25, 31.5, 40 , 50 , 63 , 80 , 100 , 125 , 160 , 200 , 250 , 315 , 400 , 500 , 630 , 800 , 1e3 , 1250 , 1600 , 2e3, 2500 , 3150 , 4e3, 5e3, 6300 , 8e3, 10e3, 12500 , 16e3, 20e3 }; PUSH_BANDS(31); } break; }; recalculate_band_coefficients(); } int EQ::get_band_count() const { return band.size(); } float EQ::get_band_frequency(int p_band) { ERR_FAIL_INDEX_V(p_band,band.size(),0); return band[p_band].freq; } void EQ::set_bands(const Vector<float>& p_bands) { band.resize(p_bands.size()); for (int i=0;i<p_bands.size();i++) { band[i].freq=p_bands[i]; } recalculate_band_coefficients(); } void EQ::set_mix_rate(float p_mix_rate) { mix_rate=p_mix_rate; recalculate_band_coefficients(); } EQ::BandProcess EQ::get_band_processor(int p_band) const { EQ::BandProcess band_proc; ERR_FAIL_INDEX_V(p_band,band.size(),band_proc); band_proc.c1=band[p_band].c1; band_proc.c2=band[p_band].c2; band_proc.c3=band[p_band].c3; return band_proc; } EQ::EQ() { mix_rate=44100; } EQ::~EQ() { }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_limiter.cpp
124
#include "audio_effect_limiter.h" void AudioEffectLimiterInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { float thresh = Math::db2linear(base->treshold); float threshdb = base->treshold; float ceiling = Math::db2linear(base->ceiling); float ceildb = base->ceiling; float makeup = Math::db2linear(ceildb - threshdb); float makeupdb = ceildb - threshdb; float sc = -base->soft_clip; float scv = Math::db2linear(sc); float sccomp = Math::db2linear(-sc); float peakdb = ceildb + 25; float peaklvl = Math::db2linear(peakdb); float scratio = base->soft_clip_ratio; float scmult = Math::abs((ceildb - sc) / (peakdb - sc)); for(int i=0;i<p_frame_count;i++) { float spl0 = p_src_frames[i].l; float spl1 = p_src_frames[i].r; spl0 = spl0 * makeup; spl1 = spl1 * makeup; float sign0 = (spl0 < 0.0 ? -1.0 : 1.0 ); float sign1 = (spl1 < 0.0 ? -1.0 : 1.0 ); float abs0 = Math::abs(spl0); float abs1 = Math::abs(spl1); float overdb0 = Math::linear2db(abs0) - ceildb; float overdb1 = Math::linear2db(abs1) - ceildb; if (abs0 > scv) { spl0 = sign0 * (scv + Math::db2linear(overdb0 * scmult)); } if (abs1 > scv) { spl1 = sign1 * (scv + Math::db2linear(overdb1 * scmult)); } spl0 = MIN(ceiling, Math::abs(spl0)) * (spl0 < 0.0 ? -1.0 : 1.0); spl1 = MIN(ceiling, Math::abs(spl1)) * (spl1 < 0.0 ? -1.0 : 1.0); p_dst_frames[i].l = spl0; p_dst_frames[i].r = spl1; } } Ref<AudioEffectInstance> AudioEffectLimiter::instance() { Ref<AudioEffectLimiterInstance> ins; ins.instance(); ins->base=Ref<AudioEffectLimiter>(this); return ins; } void AudioEffectLimiter::set_treshold_db(float p_treshold) { treshold=p_treshold; } float AudioEffectLimiter::get_treshold_db() const{ return treshold; } void AudioEffectLimiter::set_ceiling_db(float p_ceiling){ ceiling=p_ceiling; } float AudioEffectLimiter::get_ceiling_db() const{ return ceiling; } void AudioEffectLimiter::set_soft_clip_db(float p_soft_clip){ soft_clip=p_soft_clip; } float AudioEffectLimiter::get_soft_clip_db() const{ return soft_clip; } void AudioEffectLimiter::set_soft_clip_ratio(float p_soft_clip){ soft_clip_ratio=p_soft_clip; } float AudioEffectLimiter::get_soft_clip_ratio() const{ return soft_clip; } void AudioEffectLimiter::_bind_methods() { ClassDB::bind_method(_MD("set_ceiling_db","ceiling"),&AudioEffectLimiter::set_ceiling_db); ClassDB::bind_method(_MD("get_ceiling_db"),&AudioEffectLimiter::get_ceiling_db); ClassDB::bind_method(_MD("set_treshold_db","treshold"),&AudioEffectLimiter::set_treshold_db); ClassDB::bind_method(_MD("get_treshold_db"),&AudioEffectLimiter::get_treshold_db); ClassDB::bind_method(_MD("set_soft_clip_db","soft_clip"),&AudioEffectLimiter::set_soft_clip_db); ClassDB::bind_method(_MD("get_soft_clip_db"),&AudioEffectLimiter::get_soft_clip_db); ClassDB::bind_method(_MD("set_soft_clip_ratio","soft_clip"),&AudioEffectLimiter::set_soft_clip_ratio); ClassDB::bind_method(_MD("get_soft_clip_ratio"),&AudioEffectLimiter::get_soft_clip_ratio); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ceiling_db",PROPERTY_HINT_RANGE,"-20,-0.1,0.1"),_SCS("set_ceiling_db"),_SCS("get_ceiling_db")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"treshold_db",PROPERTY_HINT_RANGE,"-30,0,0.1"),_SCS("set_treshold_db"),_SCS("get_treshold_db")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"soft_clip_db",PROPERTY_HINT_RANGE,"0,6,0.1"),_SCS("set_soft_clip_db"),_SCS("get_soft_clip_db")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"soft_clip_ratio",PROPERTY_HINT_RANGE,"3,20,0.1"),_SCS("set_soft_clip_ratio"),_SCS("get_soft_clip_ratio")); } AudioEffectLimiter::AudioEffectLimiter() { treshold=0; ceiling=-0.1; soft_clip=2; soft_clip_ratio=10; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_eq.cpp
122
#include "audio_effect_eq.h" #include "servers/audio_server.h" void AudioEffectEQInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { int band_count = bands[0].size(); EQ::BandProcess *proc_l = bands[0].ptr(); EQ::BandProcess *proc_r = bands[1].ptr(); float *bgain = gains.ptr(); for(int i=0;i<band_count;i++) { bgain[i]=Math::db2linear(base->gain[i]); } for(int i=0;i<p_frame_count;i++) { AudioFrame src = p_src_frames[i]; AudioFrame dst = AudioFrame(0,0); for(int j=0;j<band_count;j++) { float l = src.l; float r = src.r; proc_l[j].process_one(l); proc_r[j].process_one(r); dst.l+=l * bgain[j]; dst.r+=r * bgain[j]; } p_dst_frames[i]=dst; } } Ref<AudioEffectInstance> AudioEffectEQ::instance() { Ref<AudioEffectEQInstance> ins; ins.instance(); ins->base=Ref<AudioEffectEQ>(this); ins->gains.resize(eq.get_band_count()); for(int i=0;i<2;i++) { ins->bands[i].resize(eq.get_band_count()); for(int j=0;j<ins->bands[i].size();j++) { ins->bands[i][j]=eq.get_band_processor(j); } } return ins; } void AudioEffectEQ::set_band_gain_db(int p_band,float p_volume) { ERR_FAIL_INDEX(p_band,gain.size()); gain[p_band]=p_volume; } float AudioEffectEQ::get_band_gain_db(int p_band) const { ERR_FAIL_INDEX_V(p_band,gain.size(),0); return gain[p_band]; } int AudioEffectEQ::get_band_count() const { return gain.size(); } bool AudioEffectEQ::_set(const StringName& p_name, const Variant& p_value) { const Map<StringName,int>::Element *E=prop_band_map.find(p_name); if (E) { set_band_gain_db(E->get(),p_value); return true; } return false; } bool AudioEffectEQ::_get(const StringName& p_name,Variant &r_ret) const{ const Map<StringName,int>::Element *E=prop_band_map.find(p_name); if (E) { r_ret=get_band_gain_db(E->get()); return true; } return false; } void AudioEffectEQ::_get_property_list( List<PropertyInfo> *p_list) const{ for(int i=0;i<band_names.size();i++) { p_list->push_back(PropertyInfo(Variant::REAL,band_names[i],PROPERTY_HINT_RANGE,"-60,24,0.1")); } } void AudioEffectEQ::_bind_methods() { ClassDB::bind_method(_MD("set_band_gain_db","band_idx","volume_db"),&AudioEffectEQ::set_band_gain_db); ClassDB::bind_method(_MD("get_band_gain_db","band_idx"),&AudioEffectEQ::get_band_gain_db); ClassDB::bind_method(_MD("get_band_count"),&AudioEffectEQ::get_band_count); } AudioEffectEQ::AudioEffectEQ(EQ::Preset p_preset) { eq.set_mix_rate(AudioServer::get_singleton()->get_mix_rate()); eq.set_preset_band_mode(p_preset); gain.resize(eq.get_band_count()); for(int i=0;i<gain.size();i++) { gain[i]=0.0; String name = "band_db/"+itos(eq.get_band_frequency(i))+"_hz"; prop_band_map[name]=i; band_names.push_back(name); } }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
core/math/matrix3.cpp
281
/*************************************************************************/ /* matrix3.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "matrix3.h" #include "math_funcs.h" #include "os/copymem.h" #define cofac(row1,col1, row2, col2)\ (elements[row1][col1] * elements[row2][col2] - elements[row1][col2] * elements[row2][col1]) void Basis::from_z(const Vector3& p_z) { if (Math::abs(p_z.z) > Math_SQRT12 ) { // choose p in y-z plane real_t a = p_z[1]*p_z[1] + p_z[2]*p_z[2]; real_t k = 1.0/Math::sqrt(a); elements[0]=Vector3(0,-p_z[2]*k,p_z[1]*k); elements[1]=Vector3(a*k,-p_z[0]*elements[0][2],p_z[0]*elements[0][1]); } else { // choose p in x-y plane real_t a = p_z.x*p_z.x + p_z.y*p_z.y; real_t k = 1.0/Math::sqrt(a); elements[0]=Vector3(-p_z.y*k,p_z.x*k,0); elements[1]=Vector3(-p_z.z*elements[0].y,p_z.z*elements[0].x,a*k); } elements[2]=p_z; } void Basis::invert() { real_t co[3]={ cofac(1, 1, 2, 2), cofac(1, 2, 2, 0), cofac(1, 0, 2, 1) }; real_t det = elements[0][0] * co[0]+ elements[0][1] * co[1]+ elements[0][2] * co[2]; ERR_FAIL_COND( det == 0 ); real_t s = 1.0/det; set( co[0]*s, cofac(0, 2, 2, 1) * s, cofac(0, 1, 1, 2) * s, co[1]*s, cofac(0, 0, 2, 2) * s, cofac(0, 2, 1, 0) * s, co[2]*s, cofac(0, 1, 2, 0) * s, cofac(0, 0, 1, 1) * s ); } void Basis::orthonormalize() { ERR_FAIL_COND(determinant() == 0); // Gram-Schmidt Process Vector3 x=get_axis(0); Vector3 y=get_axis(1); Vector3 z=get_axis(2); x.normalize(); y = (y-x*(x.dot(y))); y.normalize(); z = (z-x*(x.dot(z))-y*(y.dot(z))); z.normalize(); set_axis(0,x); set_axis(1,y); set_axis(2,z); } Basis Basis::orthonormalized() const { Basis c = *this; c.orthonormalize(); return c; } bool Basis::is_orthogonal() const { Basis id; Basis m = (*this)*transposed(); return isequal_approx(id,m); } bool Basis::is_rotation() const { return Math::isequal_approx(determinant(), 1) && is_orthogonal(); } bool Basis::is_symmetric() const { if (Math::abs(elements[0][1] - elements[1][0]) > CMP_EPSILON) return false; if (Math::abs(elements[0][2] - elements[2][0]) > CMP_EPSILON) return false; if (Math::abs(elements[1][2] - elements[2][1]) > CMP_EPSILON) return false; return true; } Basis Basis::diagonalize() { //NOTE: only implemented for symmetric matrices //with the Jacobi iterative method method ERR_FAIL_COND_V(!is_symmetric(), Basis()); const int ite_max = 1024; real_t off_matrix_norm_2 = elements[0][1] * elements[0][1] + elements[0][2] * elements[0][2] + elements[1][2] * elements[1][2]; int ite = 0; Basis acc_rot; while (off_matrix_norm_2 > CMP_EPSILON2 && ite++ < ite_max ) { real_t el01_2 = elements[0][1] * elements[0][1]; real_t el02_2 = elements[0][2] * elements[0][2]; real_t el12_2 = elements[1][2] * elements[1][2]; // Find the pivot element int i, j; if (el01_2 > el02_2) { if (el12_2 > el01_2) { i = 1; j = 2; } else { i = 0; j = 1; } } else { if (el12_2 > el02_2) { i = 1; j = 2; } else { i = 0; j = 2; } } // Compute the rotation angle real_t angle; if (Math::abs(elements[j][j] - elements[i][i]) < CMP_EPSILON) { angle = Math_PI / 4; } else { angle = 0.5 * Math::atan(2 * elements[i][j] / (elements[j][j] - elements[i][i])); } // Compute the rotation matrix Basis rot; rot.elements[i][i] = rot.elements[j][j] = Math::cos(angle); rot.elements[i][j] = - (rot.elements[j][i] = Math::sin(angle)); // Update the off matrix norm off_matrix_norm_2 -= elements[i][j] * elements[i][j]; // Apply the rotation *this = rot * *this * rot.transposed(); acc_rot = rot * acc_rot; } return acc_rot; } Basis Basis::inverse() const { Basis inv=*this; inv.invert(); return inv; } void Basis::transpose() { SWAP(elements[0][1],elements[1][0]); SWAP(elements[0][2],elements[2][0]); SWAP(elements[1][2],elements[2][1]); } Basis Basis::transposed() const { Basis tr=*this; tr.transpose(); return tr; } // Multiplies the matrix from left by the scaling matrix: M -> S.M // See the comment for Basis::rotated for further explanation. void Basis::scale(const Vector3& p_scale) { elements[0][0]*=p_scale.x; elements[0][1]*=p_scale.x; elements[0][2]*=p_scale.x; elements[1][0]*=p_scale.y; elements[1][1]*=p_scale.y; elements[1][2]*=p_scale.y; elements[2][0]*=p_scale.z; elements[2][1]*=p_scale.z; elements[2][2]*=p_scale.z; } Basis Basis::scaled( const Vector3& p_scale ) const { Basis m = *this; m.scale(p_scale); return m; } Vector3 Basis::get_scale() const { // We are assuming M = R.S, and performing a polar decomposition to extract R and S. // FIXME: We eventually need a proper polar decomposition. // As a cheap workaround until then, to ensure that R is a proper rotation matrix with determinant +1 // (such that it can be represented by a Quat or Euler angles), we absorb the sign flip into the scaling matrix. // As such, it works in conjuction with get_rotation(). real_t det_sign = determinant() > 0 ? 1 : -1; return det_sign*Vector3( Vector3(elements[0][0],elements[1][0],elements[2][0]).length(), Vector3(elements[0][1],elements[1][1],elements[2][1]).length(), Vector3(elements[0][2],elements[1][2],elements[2][2]).length() ); } // Multiplies the matrix from left by the rotation matrix: M -> R.M // Note that this does *not* rotate the matrix itself. // // The main use of Basis is as Transform.basis, which is used a the transformation matrix // of 3D object. Rotate here refers to rotation of the object (which is R * (*this)), // not the matrix itself (which is R * (*this) * R.transposed()). Basis Basis::rotated(const Vector3& p_axis, real_t p_phi) const { return Basis(p_axis, p_phi) * (*this); } void Basis::rotate(const Vector3& p_axis, real_t p_phi) { *this = rotated(p_axis, p_phi); } Basis Basis::rotated(const Vector3& p_euler) const { return Basis(p_euler) * (*this); } void Basis::rotate(const Vector3& p_euler) { *this = rotated(p_euler); } Vector3 Basis::get_rotation() const { // Assumes that the matrix can be decomposed into a proper rotation and scaling matrix as M = R.S, // and returns the Euler angles corresponding to the rotation part, complementing get_scale(). // See the comment in get_scale() for further information. Basis m = orthonormalized(); real_t det = m.determinant(); if (det < 0) { // Ensure that the determinant is 1, such that result is a proper rotation matrix which can be represented by Euler angles. m.scale(Vector3(-1,-1,-1)); } return m.get_euler(); } // get_euler returns a vector containing the Euler angles in the format // (a1,a2,a3), where a3 is the angle of the first rotation, and a1 is the last // (following the convention they are commonly defined in the literature). // // The current implementation uses XYZ convention (Z is the first rotation), // so euler.z is the angle of the (first) rotation around Z axis and so on, // // And thus, assuming the matrix is a rotation matrix, this function returns // the angles in the decomposition R = X(a1).Y(a2).Z(a3) where Z(a) rotates // around the z-axis by a and so on. Vector3 Basis::get_euler() const { // Euler angles in XYZ convention. // See https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix // // rot = cy*cz -cy*sz sy // cz*sx*sy+cx*sz cx*cz-sx*sy*sz -cy*sx // -cx*cz*sy+sx*sz cz*sx+cx*sy*sz cx*cy Vector3 euler; ERR_FAIL_COND_V(is_rotation() == false, euler); euler.y = Math::asin(elements[0][2]); if ( euler.y < Math_PI*0.5) { if ( euler.y > -Math_PI*0.5) { euler.x = Math::atan2(-elements[1][2],elements[2][2]); euler.z = Math::atan2(-elements[0][1],elements[0][0]); } else { real_t r = Math::atan2(elements[1][0],elements[1][1]); euler.z = 0.0; euler.x = euler.z - r; } } else { real_t r = Math::atan2(elements[0][1],elements[1][1]); euler.z = 0; euler.x = r - euler.z; } return euler; } // set_euler expects a vector containing the Euler angles in the format // (c,b,a), where a is the angle of the first rotation, and c is the last. // The current implementation uses XYZ convention (Z is the first rotation). void Basis::set_euler(const Vector3& p_euler) { real_t c, s; c = Math::cos(p_euler.x); s = Math::sin(p_euler.x); Basis xmat(1.0,0.0,0.0,0.0,c,-s,0.0,s,c); c = Math::cos(p_euler.y); s = Math::sin(p_euler.y); Basis ymat(c,0.0,s,0.0,1.0,0.0,-s,0.0,c); c = Math::cos(p_euler.z); s = Math::sin(p_euler.z); Basis zmat(c,-s,0.0,s,c,0.0,0.0,0.0,1.0); //optimizer will optimize away all this anyway *this = xmat*(ymat*zmat); } bool Basis::isequal_approx(const Basis& a, const Basis& b) const { for (int i=0;i<3;i++) { for (int j=0;j<3;j++) { if (Math::isequal_approx(a.elements[i][j],b.elements[i][j]) == false) return false; } } return true; } bool Basis::operator==(const Basis& p_matrix) const { for (int i=0;i<3;i++) { for (int j=0;j<3;j++) { if (elements[i][j] != p_matrix.elements[i][j]) return false; } } return true; } bool Basis::operator!=(const Basis& p_matrix) const { return (!(*this==p_matrix)); } Basis::operator String() const { String mtx; for (int i=0;i<3;i++) { for (int j=0;j<3;j++) { if (i!=0 || j!=0) mtx+=", "; mtx+=rtos( elements[i][j] ); } } return mtx; } Basis::operator Quat() const { ERR_FAIL_COND_V(is_rotation() == false, Quat()); real_t trace = elements[0][0] + elements[1][1] + elements[2][2]; real_t temp[4]; if (trace > 0.0) { real_t s = Math::sqrt(trace + 1.0); temp[3]=(s * 0.5); s = 0.5 / s; temp[0]=((elements[2][1] - elements[1][2]) * s); temp[1]=((elements[0][2] - elements[2][0]) * s); temp[2]=((elements[1][0] - elements[0][1]) * s); } else { int i = elements[0][0] < elements[1][1] ? (elements[1][1] < elements[2][2] ? 2 : 1) : (elements[0][0] < elements[2][2] ? 2 : 0); int j = (i + 1) % 3; int k = (i + 2) % 3; real_t s = Math::sqrt(elements[i][i] - elements[j][j] - elements[k][k] + 1.0); temp[i] = s * 0.5; s = 0.5 / s; temp[3] = (elements[k][j] - elements[j][k]) * s; temp[j] = (elements[j][i] + elements[i][j]) * s; temp[k] = (elements[k][i] + elements[i][k]) * s; } return Quat(temp[0],temp[1],temp[2],temp[3]); } static const Basis _ortho_bases[24]={ Basis(1, 0, 0, 0, 1, 0, 0, 0, 1), Basis(0, -1, 0, 1, 0, 0, 0, 0, 1), Basis(-1, 0, 0, 0, -1, 0, 0, 0, 1), Basis(0, 1, 0, -1, 0, 0, 0, 0, 1), Basis(1, 0, 0, 0, 0, -1, 0, 1, 0), Basis(0, 0, 1, 1, 0, 0, 0, 1, 0), Basis(-1, 0, 0, 0, 0, 1, 0, 1, 0), Basis(0, 0, -1, -1, 0, 0, 0, 1, 0), Basis(1, 0, 0, 0, -1, 0, 0, 0, -1), Basis(0, 1, 0, 1, 0, 0, 0, 0, -1), Basis(-1, 0, 0, 0, 1, 0, 0, 0, -1), Basis(0, -1, 0, -1, 0, 0, 0, 0, -1), Basis(1, 0, 0, 0, 0, 1, 0, -1, 0), Basis(0, 0, -1, 1, 0, 0, 0, -1, 0), Basis(-1, 0, 0, 0, 0, -1, 0, -1, 0), Basis(0, 0, 1, -1, 0, 0, 0, -1, 0), Basis(0, 0, 1, 0, 1, 0, -1, 0, 0), Basis(0, -1, 0, 0, 0, 1, -1, 0, 0), Basis(0, 0, -1, 0, -1, 0, -1, 0, 0), Basis(0, 1, 0, 0, 0, -1, -1, 0, 0), Basis(0, 0, 1, 0, -1, 0, 1, 0, 0), Basis(0, 1, 0, 0, 0, 1, 1, 0, 0), Basis(0, 0, -1, 0, 1, 0, 1, 0, 0), Basis(0, -1, 0, 0, 0, -1, 1, 0, 0) }; int Basis::get_orthogonal_index() const { //could be sped up if i come up with a way Basis orth=*this; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { real_t v = orth[i][j]; if (v>0.5) v=1.0; else if (v<-0.5) v=-1.0; else v=0; orth[i][j]=v; } } for(int i=0;i<24;i++) { if (_ortho_bases[i]==orth) return i; } return 0; } void Basis::set_orthogonal_index(int p_index){ //there only exist 24 orthogonal bases in r3 ERR_FAIL_INDEX(p_index,24); *this=_ortho_bases[p_index]; } void Basis::get_axis_and_angle(Vector3 &r_axis,real_t& r_angle) const { ERR_FAIL_COND(is_rotation() == false); real_t angle,x,y,z; // variables for result real_t epsilon = 0.01; // margin to allow for rounding errors real_t epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees if ( (Math::abs(elements[1][0]-elements[0][1])< epsilon) && (Math::abs(elements[2][0]-elements[0][2])< epsilon) && (Math::abs(elements[2][1]-elements[1][2])< epsilon)) { // singularity found // first check for identity matrix which must have +1 for all terms // in leading diagonaland zero in other terms if ((Math::abs(elements[1][0]+elements[0][1]) < epsilon2) && (Math::abs(elements[2][0]+elements[0][2]) < epsilon2) && (Math::abs(elements[2][1]+elements[1][2]) < epsilon2) && (Math::abs(elements[0][0]+elements[1][1]+elements[2][2]-3) < epsilon2)) { // this singularity is identity matrix so angle = 0 r_axis=Vector3(0,1,0); r_angle=0; return; } // otherwise this singularity is angle = 180 angle = Math_PI; real_t xx = (elements[0][0]+1)/2; real_t yy = (elements[1][1]+1)/2; real_t zz = (elements[2][2]+1)/2; real_t xy = (elements[1][0]+elements[0][1])/4; real_t xz = (elements[2][0]+elements[0][2])/4; real_t yz = (elements[2][1]+elements[1][2])/4; if ((xx > yy) && (xx > zz)) { // elements[0][0] is the largest diagonal term if (xx< epsilon) { x = 0; y = 0.7071; z = 0.7071; } else { x = Math::sqrt(xx); y = xy/x; z = xz/x; } } else if (yy > zz) { // elements[1][1] is the largest diagonal term if (yy< epsilon) { x = 0.7071; y = 0; z = 0.7071; } else { y = Math::sqrt(yy); x = xy/y; z = yz/y; } } else { // elements[2][2] is the largest diagonal term so base result on this if (zz< epsilon) { x = 0.7071; y = 0.7071; z = 0; } else { z = Math::sqrt(zz); x = xz/z; y = yz/z; } } r_axis=Vector3(x,y,z); r_angle=angle; return; } // as we have reached here there are no singularities so we can handle normally real_t s = Math::sqrt((elements[1][2] - elements[2][1])*(elements[1][2] - elements[2][1]) +(elements[2][0] - elements[0][2])*(elements[2][0] - elements[0][2]) +(elements[0][1] - elements[1][0])*(elements[0][1] - elements[1][0])); // s=|axis||sin(angle)|, used to normalise angle = Math::acos(( elements[0][0] + elements[1][1] + elements[2][2] - 1)/2); if (angle < 0) s = -s; x = (elements[2][1] - elements[1][2])/s; y = (elements[0][2] - elements[2][0])/s; z = (elements[1][0] - elements[0][1])/s; r_axis=Vector3(x,y,z); r_angle=angle; } Basis::Basis(const Vector3& p_euler) { set_euler( p_euler ); } Basis::Basis(const Quat& p_quat) { real_t d = p_quat.length_squared(); real_t s = 2.0 / d; real_t xs = p_quat.x * s, ys = p_quat.y * s, zs = p_quat.z * s; real_t wx = p_quat.w * xs, wy = p_quat.w * ys, wz = p_quat.w * zs; real_t xx = p_quat.x * xs, xy = p_quat.x * ys, xz = p_quat.x * zs; real_t yy = p_quat.y * ys, yz = p_quat.y * zs, zz = p_quat.z * zs; set( 1.0 - (yy + zz), xy - wz, xz + wy, xy + wz, 1.0 - (xx + zz), yz - wx, xz - wy, yz + wx, 1.0 - (xx + yy)) ; } Basis::Basis(const Vector3& p_axis, real_t p_phi) { // Rotation matrix from axis and angle, see https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Vector3 axis_sq(p_axis.x*p_axis.x,p_axis.y*p_axis.y,p_axis.z*p_axis.z); real_t cosine= Math::cos(p_phi); real_t sine= Math::sin(p_phi); elements[0][0] = axis_sq.x + cosine * ( 1.0 - axis_sq.x ); elements[0][1] = p_axis.x * p_axis.y * ( 1.0 - cosine ) - p_axis.z * sine; elements[0][2] = p_axis.z * p_axis.x * ( 1.0 - cosine ) + p_axis.y * sine; elements[1][0] = p_axis.x * p_axis.y * ( 1.0 - cosine ) + p_axis.z * sine; elements[1][1] = axis_sq.y + cosine * ( 1.0 - axis_sq.y ); elements[1][2] = p_axis.y * p_axis.z * ( 1.0 - cosine ) - p_axis.x * sine; elements[2][0] = p_axis.z * p_axis.x * ( 1.0 - cosine ) - p_axis.y * sine; elements[2][1] = p_axis.y * p_axis.z * ( 1.0 - cosine ) + p_axis.x * sine; elements[2][2] = axis_sq.z + cosine * ( 1.0 - axis_sq.z ); }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
thirdparty/zlib/gzwrite.c
665
/* gzwrite.c -- zlib functions for writing gzip files * Copyright (C) 2004-2017 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" /* Local functions */ local int gz_init OF((gz_statep)); local int gz_comp OF((gz_statep, int)); local int gz_zero OF((gz_statep, z_off64_t)); local z_size_t gz_write OF((gz_statep, voidpc, z_size_t)); /* Initialize state for writing a gzip file. Mark initialization by setting state->size to non-zero. Return -1 on a memory allocation failure, or 0 on success. */ local int gz_init(state) gz_statep state; { int ret; z_streamp strm = &(state->strm); /* allocate input buffer (double size for gzprintf) */ state->in = (unsigned char *)malloc(state->want << 1); if (state->in == NULL) { gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } /* only need output buffer and deflate state if compressing */ if (!state->direct) { /* allocate output buffer */ state->out = (unsigned char *)malloc(state->want); if (state->out == NULL) { free(state->in); gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } /* allocate deflate memory, set up for gzip compression */ strm->zalloc = Z_NULL; strm->zfree = Z_NULL; strm->opaque = Z_NULL; ret = deflateInit2(strm, state->level, Z_DEFLATED, MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy); if (ret != Z_OK) { free(state->out); free(state->in); gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } strm->next_in = NULL; } /* mark state as initialized */ state->size = state->want; /* initialize write buffer if compressing */ if (!state->direct) { strm->avail_out = state->size; strm->next_out = state->out; state->x.next = strm->next_out; } return 0; } /* Compress whatever is at avail_in and next_in and write to the output file. Return -1 if there is an error writing to the output file or if gz_init() fails to allocate memory, otherwise 0. flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, then the deflate() state is reset to start a new gzip stream. If gz->direct is true, then simply write to the output file without compressing, and ignore flush. */ local int gz_comp(state, flush) gz_statep state; int flush; { int ret, writ; unsigned have, put, max = ((unsigned)-1 >> 2) + 1; z_streamp strm = &(state->strm); /* allocate memory if this is the first time through */ if (state->size == 0 && gz_init(state) == -1) return -1; /* write directly if requested */ if (state->direct) { while (strm->avail_in) { put = strm->avail_in > max ? max : strm->avail_in; writ = write(state->fd, strm->next_in, put); if (writ < 0) { gz_error(state, Z_ERRNO, zstrerror()); return -1; } strm->avail_in -= (unsigned)writ; strm->next_in += writ; } return 0; } /* run deflate() on provided input until it produces no more output */ ret = Z_OK; do { /* write out current buffer contents if full, or if flushing, but if doing Z_FINISH then don't write until we get to Z_STREAM_END */ if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && (flush != Z_FINISH || ret == Z_STREAM_END))) { while (strm->next_out > state->x.next) { put = strm->next_out - state->x.next > (int)max ? max : (unsigned)(strm->next_out - state->x.next); writ = write(state->fd, state->x.next, put); if (writ < 0) { gz_error(state, Z_ERRNO, zstrerror()); return -1; } state->x.next += writ; } if (strm->avail_out == 0) { strm->avail_out = state->size; strm->next_out = state->out; state->x.next = state->out; } } /* compress */ have = strm->avail_out; ret = deflate(strm, flush); if (ret == Z_STREAM_ERROR) { gz_error(state, Z_STREAM_ERROR, "internal error: deflate stream corrupt"); return -1; } have -= strm->avail_out; } while (have); /* if that completed a deflate stream, allow another to start */ if (flush == Z_FINISH) deflateReset(strm); /* all done, no errors */ return 0; } /* Compress len zeros to output. Return -1 on a write error or memory allocation failure by gz_comp(), or 0 on success. */ local int gz_zero(state, len) gz_statep state; z_off64_t len; { int first; unsigned n; z_streamp strm = &(state->strm); /* consume whatever's left in the input buffer */ if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return -1; /* compress len zeros (len guaranteed > 0) */ first = 1; while (len) { n = GT_OFF(state->size) || (z_off64_t)state->size > len ? (unsigned)len : state->size; if (first) { memset(state->in, 0, n); first = 0; } strm->avail_in = n; strm->next_in = state->in; state->x.pos += n; if (gz_comp(state, Z_NO_FLUSH) == -1) return -1; len -= n; } return 0; } /* Write len bytes from buf to file. Return the number of bytes written. If the returned value is less than len, then there was an error. */ local z_size_t gz_write(state, buf, len) gz_statep state; voidpc buf; z_size_t len; { z_size_t put = len; /* if len is zero, avoid unnecessary operations */ if (len == 0) return 0; /* allocate memory if this is the first time through */ if (state->size == 0 && gz_init(state) == -1) return 0; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return 0; } /* for small len, copy to input buffer, otherwise compress directly */ if (len < state->size) { /* copy to input buffer, compress when full */ do { unsigned have, copy; if (state->strm.avail_in == 0) state->strm.next_in = state->in; have = (unsigned)((state->strm.next_in + state->strm.avail_in) - state->in); copy = state->size - have; if (copy > len) copy = len; memcpy(state->in + have, buf, copy); state->strm.avail_in += copy; state->x.pos += copy; buf = (const char *)buf + copy; len -= copy; if (len && gz_comp(state, Z_NO_FLUSH) == -1) return 0; } while (len); } else { /* consume whatever's left in the input buffer */ if (state->strm.avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return 0; /* directly compress user buffer to file */ state->strm.next_in = (z_const Bytef *)buf; do { unsigned n = (unsigned)-1; if (n > len) n = len; state->strm.avail_in = n; state->x.pos += n; if (gz_comp(state, Z_NO_FLUSH) == -1) return 0; len -= n; } while (len); } /* input was all buffered or compressed */ return put; } /* -- see zlib.h -- */ int ZEXPORT gzwrite(file, buf, len) gzFile file; voidpc buf; unsigned len; { gz_statep state; /* get internal structure */ if (file == NULL) return 0; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids a flaw in the interface) */ if ((int)len < 0) { gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); return 0; } /* write len bytes from buf (the return value will fit in an int) */ return (int)gz_write(state, buf, len); } /* -- see zlib.h -- */ z_size_t ZEXPORT gzfwrite(buf, size, nitems, file) voidpc buf; z_size_t size; z_size_t nitems; gzFile file; { z_size_t len; gz_statep state; /* get internal structure */ if (file == NULL) return 0; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; /* compute bytes to read -- error on overflow */ len = nitems * size; if (size && len / size != nitems) { gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t"); return 0; } /* write len bytes to buf, return the number of full items written */ return len ? gz_write(state, buf, len) / size : 0; } /* -- see zlib.h -- */ int ZEXPORT gzputc(file, c) gzFile file; int c; { unsigned have; unsigned char buf[1]; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return -1; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return -1; } /* try writing to input buffer for speed (state->size == 0 if buffer not initialized) */ if (state->size) { if (strm->avail_in == 0) strm->next_in = state->in; have = (unsigned)((strm->next_in + strm->avail_in) - state->in); if (have < state->size) { state->in[have] = (unsigned char)c; strm->avail_in++; state->x.pos++; return c & 0xff; } } /* no room in buffer or not initialized, use gz_write() */ buf[0] = (unsigned char)c; if (gz_write(state, buf, 1) != 1) return -1; return c & 0xff; } /* -- see zlib.h -- */ int ZEXPORT gzputs(file, str) gzFile file; const char *str; { int ret; z_size_t len; gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return -1; /* write string */ len = strlen(str); ret = gz_write(state, str, len); return ret == 0 && len != 0 ? -1 : ret; } #if defined(STDC) || defined(Z_HAVE_STDARG_H) #include <stdarg.h> /* -- see zlib.h -- */ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) { int len; unsigned left; char *next; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* make sure we have some buffer space */ if (state->size == 0 && gz_init(state) == -1) return state->err; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return state->err; } /* do the printf() into the input buffer, put length in len -- the input buffer is double-sized just for this function, so there is guaranteed to be state->size bytes available after the current contents */ if (strm->avail_in == 0) strm->next_in = state->in; next = (char *)(state->in + (strm->next_in - state->in) + strm->avail_in); next[state->size - 1] = 0; #ifdef NO_vsnprintf # ifdef HAS_vsprintf_void (void)vsprintf(next, format, va); for (len = 0; len < state->size; len++) if (next[len] == 0) break; # else len = vsprintf(next, format, va); # endif #else # ifdef HAS_vsnprintf_void (void)vsnprintf(next, state->size, format, va); len = strlen(next); # else len = vsnprintf(next, state->size, format, va); # endif #endif /* check that printf() results fit in buffer */ if (len == 0 || (unsigned)len >= state->size || next[state->size - 1] != 0) return 0; /* update buffer and position, compress first half if past that */ strm->avail_in += (unsigned)len; state->x.pos += len; if (strm->avail_in >= state->size) { left = strm->avail_in - state->size; strm->avail_in = state->size; if (gz_comp(state, Z_NO_FLUSH) == -1) return state->err; memcpy(state->in, state->in + state->size, left); strm->next_in = state->in; strm->avail_in = left; } return len; } int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) { va_list va; int ret; va_start(va, format); ret = gzvprintf(file, format, va); va_end(va); return ret; } #else /* !STDC && !Z_HAVE_STDARG_H */ /* -- see zlib.h -- */ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) gzFile file; const char *format; int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; { unsigned len, left; char *next; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; strm = &(state->strm); /* check that can really pass pointer in ints */ if (sizeof(int) != sizeof(void *)) return Z_STREAM_ERROR; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* make sure we have some buffer space */ if (state->size == 0 && gz_init(state) == -1) return state->error; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return state->error; } /* do the printf() into the input buffer, put length in len -- the input buffer is double-sized just for this function, so there is guaranteed to be state->size bytes available after the current contents */ if (strm->avail_in == 0) strm->next_in = state->in; next = (char *)(strm->next_in + strm->avail_in); next[state->size - 1] = 0; #ifdef NO_snprintf # ifdef HAS_sprintf_void sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); for (len = 0; len < size; len++) if (next[len] == 0) break; # else len = sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); # endif #else # ifdef HAS_snprintf_void snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); len = strlen(next); # else len = snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); # endif #endif /* check that printf() results fit in buffer */ if (len == 0 || len >= state->size || next[state->size - 1] != 0) return 0; /* update buffer and position, compress first half if past that */ strm->avail_in += len; state->x.pos += len; if (strm->avail_in >= state->size) { left = strm->avail_in - state->size; strm->avail_in = state->size; if (gz_comp(state, Z_NO_FLUSH) == -1) return state->err; memcpy(state->in, state->in + state->size, left); strm->next_in = state->in; strm->avail_in = left; } return (int)len; } #endif /* -- see zlib.h -- */ int ZEXPORT gzflush(file, flush) gzFile file; int flush; { gz_statep state; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* check flush parameter */ if (flush < 0 || flush > Z_FINISH) return Z_STREAM_ERROR; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return state->err; } /* compress remaining data with requested flush */ (void)gz_comp(state, flush); return state->err; } /* -- see zlib.h -- */ int ZEXPORT gzsetparams(file, level, strategy) gzFile file; int level; int strategy; { gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* if no change is requested, then do nothing */ if (level == state->level && strategy == state->strategy) return Z_OK; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return state->err; } /* change compression parameters for subsequent input */ if (state->size) { /* flush previous input with previous parameters before changing */ if (strm->avail_in && gz_comp(state, Z_BLOCK) == -1) return state->err; deflateParams(strm, level, strategy); } state->level = level; state->strategy = strategy; return Z_OK; } /* -- see zlib.h -- */ int ZEXPORT gzclose_w(file) gzFile file; { int ret = Z_OK; gz_statep state; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; /* check that we're writing */ if (state->mode != GZ_WRITE) return Z_STREAM_ERROR; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) ret = state->err; } /* flush, free memory, and close file */ if (gz_comp(state, Z_FINISH) == -1) ret = state->err; if (state->size) { if (!state->direct) { (void)deflateEnd(&(state->strm)); free(state->out); } free(state->in); } gz_error(state, Z_OK, NULL); free(state->path); if (close(state->fd) == -1) ret = Z_ERRNO; free(state); return ret; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
servers/audio/effects/audio_effect_compressor.cpp
227
#include "audio_effect_compressor.h" #include "servers/audio_server.h" void AudioEffectCompressorInstance::process(const AudioFrame *p_src_frames,AudioFrame *p_dst_frames,int p_frame_count) { float treshold = Math::db2linear(base->treshold); float sample_rate=AudioServer::get_singleton()->get_mix_rate(); float ratatcoef = exp(-1 / (0.00001f * sample_rate)); float ratrelcoef = exp(-1 / (0.5f * sample_rate)); float attime = base->attack_us / 1000000.0; float reltime = base->release_ms / 1000.0; float atcoef = exp(-1 / (attime * sample_rate)); float relcoef = exp(-1 / (reltime * sample_rate)); float makeup = Math::db2linear(base->gain); float mix = base->mix; float gr_meter_decay = exp(1 / (1 * sample_rate)); const AudioFrame *src = p_src_frames; if (base->sidechain!=StringName() && current_channel!=-1) { int bus = AudioServer::get_singleton()->thread_find_bus_index(base->sidechain); if (bus>=0) { src = AudioServer::get_singleton()->thread_get_channel_mix_buffer(bus,current_channel); } } for(int i=0;i<p_frame_count;i++) { AudioFrame s = src[i]; //convert to positive s.l = Math::abs(s.l); s.r = Math::abs(s.r); float peak = MAX(s.l,s.r); float overdb = 2.08136898f * Math::linear2db(peak/treshold); if (overdb<0.0) //we only care about what goes over to compress overdb=0.0; if(overdb-rundb>5) // diffeence is too large averatio = 4; if(overdb > rundb) { rundb = overdb + atcoef * (rundb - overdb); runratio = averatio + ratatcoef * (runratio - averatio); } else { rundb = overdb + relcoef * (rundb - overdb); runratio = averatio + ratrelcoef * (runratio - averatio); } overdb = rundb; averatio = runratio; float cratio; if(false) { //rato all-in cratio = 12 + averatio; } else { cratio = base->ratio; } float gr = -overdb * (cratio-1)/cratio; float grv = Math::db2linear(gr); runmax = maxover + relcoef * (runmax - maxover); // highest peak for setting att/rel decays in reltime maxover = runmax; if (grv < gr_meter) { gr_meter=grv; } else { gr_meter*=gr_meter_decay; if(gr_meter>1) gr_meter=1; } p_dst_frames[i] = p_src_frames[i] * grv * makeup * mix + p_src_frames[i] * (1.0-mix); } } Ref<AudioEffectInstance> AudioEffectCompressor::instance() { Ref<AudioEffectCompressorInstance> ins; ins.instance(); ins->base=Ref<AudioEffectCompressor>(this); ins->rundb=0; ins->runratio=0; ins->averatio=0; ins->runmax=0; ins->maxover=0; ins->gr_meter=1.0; ins->current_channel=-1; return ins; } void AudioEffectCompressor::set_treshold(float p_treshold) { treshold=p_treshold; } float AudioEffectCompressor::get_treshold() const { return treshold; } void AudioEffectCompressor::set_ratio(float p_ratio) { ratio=p_ratio; } float AudioEffectCompressor::get_ratio() const { return ratio; } void AudioEffectCompressor::set_gain(float p_gain) { gain=p_gain; } float AudioEffectCompressor::get_gain() const { return gain; } void AudioEffectCompressor::set_attack_us(float p_attack_us) { attack_us=p_attack_us; } float AudioEffectCompressor::get_attack_us() const { return attack_us; } void AudioEffectCompressor::set_release_ms(float p_release_ms) { release_ms=p_release_ms; } float AudioEffectCompressor::get_release_ms() const { return release_ms; } void AudioEffectCompressor::set_mix(float p_mix) { mix=p_mix; } float AudioEffectCompressor::get_mix() const { return mix; } void AudioEffectCompressor::set_sidechain(const StringName& p_sidechain) { AudioServer::get_singleton()->lock(); sidechain=p_sidechain; AudioServer::get_singleton()->unlock(); } StringName AudioEffectCompressor::get_sidechain() const { return sidechain; } void AudioEffectCompressor::_validate_property(PropertyInfo& property) const { if (property.name=="sidechain") { String buses=""; for(int i=0;i<AudioServer::get_singleton()->get_bus_count();i++) { buses+=","; buses+=AudioServer::get_singleton()->get_bus_name(i); } property.hint_string=buses; } } void AudioEffectCompressor::_bind_methods() { ClassDB::bind_method(_MD("set_treshold","treshold"),&AudioEffectCompressor::set_treshold); ClassDB::bind_method(_MD("get_treshold"),&AudioEffectCompressor::get_treshold); ClassDB::bind_method(_MD("set_ratio","ratio"),&AudioEffectCompressor::set_ratio); ClassDB::bind_method(_MD("get_ratio"),&AudioEffectCompressor::get_ratio); ClassDB::bind_method(_MD("set_gain","gain"),&AudioEffectCompressor::set_gain); ClassDB::bind_method(_MD("get_gain"),&AudioEffectCompressor::get_gain); ClassDB::bind_method(_MD("set_attack_us","attack_us"),&AudioEffectCompressor::set_attack_us); ClassDB::bind_method(_MD("get_attack_us"),&AudioEffectCompressor::get_attack_us); ClassDB::bind_method(_MD("set_release_ms","release_ms"),&AudioEffectCompressor::set_release_ms); ClassDB::bind_method(_MD("get_release_ms"),&AudioEffectCompressor::get_release_ms); ClassDB::bind_method(_MD("set_mix","mix"),&AudioEffectCompressor::set_mix); ClassDB::bind_method(_MD("get_mix"),&AudioEffectCompressor::get_mix); ClassDB::bind_method(_MD("set_sidechain","sidechain"),&AudioEffectCompressor::set_sidechain); ClassDB::bind_method(_MD("get_sidechain"),&AudioEffectCompressor::get_sidechain); ADD_PROPERTY(PropertyInfo(Variant::REAL,"treshold",PROPERTY_HINT_RANGE,"-60,0,0.1"),_SCS("set_treshold"),_SCS("get_treshold")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"ratio",PROPERTY_HINT_RANGE,"1,48,0.1"),_SCS("set_ratio"),_SCS("get_ratio")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"gain",PROPERTY_HINT_RANGE,"-20,20,0.1"),_SCS("set_gain"),_SCS("get_gain")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"attack_us",PROPERTY_HINT_RANGE,"20,2000,1"),_SCS("set_attack_us"),_SCS("get_attack_us")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"release_ms",PROPERTY_HINT_RANGE,"20,2000,1"),_SCS("set_release_ms"),_SCS("get_release_ms")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"mix",PROPERTY_HINT_RANGE,"0,1,0.01"),_SCS("set_mix"),_SCS("get_mix")); ADD_PROPERTY(PropertyInfo(Variant::REAL,"sidechain",PROPERTY_HINT_ENUM),_SCS("set_sidechain"),_SCS("get_sidechain")); } AudioEffectCompressor::AudioEffectCompressor() { treshold=0; ratio=4; gain=0; attack_us=20; release_ms=250; mix=1; }
godotengine_godot
2017-01-27
7a85d25218971506058a992d21821b47e153ec78
ext/misc/sha1.c
399
/* ** 2017-01-27 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This SQLite extension implements a functions that compute SHA1 hashes. ** Two SQL functions are implemented: ** ** sha1(X) ** sha1_query(Y) ** ** The sha1(X) function computes the SHA1 hash of the input X, or NULL if ** X is NULL. ** ** The sha1_query(Y) function evalutes all queries in the SQL statements of Y ** and returns a hash of their results. */ #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #include <assert.h> #include <string.h> #include <stdarg.h> /****************************************************************************** ** The Hash Engine */ /* Context for the SHA1 hash */ typedef struct SHA1Context SHA1Context; struct SHA1Context { unsigned int state[5]; unsigned int count[2]; unsigned char buffer[64]; }; #if __GNUC__ && (defined(__i386__) || defined(__x86_64__)) /* * GCC by itself only generates left rotates. Use right rotates if * possible to be kinder to dinky implementations with iterative rotate * instructions. */ #define SHA_ROT(op, x, k) \ ({ unsigned int y; asm(op " %1,%0" : "=r" (y) : "I" (k), "0" (x)); y; }) #define rol(x,k) SHA_ROT("roll", x, k) #define ror(x,k) SHA_ROT("rorl", x, k) #else /* Generic C equivalent */ #define SHA_ROT(x,l,r) ((x) << (l) | (x) >> (r)) #define rol(x,k) SHA_ROT(x,k,32-(k)) #define ror(x,k) SHA_ROT(x,32-(k),k) #endif #define blk0le(i) (block[i] = (ror(block[i],8)&0xFF00FF00) \ |(rol(block[i],8)&0x00FF00FF)) #define blk0be(i) block[i] #define blk(i) (block[i&15] = rol(block[(i+13)&15]^block[(i+8)&15] \ ^block[(i+2)&15]^block[i&15],1)) /* * (R0+R1), R2, R3, R4 are the different operations (rounds) used in SHA1 * * Rl0() for little-endian and Rb0() for big-endian. Endianness is * determined at run-time. */ #define Rl0(v,w,x,y,z,i) \ z+=((w&(x^y))^y)+blk0le(i)+0x5A827999+rol(v,5);w=ror(w,2); #define Rb0(v,w,x,y,z,i) \ z+=((w&(x^y))^y)+blk0be(i)+0x5A827999+rol(v,5);w=ror(w,2); #define R1(v,w,x,y,z,i) \ z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=ror(w,2); #define R2(v,w,x,y,z,i) \ z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=ror(w,2); #define R3(v,w,x,y,z,i) \ z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=ror(w,2); #define R4(v,w,x,y,z,i) \ z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=ror(w,2); /* * Hash a single 512-bit block. This is the core of the algorithm. */ #define a qq[0] #define b qq[1] #define c qq[2] #define d qq[3] #define e qq[4] void SHA1Transform(unsigned int state[5], const unsigned char buffer[64]){ unsigned int qq[5]; /* a, b, c, d, e; */ static int one = 1; unsigned int block[16]; memcpy(block, buffer, 64); memcpy(qq,state,5*sizeof(unsigned int)); /* Copy p->state[] to working vars */ /* a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; */ /* 4 rounds of 20 operations each. Loop unrolled. */ if( 1 == *(unsigned char*)&one ){ Rl0(a,b,c,d,e, 0); Rl0(e,a,b,c,d, 1); Rl0(d,e,a,b,c, 2); Rl0(c,d,e,a,b, 3); Rl0(b,c,d,e,a, 4); Rl0(a,b,c,d,e, 5); Rl0(e,a,b,c,d, 6); Rl0(d,e,a,b,c, 7); Rl0(c,d,e,a,b, 8); Rl0(b,c,d,e,a, 9); Rl0(a,b,c,d,e,10); Rl0(e,a,b,c,d,11); Rl0(d,e,a,b,c,12); Rl0(c,d,e,a,b,13); Rl0(b,c,d,e,a,14); Rl0(a,b,c,d,e,15); }else{ Rb0(a,b,c,d,e, 0); Rb0(e,a,b,c,d, 1); Rb0(d,e,a,b,c, 2); Rb0(c,d,e,a,b, 3); Rb0(b,c,d,e,a, 4); Rb0(a,b,c,d,e, 5); Rb0(e,a,b,c,d, 6); Rb0(d,e,a,b,c, 7); Rb0(c,d,e,a,b, 8); Rb0(b,c,d,e,a, 9); Rb0(a,b,c,d,e,10); Rb0(e,a,b,c,d,11); Rb0(d,e,a,b,c,12); Rb0(c,d,e,a,b,13); Rb0(b,c,d,e,a,14); Rb0(a,b,c,d,e,15); } R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; } /* Initialize a SHA1 context */ static void hash_init(SHA1Context *p){ /* SHA1 initialization constants */ p->state[0] = 0x67452301; p->state[1] = 0xEFCDAB89; p->state[2] = 0x98BADCFE; p->state[3] = 0x10325476; p->state[4] = 0xC3D2E1F0; p->count[0] = p->count[1] = 0; } /* Add new content to the SHA1 hash */ static void hash_step( SHA1Context *p, /* Add content to this context */ const unsigned char *data, /* Data to be added */ unsigned int len /* Number of bytes in data */ ){ unsigned int i, j; j = p->count[0]; if( (p->count[0] += len << 3) < j ){ p->count[1] += (len>>29)+1; } j = (j >> 3) & 63; if( (j + len) > 63 ){ (void)memcpy(&p->buffer[j], data, (i = 64-j)); SHA1Transform(p->state, p->buffer); for(; i + 63 < len; i += 64){ SHA1Transform(p->state, &data[i]); } j = 0; }else{ i = 0; } (void)memcpy(&p->buffer[j], &data[i], len - i); } /* Compute a string using sqlite3_vsnprintf() and hash it */ static void hash_step_vformat( SHA1Context *p, /* Add content to this context */ const char *zFormat, ... ){ va_list ap; int n; char zBuf[50]; va_start(ap, zFormat); sqlite3_vsnprintf(sizeof(zBuf),zBuf,zFormat,ap); va_end(ap); n = (int)strlen(zBuf); hash_step(p, (unsigned char*)zBuf, n); } /* Add padding and compute the message digest. Render the ** message digest as lower-case hexadecimal and put it into ** zOut[]. zOut[] must be at least 41 bytes long. */ static void hash_finish( SHA1Context *p, /* The SHA1 context to finish and render */ char *zOut /* Store hexadecimal hash here */ ){ unsigned int i; unsigned char finalcount[8]; unsigned char digest[20]; static const char zEncode[] = "0123456789abcdef"; for (i = 0; i < 8; i++){ finalcount[i] = (unsigned char)((p->count[(i >= 4 ? 0 : 1)] >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ } hash_step(p, (const unsigned char *)"\200", 1); while ((p->count[0] & 504) != 448){ hash_step(p, (const unsigned char *)"\0", 1); } hash_step(p, finalcount, 8); /* Should cause a SHA1Transform() */ for (i = 0; i < 20; i++){ digest[i] = (unsigned char)((p->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); } for(i=0; i<20; i++){ zOut[i*2] = zEncode[(digest[i]>>4)&0xf]; zOut[i*2+1] = zEncode[digest[i] & 0xf]; } zOut[i*2]= 0; } /* End of the hashing logic *****************************************************************************/ /* ** Implementation of the sha1(X) function. ** ** Return a lower-case hexadecimal rendering of the SHA1 hash of the ** argument X. If X is a BLOB, it is hashed as is. For all other ** types of input, X is converted into a UTF-8 string and the string ** is hash without the trailing 0x00 terminator. The hash of a NULL ** value is NULL. */ static void sha1Func( sqlite3_context *context, int argc, sqlite3_value **argv ){ SHA1Context cx; int eType = sqlite3_value_type(argv[0]); int nByte = sqlite3_value_bytes(argv[0]); char zOut[44]; if( eType==SQLITE_NULL ) return; hash_init(&cx); if( eType==SQLITE_BLOB ){ hash_step(&cx, sqlite3_value_blob(argv[0]), nByte); }else{ hash_step(&cx, sqlite3_value_text(argv[0]), nByte); } hash_finish(&cx, zOut); sqlite3_result_text(context, zOut, 40, SQLITE_TRANSIENT); } /* ** Implementation of the sha1_query(SQL) function. ** ** This function compiles and runs the SQL statement(s) given in the ** argument. The results are hashed using SHA1 and that hash is returned. ** ** The original SQL text is included as part of the hash. ** ** The hash is not just a concatenation of the outputs. Each query ** is delimited and each row and value within the query is delimited, ** with all values being marked with their datatypes. */ static void sha1QueryFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ sqlite3 *db = sqlite3_context_db_handle(context); const char *zSql = (const char*)sqlite3_value_text(argv[0]); sqlite3_stmt *pStmt = 0; int nCol; /* Number of columns in the result set */ int i; /* Loop counter */ int rc; int n; const char *z; SHA1Context cx; char zOut[44]; if( zSql==0 ) return; hash_init(&cx); while( zSql[0] ){ rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zSql); if( rc ){ char *zMsg = sqlite3_mprintf("error SQL statement [%s]: %s", zSql, sqlite3_errmsg(db)); sqlite3_finalize(pStmt); sqlite3_result_error(context, zMsg, -1); sqlite3_free(zMsg); return; } if( !sqlite3_stmt_readonly(pStmt) ){ char *zMsg = sqlite3_mprintf("non-query: [%s]", sqlite3_sql(pStmt)); sqlite3_finalize(pStmt); sqlite3_result_error(context, zMsg, -1); sqlite3_free(zMsg); return; } nCol = sqlite3_column_count(pStmt); z = sqlite3_sql(pStmt); n = (int)strlen(z); hash_step_vformat(&cx,"S%d:",n); hash_step(&cx,(unsigned char*)z,n); /* Compute a hash over the result of the query */ while( SQLITE_ROW==sqlite3_step(pStmt) ){ hash_step(&cx,(const unsigned char*)"R",1); for(i=0; i<nCol; i++){ switch( sqlite3_column_type(pStmt,i) ){ case SQLITE_NULL: { hash_step(&cx, (const unsigned char*)"N",1); break; } case SQLITE_INTEGER: { sqlite3_uint64 u; int j; unsigned char x[9]; sqlite3_int64 v = sqlite3_column_int64(pStmt,i); memcpy(&u, &v, 8); for(j=8; j>=1; j--){ x[j] = u & 0xff; u >>= 8; } x[0] = 'I'; hash_step(&cx, x, 9); break; } case SQLITE_FLOAT: { sqlite3_uint64 u; int j; unsigned char x[8]; double r = sqlite3_column_double(pStmt,i); memcpy(&u, &r, 8); for(j=8; j>=1; j--){ x[j] = u & 0xff; u >>= 8; } x[0] = 'F'; hash_step(&cx,x,9); break; } case SQLITE_TEXT: { int n = sqlite3_column_bytes(pStmt, i); const unsigned char *z = sqlite3_column_text(pStmt, i); hash_step_vformat(&cx,"T%d:",n); hash_step(&cx, z, n); break; } case SQLITE_BLOB: { int n = sqlite3_column_bytes(pStmt, i); const unsigned char *z = sqlite3_column_blob(pStmt, i); hash_step_vformat(&cx,"B%d:",n); hash_step(&cx, z, n); break; } } } } sqlite3_finalize(pStmt); } hash_finish(&cx, zOut); sqlite3_result_text(context, zOut, 40, SQLITE_TRANSIENT); } #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_sha_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ int rc = SQLITE_OK; SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ rc = sqlite3_create_function(db, "sha1", 1, SQLITE_UTF8, 0, sha1Func, 0, 0); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "sha1_query", 1, SQLITE_UTF8, 0, sha1QueryFunc, 0, 0); } return rc; }
sqlite_sqlite
2017-01-28
2d2e4f389584fec0b27100107b18bb835ddeba94
test/wordcount.c
284
/* ** This C program extracts all "words" from an input document and adds them ** to an SQLite database. A "word" is any contiguous sequence of alphabetic ** characters. All digits, punctuation, and whitespace characters are ** word separators. The database stores a single entry for each distinct ** word together with a count of the number of occurrences of that word. ** A fresh database is created automatically on each run. ** ** wordcount DATABASE INPUTFILE ** ** The INPUTFILE name can be omitted, in which case input it taken from ** standard input. ** ** Option: ** ** ** Modes: ** ** Insert mode means: ** (1) INSERT OR IGNORE INTO wordcount VALUES($new,1) ** (2) UPDATE wordcount SET cnt=cnt+1 WHERE word=$new -- if (1) is a noop ** ** Update mode means: ** (1) INSERT OR IGNORE INTO wordcount VALUES($new,0) ** (2) UPDATE wordcount SET cnt=cnt+1 WHERE word=$new ** ** Replace mode means: ** (1) REPLACE INTO wordcount ** VALUES($new,ifnull((SELECT cnt FROM wordcount WHERE word=$new),0)+1); ** ** Select mode means: ** (1) SELECT 1 FROM wordcount WHERE word=$new ** (2) INSERT INTO wordcount VALUES($new,1) -- if (1) returns nothing ** (3) UPDATE wordcount SET cnt=cnt+1 WHERE word=$new --if (1) return TRUE ** ** Delete mode means: ** (1) DELETE FROM wordcount WHERE word=$new ** ** Query mode means: ** (1) SELECT cnt FROM wordcount WHERE word=$new ** ** Note that delete mode and query mode are only useful for preexisting ** databases. The wordcount table is created using IF NOT EXISTS so this ** utility can be run multiple times on the same database file. The ** --without-rowid, --nocase, and --pagesize parameters are only effective ** when creating a new database and are harmless no-ops on preexisting ** databases. ** ****************************************************************************** ** ** Compile as follows: ** ** gcc -I. wordcount.c sqlite3.c -ldl -lpthreads ** ** Or: ** ** gcc -I. -DSQLITE_THREADSAFE=0 -DSQLITE_OMIT_LOAD_EXTENSION \ ** wordcount.c sqlite3.c */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdarg.h> #include "sqlite3.h" #ifndef _WIN32 # include <unistd.h> #else # include <io.h> #endif #define ISALPHA(X) isalpha((unsigned char)(X)) const char zHelp[] = "Usage: wordcount [OPTIONS] DATABASE [INPUT]\n" " --all Repeat the test for all test modes\n" " --cachesize NNN Use a cache size of NNN\n" " --commit NNN Commit after every NNN operations\n" " --delete Use DELETE mode\n" " --insert Use INSERT mode (the default)\n" " --journal MMMM Use PRAGMA journal_mode=MMMM\n" " --nocase Add the NOCASE collating sequence to the words.\n" " --nosync Use PRAGMA synchronous=OFF\n" " --pagesize NNN Use a page size of NNN\n" " --query Use QUERY mode\n" " --replace Use REPLACE mode\n" " --select Use SELECT mode\n" " --stats Show sqlite3_status() results at the end.\n" " --summary Show summary information on the collected data.\n" " --tag NAME Tag all output using NAME. Use only stdout.\n" " --timer Time the operation of this program\n" " --trace Enable sqlite3_trace() output.\n" " --update Use UPDATE mode\n" " --without-rowid Use a WITHOUT ROWID table to store the words.\n" ; /* Output tag */ char *zTag = "--"; /* Return the current wall-clock time */ static sqlite3_int64 realTime(void){ static sqlite3_vfs *clockVfs = 0; sqlite3_int64 t; if( clockVfs==0 ) clockVfs = sqlite3_vfs_find(0); if( clockVfs->iVersion>=1 && clockVfs->xCurrentTimeInt64!=0 ){ clockVfs->xCurrentTimeInt64(clockVfs, &t); }else{ double r; clockVfs->xCurrentTime(clockVfs, &r); t = (sqlite3_int64)(r*86400000.0); } return t; } /* Print an error message and exit */ static void fatal_error(const char *zMsg, ...){ va_list ap; va_start(ap, zMsg); vfprintf(stderr, zMsg, ap); va_end(ap); exit(1); } /* Print a usage message and quit */ static void usage(void){ printf("%s",zHelp); exit(0); } /* The sqlite3_trace() callback function */ static void traceCallback(void *NotUsed, const char *zSql){ printf("%s;\n", zSql); } /* An sqlite3_exec() callback that prints results on standard output, ** each column separated by a single space. */ static int printResult(void *NotUsed, int nArg, char **azArg, char **azNm){ int i; printf("%s", zTag); for(i=0; i<nArg; i++){ printf(" %s", azArg[i] ? azArg[i] : "(null)"); } printf("\n"); return 0; } /* ** Add one character to a hash */ static void addCharToHash(unsigned int *a, unsigned char x){ if( a[0]<4 ){ a[1] = (a[1]<<8) | x; a[0]++; }else{ a[2] = (a[2]<<8) | x; a[0]++; if( a[0]==8 ){ a[3] += a[1] + a[4]; a[4] += a[2] + a[3]; a[0] = a[1] = a[2] = 0; } } } /* ** Compute the final hash value. */ static void finalHash(unsigned int *a, char *z){ a[3] += a[1] + a[4] + a[0]; a[4] += a[2] + a[3]; sqlite3_snprintf(17, z, "%08x%08x", a[3], a[4]); } /* ** Implementation of a checksum() aggregate SQL function */ static void checksumStep( sqlite3_context *context, int argc, sqlite3_value **argv ){ const unsigned char *zVal; int nVal, i, j; unsigned int *a; a = (unsigned*)sqlite3_aggregate_context(context, sizeof(unsigned int)*5); if( a ){ for(i=0; i<argc; i++){ nVal = sqlite3_value_bytes(argv[i]); zVal = (const unsigned char*)sqlite3_value_text(argv[i]); if( zVal ) for(j=0; j<nVal; j++) addCharToHash(a, zVal[j]); addCharToHash(a, '|'); } addCharToHash(a, '\n'); } } static void checksumFinalize(sqlite3_context *context){ unsigned int *a; char zResult[24]; a = sqlite3_aggregate_context(context, 0); if( a ){ finalHash(a, zResult); sqlite3_result_text(context, zResult, -1, SQLITE_TRANSIENT); } } /* Define operating modes */ #define MODE_INSERT 0 #define MODE_REPLACE 1 #define MODE_SELECT 2 #define MODE_UPDATE 3 #define MODE_DELETE 4 #define MODE_QUERY 5 #define MODE_COUNT 6 #define MODE_ALL (-1) /* Mode names */ static const char *azMode[] = { "--insert", "--replace", "--select", "--update", "--delete", "--query" }; /* ** Determine if another iteration of the test is required. Return true ** if so. Return zero if all iterations have finished. */ static int allLoop( int iMode, /* The selected test mode */ int *piLoopCnt, /* Iteration loop counter */ int *piMode2, /* The test mode to use on the next iteration */ int *pUseWithoutRowid /* Whether or not to use --without-rowid */ ){ int i; if( iMode!=MODE_ALL ){ if( *piLoopCnt ) return 0; *piMode2 = iMode; *piLoopCnt = 1; return 1; } if( (*piLoopCnt)>=MODE_COUNT*2 ) return 0; i = (*piLoopCnt)++; *pUseWithoutRowid = i&1; *piMode2 = i>>1; return 1; } int main(int argc, char **argv){ const char *zFileToRead = 0; /* Input file. NULL for stdin */ const char *zDbName = 0; /* Name of the database file to create */ int useWithoutRowid = 0; /* True for --without-rowid */ int iMode = MODE_INSERT; /* One of MODE_xxxxx */ int iMode2; /* Mode to use for current --all iteration */ int iLoopCnt = 0; /* Which iteration when running --all */ int useNocase = 0; /* True for --nocase */ int doTrace = 0; /* True for --trace */ int showStats = 0; /* True for --stats */ int showSummary = 0; /* True for --summary */ int showTimer = 0; /* True for --timer */ int cacheSize = 0; /* Desired cache size. 0 means default */ int pageSize = 0; /* Desired page size. 0 means default */ int commitInterval = 0; /* How often to commit. 0 means never */ int noSync = 0; /* True for --nosync */ const char *zJMode = 0; /* Journal mode */ int nOp = 0; /* Operation counter */ int i, j; /* Loop counters */ sqlite3 *db; /* The SQLite database connection */ char *zSql; /* Constructed SQL statement */ sqlite3_stmt *pInsert = 0; /* The INSERT statement */ sqlite3_stmt *pUpdate = 0; /* The UPDATE statement */ sqlite3_stmt *pSelect = 0; /* The SELECT statement */ sqlite3_stmt *pDelete = 0; /* The DELETE statement */ FILE *in; /* The open input file */ int rc; /* Return code from an SQLite interface */ int iCur, iHiwtr; /* Statistics values, current and "highwater" */ FILE *pTimer = stderr; /* Output channel for the timer */ sqlite3_int64 sumCnt = 0; /* Sum in QUERY mode */ sqlite3_int64 startTime; /* Time of start */ sqlite3_int64 totalTime = 0; /* Total time */ char zInput[2000]; /* A single line of input */ /* Process command-line arguments */ for(i=1; i<argc; i++){ const char *z = argv[i]; if( z[0]=='-' ){ do{ z++; }while( z[0]=='-' ); if( strcmp(z,"without-rowid")==0 ){ useWithoutRowid = 1; }else if( strcmp(z,"replace")==0 ){ iMode = MODE_REPLACE; }else if( strcmp(z,"select")==0 ){ iMode = MODE_SELECT; }else if( strcmp(z,"insert")==0 ){ iMode = MODE_INSERT; }else if( strcmp(z,"update")==0 ){ iMode = MODE_UPDATE; }else if( strcmp(z,"delete")==0 ){ iMode = MODE_DELETE; }else if( strcmp(z,"query")==0 ){ iMode = MODE_QUERY; }else if( strcmp(z,"all")==0 ){ iMode = MODE_ALL; showTimer = -99; }else if( strcmp(z,"nocase")==0 ){ useNocase = 1; }else if( strcmp(z,"trace")==0 ){ doTrace = 1; }else if( strcmp(z,"nosync")==0 ){ noSync = 1; }else if( strcmp(z,"stats")==0 ){ showStats = 1; }else if( strcmp(z,"summary")==0 ){ showSummary = 1; }else if( strcmp(z,"timer")==0 ){ showTimer = i; }else if( strcmp(z,"cachesize")==0 && i<argc-1 ){ i++; cacheSize = atoi(argv[i]); }else if( strcmp(z,"pagesize")==0 && i<argc-1 ){ i++; pageSize = atoi(argv[i]); }else if( strcmp(z,"commit")==0 && i<argc-1 ){ i++; commitInterval = atoi(argv[i]); }else if( strcmp(z,"journal")==0 && i<argc-1 ){ zJMode = argv[++i]; }else if( strcmp(z,"tag")==0 && i<argc-1 ){ zTag = argv[++i]; pTimer = stdout; }else if( strcmp(z, "help")==0 || strcmp(z,"?")==0 ){ usage(); }else{ fatal_error("unknown option: \"%s\"\n" "Use --help for a list of options\n", argv[i]); } }else if( zDbName==0 ){ zDbName = argv[i]; }else if( zFileToRead==0 ){ zFileToRead = argv[i]; }else{ fatal_error("surplus argument: \"%s\"\n", argv[i]); } } if( zDbName==0 ){ usage(); } startTime = realTime(); /* Open the database and the input file */ if( zDbName[0] && strcmp(zDbName,":memory:")!=0 ){ unlink(zDbName); } if( sqlite3_open(zDbName, &db) ){ fatal_error("Cannot open database file: %s\n", zDbName); } if( zFileToRead ){ in = fopen(zFileToRead, "rb"); if( in==0 ){ fatal_error("Could not open input file \"%s\"\n", zFileToRead); } }else{ if( iMode==MODE_ALL ){ fatal_error("The --all mode cannot be used with stdin\n"); } in = stdin; } /* Set database connection options */ if( doTrace ) sqlite3_trace(db, traceCallback, 0); if( pageSize ){ zSql = sqlite3_mprintf("PRAGMA page_size=%d", pageSize); sqlite3_exec(db, zSql, 0, 0, 0); sqlite3_free(zSql); } if( cacheSize ){ zSql = sqlite3_mprintf("PRAGMA cache_size=%d", cacheSize); sqlite3_exec(db, zSql, 0, 0, 0); sqlite3_free(zSql); } if( noSync ) sqlite3_exec(db, "PRAGMA synchronous=OFF", 0, 0, 0); if( zJMode ){ zSql = sqlite3_mprintf("PRAGMA journal_mode=%s", zJMode); sqlite3_exec(db, zSql, 0, 0, 0); sqlite3_free(zSql); } iLoopCnt = 0; while( allLoop(iMode, &iLoopCnt, &iMode2, &useWithoutRowid) ){ /* Delete prior content in --all mode */ if( iMode==MODE_ALL ){ if( sqlite3_exec(db, "DROP TABLE IF EXISTS wordcount; VACUUM;",0,0,0) ){ fatal_error("Could not clean up prior iteration\n"); } startTime = realTime(); rewind(in); } /* Construct the "wordcount" table into which to put the words */ if( sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, 0) ){ fatal_error("Could not start a transaction\n"); } zSql = sqlite3_mprintf( "CREATE TABLE IF NOT EXISTS wordcount(\n" " word TEXT PRIMARY KEY COLLATE %s,\n" " cnt INTEGER\n" ")%s", useNocase ? "nocase" : "binary", useWithoutRowid ? " WITHOUT ROWID" : "" ); if( zSql==0 ) fatal_error("out of memory\n"); rc = sqlite3_exec(db, zSql, 0, 0, 0); if( rc ) fatal_error("Could not create the wordcount table: %s.\n", sqlite3_errmsg(db)); sqlite3_free(zSql); /* Prepare SQL statements that will be needed */ if( iMode2==MODE_QUERY ){ rc = sqlite3_prepare_v2(db, "SELECT cnt FROM wordcount WHERE word=?1", -1, &pSelect, 0); if( rc ) fatal_error("Could not prepare the SELECT statement: %s\n", sqlite3_errmsg(db)); } if( iMode2==MODE_SELECT ){ rc = sqlite3_prepare_v2(db, "SELECT 1 FROM wordcount WHERE word=?1", -1, &pSelect, 0); if( rc ) fatal_error("Could not prepare the SELECT statement: %s\n", sqlite3_errmsg(db)); rc = sqlite3_prepare_v2(db, "INSERT INTO wordcount(word,cnt) VALUES(?1,1)", -1, &pInsert, 0); if( rc ) fatal_error("Could not prepare the INSERT statement: %s\n", sqlite3_errmsg(db)); } if( iMode2==MODE_SELECT || iMode2==MODE_UPDATE || iMode2==MODE_INSERT ){ rc = sqlite3_prepare_v2(db, "UPDATE wordcount SET cnt=cnt+1 WHERE word=?1", -1, &pUpdate, 0); if( rc ) fatal_error("Could not prepare the UPDATE statement: %s\n", sqlite3_errmsg(db)); } if( iMode2==MODE_INSERT ){ rc = sqlite3_prepare_v2(db, "INSERT OR IGNORE INTO wordcount(word,cnt) VALUES(?1,1)", -1, &pInsert, 0); if( rc ) fatal_error("Could not prepare the INSERT statement: %s\n", sqlite3_errmsg(db)); } if( iMode2==MODE_UPDATE ){ rc = sqlite3_prepare_v2(db, "INSERT OR IGNORE INTO wordcount(word,cnt) VALUES(?1,0)", -1, &pInsert, 0); if( rc ) fatal_error("Could not prepare the INSERT statement: %s\n", sqlite3_errmsg(db)); } if( iMode2==MODE_REPLACE ){ rc = sqlite3_prepare_v2(db, "REPLACE INTO wordcount(word,cnt)" "VALUES(?1,coalesce((SELECT cnt FROM wordcount WHERE word=?1),0)+1)", -1, &pInsert, 0); if( rc ) fatal_error("Could not prepare the REPLACE statement: %s\n", sqlite3_errmsg(db)); } if( iMode2==MODE_DELETE ){ rc = sqlite3_prepare_v2(db, "DELETE FROM wordcount WHERE word=?1", -1, &pDelete, 0); if( rc ) fatal_error("Could not prepare the DELETE statement: %s\n", sqlite3_errmsg(db)); } /* Process the input file */ while( fgets(zInput, sizeof(zInput), in) ){ for(i=0; zInput[i]; i++){ if( !ISALPHA(zInput[i]) ) continue; for(j=i+1; ISALPHA(zInput[j]); j++){} /* Found a new word at zInput[i] that is j-i bytes long. ** Process it into the wordcount table. */ if( iMode2==MODE_DELETE ){ sqlite3_bind_text(pDelete, 1, zInput+i, j-i, SQLITE_STATIC); if( sqlite3_step(pDelete)!=SQLITE_DONE ){ fatal_error("DELETE failed: %s\n", sqlite3_errmsg(db)); } sqlite3_reset(pDelete); }else if( iMode2==MODE_SELECT ){ sqlite3_bind_text(pSelect, 1, zInput+i, j-i, SQLITE_STATIC); rc = sqlite3_step(pSelect); sqlite3_reset(pSelect); if( rc==SQLITE_ROW ){ sqlite3_bind_text(pUpdate, 1, zInput+i, j-i, SQLITE_STATIC); if( sqlite3_step(pUpdate)!=SQLITE_DONE ){ fatal_error("UPDATE failed: %s\n", sqlite3_errmsg(db)); } sqlite3_reset(pUpdate); }else if( rc==SQLITE_DONE ){ sqlite3_bind_text(pInsert, 1, zInput+i, j-i, SQLITE_STATIC); if( sqlite3_step(pInsert)!=SQLITE_DONE ){ fatal_error("Insert failed: %s\n", sqlite3_errmsg(db)); } sqlite3_reset(pInsert); }else{ fatal_error("SELECT failed: %s\n", sqlite3_errmsg(db)); } }else if( iMode2==MODE_QUERY ){ sqlite3_bind_text(pSelect, 1, zInput+i, j-i, SQLITE_STATIC); if( sqlite3_step(pSelect)==SQLITE_ROW ){ sumCnt += sqlite3_column_int64(pSelect, 0); } sqlite3_reset(pSelect); }else{ sqlite3_bind_text(pInsert, 1, zInput+i, j-i, SQLITE_STATIC); if( sqlite3_step(pInsert)!=SQLITE_DONE ){ fatal_error("INSERT failed: %s\n", sqlite3_errmsg(db)); } sqlite3_reset(pInsert); if( iMode2==MODE_UPDATE || (iMode2==MODE_INSERT && sqlite3_changes(db)==0) ){ sqlite3_bind_text(pUpdate, 1, zInput+i, j-i, SQLITE_STATIC); if( sqlite3_step(pUpdate)!=SQLITE_DONE ){ fatal_error("UPDATE failed: %s\n", sqlite3_errmsg(db)); } sqlite3_reset(pUpdate); } } i = j-1; /* Increment the operation counter. Do a COMMIT if it is time. */ nOp++; if( commitInterval>0 && (nOp%commitInterval)==0 ){ sqlite3_exec(db, "COMMIT; BEGIN IMMEDIATE", 0, 0, 0); } } } sqlite3_exec(db, "COMMIT", 0, 0, 0); sqlite3_finalize(pInsert); pInsert = 0; sqlite3_finalize(pUpdate); pUpdate = 0; sqlite3_finalize(pSelect); pSelect = 0; sqlite3_finalize(pDelete); pDelete = 0; if( iMode2==MODE_QUERY && iMode!=MODE_ALL ){ printf("%s sum of cnt: %lld\n", zTag, sumCnt); rc = sqlite3_prepare_v2(db,"SELECT sum(cnt*cnt) FROM wordcount", -1, &pSelect, 0); if( rc==SQLITE_OK && sqlite3_step(pSelect)==SQLITE_ROW ){ printf("%s double-check: %lld\n", zTag,sqlite3_column_int64(pSelect,0)); } sqlite3_finalize(pSelect); } if( showTimer ){ sqlite3_int64 elapseTime = realTime() - startTime; totalTime += elapseTime; fprintf(pTimer, "%3d.%03d wordcount", (int)(elapseTime/1000), (int)(elapseTime%1000)); if( iMode==MODE_ALL ){ fprintf(pTimer, " %s%s\n", azMode[iMode2], useWithoutRowid? " --without-rowid" : ""); }else{ for(i=1; i<argc; i++) if( i!=showTimer ) fprintf(pTimer," %s",argv[i]); fprintf(pTimer, "\n"); } } if( showSummary ){ sqlite3_create_function(db, "checksum", -1, SQLITE_UTF8, 0, 0, checksumStep, checksumFinalize); sqlite3_exec(db, "SELECT 'count(*): ', count(*) FROM wordcount;\n" "SELECT 'sum(cnt): ', sum(cnt) FROM wordcount;\n" "SELECT 'max(cnt): ', max(cnt) FROM wordcount;\n" "SELECT 'avg(cnt): ', avg(cnt) FROM wordcount;\n" "SELECT 'sum(cnt=1):', sum(cnt=1) FROM wordcount;\n" "SELECT 'top 10: ', group_concat(word, ', ') FROM " "(SELECT word FROM wordcount ORDER BY cnt DESC, word LIMIT 10);\n" "SELECT 'checksum: ', checksum(word, cnt) FROM " "(SELECT word, cnt FROM wordcount ORDER BY word);\n" "PRAGMA integrity_check;\n", printResult, 0, 0); } } /* End the --all loop */ /* Close the input file after the last read */ if( zFileToRead ) fclose(in); /* In --all mode, so the total time */ if( iMode==MODE_ALL && showTimer ){ fprintf(pTimer, "%3d.%03d wordcount --all\n", (int)(totalTime/1000), (int)(totalTime%1000)); } /* Database connection statistics printed after both prepared statements ** have been finalized */ if( showStats ){ sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_USED, &iCur, &iHiwtr, 0); printf("%s Lookaside Slots Used: %d (max %d)\n", zTag, iCur,iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_HIT, &iCur, &iHiwtr, 0); printf("%s Successful lookasides: %d\n", zTag, iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE, &iCur,&iHiwtr,0); printf("%s Lookaside size faults: %d\n", zTag, iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL, &iCur,&iHiwtr,0); printf("%s Lookaside OOM faults: %d\n", zTag, iHiwtr); sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_USED, &iCur, &iHiwtr, 0); printf("%s Pager Heap Usage: %d bytes\n", zTag, iCur); sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_HIT, &iCur, &iHiwtr, 1); printf("%s Page cache hits: %d\n", zTag, iCur); sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_MISS, &iCur, &iHiwtr, 1); printf("%s Page cache misses: %d\n", zTag, iCur); sqlite3_db_status(db, SQLITE_DBSTATUS_CACHE_WRITE, &iCur, &iHiwtr, 1); printf("%s Page cache writes: %d\n", zTag, iCur); sqlite3_db_status(db, SQLITE_DBSTATUS_SCHEMA_USED, &iCur, &iHiwtr, 0); printf("%s Schema Heap Usage: %d bytes\n", zTag, iCur); sqlite3_db_status(db, SQLITE_DBSTATUS_STMT_USED, &iCur, &iHiwtr, 0); printf("%s Statement Heap Usage: %d bytes\n", zTag, iCur); } sqlite3_close(db); /* Global memory usage statistics printed after the database connection ** has closed. Memory usage should be zero at this point. */ if( showStats ){ sqlite3_status(SQLITE_STATUS_MEMORY_USED, &iCur, &iHiwtr, 0); printf("%s Memory Used (bytes): %d (max %d)\n", zTag,iCur,iHiwtr); sqlite3_status(SQLITE_STATUS_MALLOC_COUNT, &iCur, &iHiwtr, 0); printf("%s Outstanding Allocations: %d (max %d)\n",zTag,iCur,iHiwtr); sqlite3_status(SQLITE_STATUS_PAGECACHE_OVERFLOW, &iCur, &iHiwtr, 0); printf("%s Pcache Overflow Bytes: %d (max %d)\n",zTag,iCur,iHiwtr); sqlite3_status(SQLITE_STATUS_SCRATCH_OVERFLOW, &iCur, &iHiwtr, 0); printf("%s Scratch Overflow Bytes: %d (max %d)\n",zTag,iCur,iHiwtr); sqlite3_status(SQLITE_STATUS_MALLOC_SIZE, &iCur, &iHiwtr, 0); printf("%s Largest Allocation: %d bytes\n",zTag,iHiwtr); sqlite3_status(SQLITE_STATUS_PAGECACHE_SIZE, &iCur, &iHiwtr, 0); printf("%s Largest Pcache Allocation: %d bytes\n",zTag,iHiwtr); sqlite3_status(SQLITE_STATUS_SCRATCH_SIZE, &iCur, &iHiwtr, 0); printf("%s Largest Scratch Allocation: %d bytes\n",zTag,iHiwtr); } return 0; }
sqlite_sqlite
2017-01-28
2d2e4f389584fec0b27100107b18bb835ddeba94
lib/StaticAnalyzer/Checkers/IteratorPastEndChecker.cpp
842
//===-- IteratorPastEndChecker.cpp --------------------------------*- C++ -*--// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Defines a checker for using iterators outside their range (past end). Usage // means here dereferencing, incrementing etc. // //===----------------------------------------------------------------------===// #include "ClangSACheckers.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" #include <utility> using namespace clang; using namespace ento; namespace { struct IteratorPosition { private: enum Kind { InRange, OutofRange } K; IteratorPosition(Kind InK) : K(InK) {} public: bool isInRange() const { return K == InRange; } bool isOutofRange() const { return K == OutofRange; } static IteratorPosition getInRange() { return IteratorPosition(InRange); } static IteratorPosition getOutofRange() { return IteratorPosition(OutofRange); } bool operator==(const IteratorPosition &X) const { return K == X.K; } bool operator!=(const IteratorPosition &X) const { return K != X.K; } void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(K); } }; typedef llvm::PointerUnion<const MemRegion *, SymbolRef> RegionOrSymbol; struct IteratorComparison { private: RegionOrSymbol Left, Right; bool Equality; public: IteratorComparison(RegionOrSymbol L, RegionOrSymbol R, bool Eq) : Left(L), Right(R), Equality(Eq) {} RegionOrSymbol getLeft() const { return Left; } RegionOrSymbol getRight() const { return Right; } bool isEquality() const { return Equality; } bool operator==(const IteratorComparison &X) const { return Left == X.Left && Right == X.Right && Equality == X.Equality; } bool operator!=(const IteratorComparison &X) const { return Left != X.Left || Right != X.Right || Equality != X.Equality; } void Profile(llvm::FoldingSetNodeID &ID) const { ID.AddInteger(Equality); } }; class IteratorPastEndChecker : public Checker< check::PreCall, check::PostCall, check::PreStmt<CXXOperatorCallExpr>, check::PostStmt<CXXConstructExpr>, check::PostStmt<DeclStmt>, check::PostStmt<MaterializeTemporaryExpr>, check::BeginFunction, check::DeadSymbols, eval::Assume, eval::Call> { mutable IdentifierInfo *II_find = nullptr, *II_find_end = nullptr, *II_find_first_of = nullptr, *II_find_if = nullptr, *II_find_if_not = nullptr, *II_lower_bound = nullptr, *II_upper_bound = nullptr, *II_search = nullptr, *II_search_n = nullptr; std::unique_ptr<BugType> PastEndBugType; void handleComparison(CheckerContext &C, const SVal &RetVal, const SVal &LVal, const SVal &RVal, OverloadedOperatorKind Op) const; void handleAccess(CheckerContext &C, const SVal &Val) const; void handleDecrement(CheckerContext &C, const SVal &Val) const; void handleEnd(CheckerContext &C, const SVal &RetVal) const; bool evalFind(CheckerContext &C, const CallExpr *CE) const; bool evalFindEnd(CheckerContext &C, const CallExpr *CE) const; bool evalFindFirstOf(CheckerContext &C, const CallExpr *CE) const; bool evalFindIf(CheckerContext &C, const CallExpr *CE) const; bool evalFindIfNot(CheckerContext &C, const CallExpr *CE) const; bool evalLowerBound(CheckerContext &C, const CallExpr *CE) const; bool evalUpperBound(CheckerContext &C, const CallExpr *CE) const; bool evalSearch(CheckerContext &C, const CallExpr *CE) const; bool evalSearchN(CheckerContext &C, const CallExpr *CE) const; void Find(CheckerContext &C, const CallExpr *CE) const; void reportPastEndBug(const StringRef &Message, const SVal &Val, CheckerContext &C, ExplodedNode *ErrNode) const; void initIdentifiers(ASTContext &Ctx) const; public: IteratorPastEndChecker(); void checkPreCall(const CallEvent &Call, CheckerContext &C) const; void checkPostCall(const CallEvent &Call, CheckerContext &C) const; void checkPreStmt(const CXXOperatorCallExpr *COCE, CheckerContext &C) const; void checkBeginFunction(CheckerContext &C) const; void checkPostStmt(const CXXConstructExpr *CCE, CheckerContext &C) const; void checkPostStmt(const DeclStmt *DS, CheckerContext &C) const; void checkPostStmt(const MaterializeTemporaryExpr *MTE, CheckerContext &C) const; void checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const; ProgramStateRef evalAssume(ProgramStateRef State, SVal Cond, bool Assumption) const; bool evalCall(const CallExpr *CE, CheckerContext &C) const; }; } REGISTER_MAP_WITH_PROGRAMSTATE(IteratorSymbolMap, SymbolRef, IteratorPosition) REGISTER_MAP_WITH_PROGRAMSTATE(IteratorRegionMap, const MemRegion *, IteratorPosition) REGISTER_MAP_WITH_PROGRAMSTATE(IteratorComparisonMap, const SymExpr *, IteratorComparison) #define INIT_ID(Id) \ if (!II_##Id) \ II_##Id = &Ctx.Idents.get(#Id) namespace { bool isIteratorType(const QualType &Type); bool isIterator(const CXXRecordDecl *CRD); bool isEndCall(const FunctionDecl *Func); bool isSimpleComparisonOperator(OverloadedOperatorKind OK); bool isAccessOperator(OverloadedOperatorKind OK); bool isDecrementOperator(OverloadedOperatorKind OK); BinaryOperator::Opcode getOpcode(const SymExpr *SE); const RegionOrSymbol getRegionOrSymbol(const SVal &Val); const ProgramStateRef processComparison(ProgramStateRef State, RegionOrSymbol LVal, RegionOrSymbol RVal, bool Equal); const ProgramStateRef saveComparison(ProgramStateRef State, const SymExpr *Condition, const SVal &LVal, const SVal &RVal, bool Eq); const IteratorComparison *loadComparison(ProgramStateRef State, const SymExpr *Condition); const IteratorPosition *getIteratorPosition(ProgramStateRef State, const SVal &Val); const IteratorPosition *getIteratorPosition(ProgramStateRef State, RegionOrSymbol RegOrSym); ProgramStateRef setIteratorPosition(ProgramStateRef State, const SVal &Val, IteratorPosition Pos); ProgramStateRef setIteratorPosition(ProgramStateRef State, RegionOrSymbol RegOrSym, IteratorPosition Pos); ProgramStateRef adjustIteratorPosition(ProgramStateRef State, RegionOrSymbol RegOrSym, IteratorPosition Pos, bool Equal); bool contradictingIteratorPositions(IteratorPosition Pos1, IteratorPosition Pos2, bool Equal); } IteratorPastEndChecker::IteratorPastEndChecker() { PastEndBugType.reset( new BugType(this, "Iterator Past End", "Misuse of STL APIs")); PastEndBugType->setSuppressOnSink(true); } void IteratorPastEndChecker::checkPreCall(const CallEvent &Call, CheckerContext &C) const { // Check for access past end const auto *Func = Call.getDecl()->getAsFunction(); if (!Func) return; if (Func->isOverloadedOperator()) { if (isAccessOperator(Func->getOverloadedOperator())) { if (const auto *InstCall = dyn_cast<CXXInstanceCall>(&Call)) { handleAccess(C, InstCall->getCXXThisVal()); } else { handleAccess(C, Call.getArgSVal(0)); } } } } void IteratorPastEndChecker::checkPostCall(const CallEvent &Call, CheckerContext &C) const { // Record end() iterators, iterator decrementation and comparison const auto *Func = Call.getDecl()->getAsFunction(); if (!Func) return; if (Func->isOverloadedOperator()) { const auto Op = Func->getOverloadedOperator(); if (isSimpleComparisonOperator(Op)) { if (Func->isCXXInstanceMember()) { const auto &InstCall = static_cast<const CXXInstanceCall &>(Call); handleComparison(C, InstCall.getReturnValue(), InstCall.getCXXThisVal(), InstCall.getArgSVal(0), Op); } else { handleComparison(C, Call.getReturnValue(), Call.getArgSVal(0), Call.getArgSVal(1), Op); } } else if (isDecrementOperator(Func->getOverloadedOperator())) { if (Func->isCXXInstanceMember()) { const auto &InstCall = static_cast<const CXXInstanceCall &>(Call); handleDecrement(C, InstCall.getCXXThisVal()); } else { handleDecrement(C, Call.getArgSVal(0)); } } } else if (Func->isCXXInstanceMember()) { if (!isEndCall(Func)) return; if (!isIteratorType(Call.getResultType())) return; handleEnd(C, Call.getReturnValue()); } } void IteratorPastEndChecker::checkPreStmt(const CXXOperatorCallExpr *COCE, CheckerContext &C) const { const auto *ThisExpr = COCE->getArg(0); auto State = C.getState(); const auto *LCtx = C.getPredecessor()->getLocationContext(); const auto CurrentThis = State->getSVal(ThisExpr, LCtx); if (const auto *Reg = CurrentThis.getAsRegion()) { if (!Reg->getAs<CXXTempObjectRegion>()) return; const auto OldState = C.getPredecessor()->getFirstPred()->getState(); const auto OldThis = OldState->getSVal(ThisExpr, LCtx); const auto *Pos = getIteratorPosition(OldState, OldThis); if (!Pos) return; State = setIteratorPosition(State, CurrentThis, *Pos); C.addTransition(State); } } void IteratorPastEndChecker::checkBeginFunction(CheckerContext &C) const { // Copy state of iterator arguments to iterator parameters auto State = C.getState(); const auto *LCtx = C.getLocationContext(); const auto *Site = cast<StackFrameContext>(LCtx)->getCallSite(); if (!Site) return; const auto *FD = dyn_cast<FunctionDecl>(LCtx->getDecl()); if (!FD) return; const auto *CE = dyn_cast<CallExpr>(Site); if (!CE) return; bool Change = false; int idx = 0; for (const auto P : FD->parameters()) { auto Param = State->getLValue(P, LCtx); auto Arg = State->getSVal(CE->getArg(idx++), LCtx->getParent()); const auto *Pos = getIteratorPosition(State, Arg); if (!Pos) continue; State = setIteratorPosition(State, Param, *Pos); Change = true; } if (Change) { C.addTransition(State); } } void IteratorPastEndChecker::checkPostStmt(const CXXConstructExpr *CCE, CheckerContext &C) const { // Transfer iterator state in case of copy or move by constructor const auto *ctr = CCE->getConstructor(); if (!ctr->isCopyOrMoveConstructor()) return; const auto *RHSExpr = CCE->getArg(0); auto State = C.getState(); const auto *LCtx = C.getLocationContext(); const auto RetVal = State->getSVal(CCE, LCtx); const auto RHSVal = State->getSVal(RHSExpr, LCtx); const auto *RHSPos = getIteratorPosition(State, RHSVal); if (!RHSPos) return; State = setIteratorPosition(State, RetVal, *RHSPos); C.addTransition(State); } void IteratorPastEndChecker::checkPostStmt(const DeclStmt *DS, CheckerContext &C) const { // Transfer iterator state to new variable declaration for (const auto *D : DS->decls()) { const auto *VD = dyn_cast<VarDecl>(D); if (!VD || !VD->hasInit()) continue; auto State = C.getState(); const auto *LCtx = C.getPredecessor()->getLocationContext(); const auto *Pos = getIteratorPosition(State, State->getSVal(VD->getInit(), LCtx)); if (!Pos) continue; State = setIteratorPosition(State, State->getLValue(VD, LCtx), *Pos); C.addTransition(State); } } void IteratorPastEndChecker::checkPostStmt(const MaterializeTemporaryExpr *MTE, CheckerContext &C) const { /* Transfer iterator state for to temporary objects */ auto State = C.getState(); const auto *LCtx = C.getPredecessor()->getLocationContext(); const auto *Pos = getIteratorPosition(State, State->getSVal(MTE->GetTemporaryExpr(), LCtx)); if (!Pos) return; State = setIteratorPosition(State, State->getSVal(MTE, LCtx), *Pos); C.addTransition(State); } void IteratorPastEndChecker::checkDeadSymbols(SymbolReaper &SR, CheckerContext &C) const { auto State = C.getState(); auto RegionMap = State->get<IteratorRegionMap>(); for (const auto Reg : RegionMap) { if (!SR.isLiveRegion(Reg.first)) { State = State->remove<IteratorRegionMap>(Reg.first); } } auto SymbolMap = State->get<IteratorSymbolMap>(); for (const auto Sym : SymbolMap) { if (SR.isDead(Sym.first)) { State = State->remove<IteratorSymbolMap>(Sym.first); } } auto ComparisonMap = State->get<IteratorComparisonMap>(); for (const auto Comp : ComparisonMap) { if (SR.isDead(Comp.first)) { State = State->remove<IteratorComparisonMap>(Comp.first); } } } ProgramStateRef IteratorPastEndChecker::evalAssume(ProgramStateRef State, SVal Cond, bool Assumption) const { // Load recorded comparison and transfer iterator state between sides // according to comparison operator and assumption const auto *SE = Cond.getAsSymExpr(); if (!SE) return State; auto Opc = getOpcode(SE); if (Opc != BO_EQ && Opc != BO_NE) return State; bool Negated = false; const auto *Comp = loadComparison(State, SE); if (!Comp) { // Try negated comparison, which is a SymExpr to 0 integer comparison const auto *SIE = dyn_cast<SymIntExpr>(SE); if (!SIE) return State; if (SIE->getRHS() != 0) return State; SE = SIE->getLHS(); Negated = SIE->getOpcode() == BO_EQ; // Equal to zero means negation Opc = getOpcode(SE); if (Opc != BO_EQ && Opc != BO_NE) return State; Comp = loadComparison(State, SE); if (!Comp) return State; } return processComparison(State, Comp->getLeft(), Comp->getRight(), (Comp->isEquality() == Assumption) != Negated); } // FIXME: Evaluation of these STL calls should be moved to StdCLibraryFunctions // checker (see patch r284960) or another similar checker for C++ STL // functions (e.g. StdCXXLibraryFunctions or StdCppLibraryFunctions). bool IteratorPastEndChecker::evalCall(const CallExpr *CE, CheckerContext &C) const { const FunctionDecl *FD = C.getCalleeDecl(CE); if (!FD) return false; ASTContext &Ctx = C.getASTContext(); initIdentifiers(Ctx); if (FD->getKind() == Decl::Function) { if (FD->isInStdNamespace()) { if (FD->getIdentifier() == II_find) { return evalFind(C, CE); } else if (FD->getIdentifier() == II_find_end) { return evalFindEnd(C, CE); } else if (FD->getIdentifier() == II_find_first_of) { return evalFindFirstOf(C, CE); } else if (FD->getIdentifier() == II_find_if) { return evalFindIf(C, CE); } else if (FD->getIdentifier() == II_find_if) { return evalFindIf(C, CE); } else if (FD->getIdentifier() == II_find_if_not) { return evalFindIfNot(C, CE); } else if (FD->getIdentifier() == II_upper_bound) { return evalUpperBound(C, CE); } else if (FD->getIdentifier() == II_lower_bound) { return evalLowerBound(C, CE); } else if (FD->getIdentifier() == II_search) { return evalSearch(C, CE); } else if (FD->getIdentifier() == II_search_n) { return evalSearchN(C, CE); } } } return false; } void IteratorPastEndChecker::handleComparison(CheckerContext &C, const SVal &RetVal, const SVal &LVal, const SVal &RVal, OverloadedOperatorKind Op) const { // Record the operands and the operator of the comparison for the next // evalAssume, if the result is a symbolic expression. If it is a concrete // value (only one branch is possible), then transfer the state between // the operands according to the operator and the result auto State = C.getState(); if (const auto *Condition = RetVal.getAsSymbolicExpression()) { const auto *LPos = getIteratorPosition(State, LVal); const auto *RPos = getIteratorPosition(State, RVal); if (!LPos && !RPos) return; State = saveComparison(State, Condition, LVal, RVal, Op == OO_EqualEqual); C.addTransition(State); } else if (const auto TruthVal = RetVal.getAs<nonloc::ConcreteInt>()) { if ((State = processComparison( State, getRegionOrSymbol(LVal), getRegionOrSymbol(RVal), (Op == OO_EqualEqual) == (TruthVal->getValue() != 0)))) { C.addTransition(State); } else { C.generateSink(State, C.getPredecessor()); } } } void IteratorPastEndChecker::handleAccess(CheckerContext &C, const SVal &Val) const { auto State = C.getState(); const auto *Pos = getIteratorPosition(State, Val); if (Pos && Pos->isOutofRange()) { auto *N = C.generateNonFatalErrorNode(State); if (!N) { return; } reportPastEndBug("Iterator accessed past its end.", Val, C, N); } } void IteratorPastEndChecker::handleDecrement(CheckerContext &C, const SVal &Val) const { auto State = C.getState(); const auto *Pos = getIteratorPosition(State, Val); if (Pos && Pos->isOutofRange()) { State = setIteratorPosition(State, Val, IteratorPosition::getInRange()); // FIXME: We could also check for iterators ahead of their beginnig in the // future, but currently we do not care for such errors. We also // assume that the iterator is not past its end by more then one // position. C.addTransition(State); } } void IteratorPastEndChecker::handleEnd(CheckerContext &C, const SVal &RetVal) const { auto State = C.getState(); State = setIteratorPosition(State, RetVal, IteratorPosition::getOutofRange()); C.addTransition(State); } bool IteratorPastEndChecker::evalFind(CheckerContext &C, const CallExpr *CE) const { if (CE->getNumArgs() == 3 && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType())) { Find(C, CE); return true; } return false; } bool IteratorPastEndChecker::evalFindEnd(CheckerContext &C, const CallExpr *CE) const { if ((CE->getNumArgs() == 4 || CE->getNumArgs() == 5) && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType()) && isIteratorType(CE->getArg(2)->getType()) && isIteratorType(CE->getArg(3)->getType())) { Find(C, CE); return true; } return false; } bool IteratorPastEndChecker::evalFindFirstOf(CheckerContext &C, const CallExpr *CE) const { if ((CE->getNumArgs() == 4 || CE->getNumArgs() == 5) && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType()) && isIteratorType(CE->getArg(2)->getType()) && isIteratorType(CE->getArg(3)->getType())) { Find(C, CE); return true; } return false; } bool IteratorPastEndChecker::evalFindIf(CheckerContext &C, const CallExpr *CE) const { if (CE->getNumArgs() == 3 && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType())) { Find(C, CE); return true; } return false; } bool IteratorPastEndChecker::evalFindIfNot(CheckerContext &C, const CallExpr *CE) const { if (CE->getNumArgs() == 3 && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType())) { Find(C, CE); return true; } return false; } bool IteratorPastEndChecker::evalLowerBound(CheckerContext &C, const CallExpr *CE) const { if ((CE->getNumArgs() == 3 || CE->getNumArgs() == 4) && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType())) { Find(C, CE); return true; } return false; } bool IteratorPastEndChecker::evalUpperBound(CheckerContext &C, const CallExpr *CE) const { if ((CE->getNumArgs() == 3 || CE->getNumArgs() == 4) && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType())) { Find(C, CE); return true; } return false; } bool IteratorPastEndChecker::evalSearch(CheckerContext &C, const CallExpr *CE) const { if ((CE->getNumArgs() == 4 || CE->getNumArgs() == 5) && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType()) && isIteratorType(CE->getArg(2)->getType()) && isIteratorType(CE->getArg(3)->getType())) { Find(C, CE); return true; } return false; } bool IteratorPastEndChecker::evalSearchN(CheckerContext &C, const CallExpr *CE) const { if ((CE->getNumArgs() == 4 || CE->getNumArgs() == 5) && isIteratorType(CE->getArg(0)->getType()) && isIteratorType(CE->getArg(1)->getType())) { Find(C, CE); return true; } return false; } void IteratorPastEndChecker::Find(CheckerContext &C, const CallExpr *CE) const { auto state = C.getState(); auto &svalBuilder = C.getSValBuilder(); const auto *LCtx = C.getLocationContext(); auto RetVal = svalBuilder.conjureSymbolVal(nullptr, CE, LCtx, C.blockCount()); auto SecondParam = state->getSVal(CE->getArg(1), LCtx); auto stateFound = state->BindExpr(CE, LCtx, RetVal); auto stateNotFound = state->BindExpr(CE, LCtx, SecondParam); C.addTransition(stateFound); C.addTransition(stateNotFound); } void IteratorPastEndChecker::reportPastEndBug(const StringRef &Message, const SVal &Val, CheckerContext &C, ExplodedNode *ErrNode) const { auto R = llvm::make_unique<BugReport>(*PastEndBugType, Message, ErrNode); R->markInteresting(Val); C.emitReport(std::move(R)); } void IteratorPastEndChecker::initIdentifiers(ASTContext &Ctx) const { INIT_ID(find); INIT_ID(find_end); INIT_ID(find_first_of); INIT_ID(find_if); INIT_ID(find_if_not); INIT_ID(lower_bound); INIT_ID(upper_bound); INIT_ID(search); INIT_ID(search_n); } namespace { bool isIteratorType(const QualType &Type) { if (Type->isPointerType()) return true; const auto *CRD = Type->getUnqualifiedDesugaredType()->getAsCXXRecordDecl(); return isIterator(CRD); } bool isIterator(const CXXRecordDecl *CRD) { if (!CRD) return false; const auto Name = CRD->getName(); if (!(Name.endswith_lower("iterator") || Name.endswith_lower("iter") || Name.endswith_lower("it"))) return false; bool HasCopyCtor = false, HasCopyAssign = true, HasDtor = false, HasPreIncrOp = false, HasPostIncrOp = false, HasDerefOp = false; for (const auto *Method : CRD->methods()) { if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Method)) { if (Ctor->isCopyConstructor()) { HasCopyCtor = !Ctor->isDeleted() && Ctor->getAccess() == AS_public; } continue; } if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(Method)) { HasDtor = !Dtor->isDeleted() && Dtor->getAccess() == AS_public; continue; } if (Method->isCopyAssignmentOperator()) { HasCopyAssign = !Method->isDeleted() && Method->getAccess() == AS_public; continue; } if (!Method->isOverloadedOperator()) continue; const auto OPK = Method->getOverloadedOperator(); if (OPK == OO_PlusPlus) { HasPreIncrOp = HasPreIncrOp || (Method->getNumParams() == 0); HasPostIncrOp = HasPostIncrOp || (Method->getNumParams() == 1); continue; } if (OPK == OO_Star) { HasDerefOp = (Method->getNumParams() == 0); continue; } } return HasCopyCtor && HasCopyAssign && HasDtor && HasPreIncrOp && HasPostIncrOp && HasDerefOp; } bool isEndCall(const FunctionDecl *Func) { const auto *IdInfo = Func->getIdentifier(); if (!IdInfo) return false; return IdInfo->getName().endswith_lower("end"); } bool isSimpleComparisonOperator(OverloadedOperatorKind OK) { return OK == OO_EqualEqual || OK == OO_ExclaimEqual; } bool isAccessOperator(OverloadedOperatorKind OK) { return OK == OO_Star || OK == OO_Arrow || OK == OO_ArrowStar || OK == OO_Plus || OK == OO_PlusEqual || OK == OO_PlusPlus || OK == OO_Subscript; } bool isDecrementOperator(OverloadedOperatorKind OK) { return OK == OO_MinusEqual || OK == OO_MinusMinus; } BinaryOperator::Opcode getOpcode(const SymExpr *SE) { if (const auto *BSE = dyn_cast<BinarySymExpr>(SE)) { return BSE->getOpcode(); } else if (const auto *SC = dyn_cast<SymbolConjured>(SE)) { const auto *COE = dyn_cast<CXXOperatorCallExpr>(SC->getStmt()); if (!COE) return BO_Comma; // Extremal value, neither EQ nor NE if (COE->getOperator() == OO_EqualEqual) { return BO_EQ; } else if (COE->getOperator() == OO_ExclaimEqual) { return BO_NE; } return BO_Comma; // Extremal value, neither EQ nor NE } return BO_Comma; // Extremal value, neither EQ nor NE } const RegionOrSymbol getRegionOrSymbol(const SVal &Val) { if (const auto Reg = Val.getAsRegion()) { return Reg; } else if (const auto Sym = Val.getAsSymbol()) { return Sym; } else if (const auto LCVal = Val.getAs<nonloc::LazyCompoundVal>()) { return LCVal->getRegion(); } return RegionOrSymbol(); } const ProgramStateRef processComparison(ProgramStateRef State, RegionOrSymbol LVal, RegionOrSymbol RVal, bool Equal) { const auto *LPos = getIteratorPosition(State, LVal); const auto *RPos = getIteratorPosition(State, RVal); if (LPos && !RPos) { State = adjustIteratorPosition(State, RVal, *LPos, Equal); } else if (!LPos && RPos) { State = adjustIteratorPosition(State, LVal, *RPos, Equal); } else if (LPos && RPos) { if (contradictingIteratorPositions(*LPos, *RPos, Equal)) { return nullptr; } } return State; } const ProgramStateRef saveComparison(ProgramStateRef State, const SymExpr *Condition, const SVal &LVal, const SVal &RVal, bool Eq) { const auto Left = getRegionOrSymbol(LVal); const auto Right = getRegionOrSymbol(RVal); if (!Left || !Right) return State; return State->set<IteratorComparisonMap>(Condition, IteratorComparison(Left, Right, Eq)); } const IteratorComparison *loadComparison(ProgramStateRef State, const SymExpr *Condition) { return State->get<IteratorComparisonMap>(Condition); } const IteratorPosition *getIteratorPosition(ProgramStateRef State, const SVal &Val) { if (const auto Reg = Val.getAsRegion()) { return State->get<IteratorRegionMap>(Reg); } else if (const auto Sym = Val.getAsSymbol()) { return State->get<IteratorSymbolMap>(Sym); } else if (const auto LCVal = Val.getAs<nonloc::LazyCompoundVal>()) { return State->get<IteratorRegionMap>(LCVal->getRegion()); } return nullptr; } const IteratorPosition *getIteratorPosition(ProgramStateRef State, RegionOrSymbol RegOrSym) { if (RegOrSym.is<const MemRegion *>()) { return State->get<IteratorRegionMap>(RegOrSym.get<const MemRegion *>()); } else if (RegOrSym.is<SymbolRef>()) { return State->get<IteratorSymbolMap>(RegOrSym.get<SymbolRef>()); } return nullptr; } ProgramStateRef setIteratorPosition(ProgramStateRef State, const SVal &Val, IteratorPosition Pos) { if (const auto Reg = Val.getAsRegion()) { return State->set<IteratorRegionMap>(Reg, Pos); } else if (const auto Sym = Val.getAsSymbol()) { return State->set<IteratorSymbolMap>(Sym, Pos); } else if (const auto LCVal = Val.getAs<nonloc::LazyCompoundVal>()) { return State->set<IteratorRegionMap>(LCVal->getRegion(), Pos); } return nullptr; } ProgramStateRef setIteratorPosition(ProgramStateRef State, RegionOrSymbol RegOrSym, IteratorPosition Pos) { if (RegOrSym.is<const MemRegion *>()) { return State->set<IteratorRegionMap>(RegOrSym.get<const MemRegion *>(), Pos); } else if (RegOrSym.is<SymbolRef>()) { return State->set<IteratorSymbolMap>(RegOrSym.get<SymbolRef>(), Pos); } return nullptr; } ProgramStateRef adjustIteratorPosition(ProgramStateRef State, RegionOrSymbol RegOrSym, IteratorPosition Pos, bool Equal) { if ((Pos.isInRange() && Equal) || (Pos.isOutofRange() && !Equal)) { return setIteratorPosition(State, RegOrSym, IteratorPosition::getInRange()); } else if (Pos.isOutofRange() && Equal) { return setIteratorPosition(State, RegOrSym, IteratorPosition::getOutofRange()); } else { return State; } } bool contradictingIteratorPositions(IteratorPosition Pos1, IteratorPosition Pos2, bool Equal) { return ((Pos1 != Pos2) && Equal) || ((Pos1.isOutofRange() && Pos2.isOutofRange()) && !Equal); } } void ento::registerIteratorPastEndChecker(CheckerManager &Mgr) { Mgr.registerChecker<IteratorPastEndChecker>(); }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_simd_misc_messages.c
312
// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute simd'}} #pragma omp target teams distribute simd foo void test_no_clause() { int i; #pragma omp target teams distribute simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp target teams distribute simd' must be a for loop}} #pragma omp target teams distribute simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp target teams distribute simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd; for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} #pragma omp target teams distribute simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp target teams distribute simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target teams distribute simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target teams distribute simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} #pragma omp target teams distribute simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute simd', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target teams distribute simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target teams distribute simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-error@+4 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp target teams distribute simd collapse(2) firstprivate(i) for (i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) #pragma omp parallel for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd firstprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute simd firstprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute simd firstprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute simd firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute simd lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute simd lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_parallel_for_is_device_ptr_messages.cpp
311
// RUN: %clang_cc1 -std=c++11 -verify -fopenmp %s struct ST { int *a; }; typedef int arr[10]; typedef ST STarr[10]; typedef struct { int a; } S; struct SA { const int d = 5; const int da[5] = { 0 }; ST e; ST g[10]; STarr &rg = g; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; arr &raa = aa; S *ps; void func(int arg) { #pragma omp target parallel for is_device_ptr // expected-error {{expected '(' after 'is_device_ptr'}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected expression}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr() // expected-error {{expected expression}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(alloc) // expected-error {{use of undeclared identifier 'alloc'}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(arg // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(i) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(j) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(k) // OK for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(z) // OK for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(aa) // OK for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(raa) // OK for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(e) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(g) // OK for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(rg) // OK for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(k,i,j) // expected-error2 {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(d) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(da) // OK for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for map(ps) is_device_ptr(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(ps) map(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for map(ps->a) is_device_ptr(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for is_device_ptr(ps) map(ps->a) // expected-error{{pointer cannot be mapped along with a section derived from itself}} expected-note{{used here}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for firstprivate(ps) is_device_ptr(ps) // expected-error{{firstprivate variable cannot be in a is_device_ptr clause in '#pragma omp target parallel for' directive}} expected-note{{defined as firstprivate}} for (int ii=0; ii<10; ii++) ; #pragma omp target parallel for private(ps) is_device_ptr(ps) // expected-error{{private variable cannot be in a is_device_ptr clause in '#pragma omp target parallel for' directive}} expected-note{{defined as private}} for (int ii=0; ii<10; ii++) ; return; } }; struct SB { unsigned A; unsigned B; float Arr[100]; float *Ptr; float *foo() { return &Arr[0]; } }; struct SC { unsigned A : 2; unsigned B : 3; unsigned C; unsigned D; float Arr[100]; SB S; SB ArrS[100]; SB *PtrS; SB *&RPtrS; float *Ptr; SC(SB *&_RPtrS) : RPtrS(_RPtrS) {} }; union SD { unsigned A; float B; }; struct S1; extern S1 a; class S2 { mutable int a; public: S2():a(0) { } S2(S2 &s2):a(s2.a) { } static float S2s; static const float S2sc; }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3():a(0) { } S3(S3 &s3):a(s3.a) { } }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} S5(const S5 &s5):a(s5.a) { } public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) typedef struct { int a; } S6; template <typename T, int I> T tmain(T argc) { const T d = 5; const T da[5] = { 0 }; S4 e(4); S5 g(5); S6 h[10]; auto &rh = h; T i; T &j = i; T *k = &j; T *&z = k; T aa[10]; auto &raa = aa; #pragma omp target parallel for is_device_ptr // expected-error {{expected '(' after 'is_device_ptr'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected expression}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr() // expected-error {{expected expression}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(alloc) // expected-error {{use of undeclared identifier 'alloc'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(i) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(j) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(k) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(z) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(aa) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(raa) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(e) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(g) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(h) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(rh) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(k,i,j) // expected-error2 {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(d) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(da) // OK for (int kk=0; kk<20; kk++) ; return 0; } int main(int argc, char **argv) { const int d = 5; const int da[5] = { 0 }; S4 e(4); S5 g(5); S6 h[10]; auto &rh = h; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; auto &raa = aa; #pragma omp target parallel for is_device_ptr // expected-error {{expected '(' after 'is_device_ptr'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected expression}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr() // expected-error {{expected expression}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(alloc) // expected-error {{use of undeclared identifier 'alloc'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(i) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(j) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(k) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(z) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(aa) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(raa) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(e) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(g) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(h) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(rh) // OK for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(k,i,j) // expected-error2 {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(d) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int kk=0; kk<20; kk++) ; #pragma omp target parallel for is_device_ptr(da) // OK for (int kk=0; kk<20; kk++) ; return tmain<int, 3>(argc); // expected-note {{in instantiation of function template specialization 'tmain<int, 3>' requested here}} }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_parallel_for_simd_is_device_ptr_ast_print.cpp
318
// RUN: %clang_cc1 -verify -fopenmp -std=c++11 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER struct ST { int *a; }; typedef int arr[10]; typedef ST STarr[10]; struct SA { const int da[5] = { 0 }; ST g[10]; STarr &rg = g; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; arr &raa = aa; void func(int arg) { #pragma omp target parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(aa) // OK for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(raa) // OK for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(g) // OK for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(rg) // OK for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(da) // OK for (int i=0; i<100; i++) ; return; } }; // CHECK: struct SA // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: ST g[10]; // CHECK-NEXT: STarr &rg = this->g; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = this->i; // CHECK-NEXT: int *k = &this->j; // CHECK-NEXT: int *&z = this->k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: arr &raa = this->aa; // CHECK-NEXT: func( // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(this->k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(this->z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(this->aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(this->raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(this->g) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(this->rg) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(this->da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; struct SB { unsigned A; unsigned B; float Arr[100]; float *Ptr; float *foo() { return &Arr[0]; } }; struct SC { unsigned A : 2; unsigned B : 3; unsigned C; unsigned D; float Arr[100]; SB S; SB ArrS[100]; SB *PtrS; SB *&RPtrS; float *Ptr; SC(SB *&_RPtrS) : RPtrS(_RPtrS) {} }; union SD { unsigned A; float B; }; struct S1; extern S1 a; class S2 { mutable int a; public: S2():a(0) { } S2(S2 &s2):a(s2.a) { } static float S2s; static const float S2sc; }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3():a(0) { } S3(S3 &s3):a(s3.a) { } }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} S5(const S5 &s5):a(s5.a) { } public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) typedef struct { int a; } S6; template <typename T> T tmain(T argc) { const T da[5] = { 0 }; S6 h[10]; auto &rh = h; T i; T &j = i; T *k = &j; T *&z = k; T aa[10]; auto &raa = aa; #pragma omp target parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(aa) for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(raa) for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(h) for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(rh) for (int i=0; i<100; i++) ; #pragma omp target parallel for simd is_device_ptr(da) for (int i=0; i<100; i++) ; return 0; } // CHECK: template<> int tmain<int>(int argc) { // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK: template<> int *tmain<int *>(int *argc) { // CHECK-NEXT: int *const da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int *i; // CHECK-NEXT: int *&j = i; // CHECK-NEXT: int **k = &j; // CHECK-NEXT: int **&z = k; // CHECK-NEXT: int *aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-LABEL: int main(int argc, char **argv) { int main(int argc, char **argv) { const int da[5] = { 0 }; S6 h[10]; auto &rh = h; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; auto &raa = aa; // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; #pragma omp target parallel for simd is_device_ptr(k) // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target parallel for simd is_device_ptr(z) // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target parallel for simd is_device_ptr(aa) // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(aa) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target parallel for simd is_device_ptr(raa) // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(raa) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target parallel for simd is_device_ptr(h) // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(h) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target parallel for simd is_device_ptr(rh) // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(rh) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target parallel for simd is_device_ptr(da) // CHECK-NEXT: #pragma omp target parallel for simd is_device_ptr(da) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; return tmain<int>(argc) + *tmain<int *>(&argc); } #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/SemaCXX/diagnose_if.cpp
669
// RUN: %clang_cc1 %s -verify -fno-builtin -std=c++14 #define _diagnose_if(...) __attribute__((diagnose_if(__VA_ARGS__))) using size_t = decltype(sizeof(int)); namespace type_dependent { template <typename T> void neverok() _diagnose_if(!T(), "oh no", "error") {} // expected-note 4{{from 'diagnose_if'}} template <typename T> void alwaysok() _diagnose_if(T(), "oh no", "error") {} template <typename T> void alwayswarn() _diagnose_if(!T(), "oh no", "warning") {} // expected-note 4{{from 'diagnose_if'}} template <typename T> void neverwarn() _diagnose_if(T(), "oh no", "warning") {} void runAll() { alwaysok<int>(); alwaysok<int>(); { void (*pok)() = alwaysok<int>; pok = &alwaysok<int>; } neverok<int>(); // expected-error{{oh no}} neverok<short>(); // expected-error{{oh no}} { void (*pok)() = neverok<int>; // expected-error{{oh no}} } { void (*pok)(); pok = &neverok<int>; // expected-error{{oh no}} } alwayswarn<int>(); // expected-warning{{oh no}} alwayswarn<short>(); // expected-warning{{oh no}} { void (*pok)() = alwayswarn<int>; // expected-warning{{oh no}} pok = &alwayswarn<int>; // expected-warning{{oh no}} } neverwarn<int>(); neverwarn<short>(); { void (*pok)() = neverwarn<int>; pok = &neverwarn<int>; } } template <typename T> void errorIf(T a) _diagnose_if(T() != a, "oh no", "error") {} // expected-note{{from 'diagnose_if'}} template <typename T> void warnIf(T a) _diagnose_if(T() != a, "oh no", "warning") {} // expected-note{{from 'diagnose_if'}} void runIf() { errorIf(0); errorIf(1); // expected-error{{oh no}} warnIf(0); warnIf(1); // expected-warning{{oh no}} } } namespace value_dependent { template <int N> void neverok() _diagnose_if(N == 0 || N != 0, "oh no", "error") {} // expected-note 4{{from 'diagnose_if'}} template <int N> void alwaysok() _diagnose_if(N == 0 && N != 0, "oh no", "error") {} template <int N> void alwayswarn() _diagnose_if(N == 0 || N != 0, "oh no", "warning") {} // expected-note 4{{from 'diagnose_if'}} template <int N> void neverwarn() _diagnose_if(N == 0 && N != 0, "oh no", "warning") {} void runAll() { alwaysok<0>(); alwaysok<1>(); { void (*pok)() = alwaysok<0>; pok = &alwaysok<0>; } neverok<0>(); // expected-error{{oh no}} neverok<1>(); // expected-error{{oh no}} { void (*pok)() = neverok<0>; // expected-error{{oh no}} } { void (*pok)(); pok = &neverok<0>; // expected-error{{oh no}} } alwayswarn<0>(); // expected-warning{{oh no}} alwayswarn<1>(); // expected-warning{{oh no}} { void (*pok)() = alwayswarn<0>; // expected-warning{{oh no}} pok = &alwayswarn<0>; // expected-warning{{oh no}} } neverwarn<0>(); neverwarn<1>(); { void (*pok)() = neverwarn<0>; pok = &neverwarn<0>; } } template <int N> void errorIf(int a) _diagnose_if(N != a, "oh no", "error") {} // expected-note{{from 'diagnose_if'}} template <int N> void warnIf(int a) _diagnose_if(N != a, "oh no", "warning") {} // expected-note{{from 'diagnose_if'}} void runIf() { errorIf<0>(0); errorIf<0>(1); // expected-error{{oh no}} warnIf<0>(0); warnIf<0>(1); // expected-warning{{oh no}} } } namespace no_overload_interaction { void foo(int) _diagnose_if(1, "oh no", "error"); // expected-note{{from 'diagnose_if'}} void foo(short); void bar(int); void bar(short) _diagnose_if(1, "oh no", "error"); void fooArg(int a) _diagnose_if(a, "oh no", "error"); // expected-note{{from 'diagnose_if'}} void fooArg(short); void barArg(int); void barArg(short a) _diagnose_if(a, "oh no", "error"); void runAll() { foo(1); // expected-error{{oh no}} bar(1); fooArg(1); // expected-error{{oh no}} barArg(1); auto p = foo; // expected-error{{incompatible initializer of type '<overloaded function type>'}} } } namespace with_default_args { void foo(int a = 0) _diagnose_if(a, "oh no", "warning"); // expected-note 1{{from 'diagnose_if'}} void bar(int a = 1) _diagnose_if(a, "oh no", "warning"); // expected-note 2{{from 'diagnose_if'}} void runAll() { foo(); foo(0); foo(1); // expected-warning{{oh no}} bar(); // expected-warning{{oh no}} bar(0); bar(1); // expected-warning{{oh no}} } } namespace naked_mem_expr { struct Foo { void foo(int a) _diagnose_if(a, "should warn", "warning"); // expected-note{{from 'diagnose_if'}} void bar(int a) _diagnose_if(a, "oh no", "error"); // expected-note{{from 'diagnose_if'}} }; void runFoo() { Foo().foo(0); Foo().foo(1); // expected-warning{{should warn}} Foo().bar(0); Foo().bar(1); // expected-error{{oh no}} } } namespace class_template { template <typename T> struct Errors { void foo(int i) _diagnose_if(i, "bad i", "error"); // expected-note{{from 'diagnose_if'}} void bar(int i) _diagnose_if(i != T(), "bad i", "error"); // expected-note{{from 'diagnose_if'}} void fooOvl(int i) _diagnose_if(i, "int bad i", "error"); // expected-note{{from 'diagnose_if'}} void fooOvl(short i) _diagnose_if(i, "short bad i", "error"); // expected-note{{from 'diagnose_if'}} void barOvl(int i) _diagnose_if(i != T(), "int bad i", "error"); // expected-note{{from 'diagnose_if'}} void barOvl(short i) _diagnose_if(i != T(), "short bad i", "error"); // expected-note{{from 'diagnose_if'}} }; void runErrors() { Errors<int>().foo(0); Errors<int>().foo(1); // expected-error{{bad i}} Errors<int>().bar(0); Errors<int>().bar(1); // expected-error{{bad i}} Errors<int>().fooOvl(0); Errors<int>().fooOvl(1); // expected-error{{int bad i}} Errors<int>().fooOvl(short(0)); Errors<int>().fooOvl(short(1)); // expected-error{{short bad i}} Errors<int>().barOvl(0); Errors<int>().barOvl(1); // expected-error{{int bad i}} Errors<int>().barOvl(short(0)); Errors<int>().barOvl(short(1)); // expected-error{{short bad i}} } template <typename T> struct Warnings { void foo(int i) _diagnose_if(i, "bad i", "warning"); // expected-note{{from 'diagnose_if'}} void bar(int i) _diagnose_if(i != T(), "bad i", "warning"); // expected-note{{from 'diagnose_if'}} void fooOvl(int i) _diagnose_if(i, "int bad i", "warning"); // expected-note{{from 'diagnose_if'}} void fooOvl(short i) _diagnose_if(i, "short bad i", "warning"); // expected-note{{from 'diagnose_if'}} void barOvl(int i) _diagnose_if(i != T(), "int bad i", "warning"); // expected-note{{from 'diagnose_if'}} void barOvl(short i) _diagnose_if(i != T(), "short bad i", "warning"); // expected-note{{from 'diagnose_if'}} }; void runWarnings() { Warnings<int>().foo(0); Warnings<int>().foo(1); // expected-warning{{bad i}} Warnings<int>().bar(0); Warnings<int>().bar(1); // expected-warning{{bad i}} Warnings<int>().fooOvl(0); Warnings<int>().fooOvl(1); // expected-warning{{int bad i}} Warnings<int>().fooOvl(short(0)); Warnings<int>().fooOvl(short(1)); // expected-warning{{short bad i}} Warnings<int>().barOvl(0); Warnings<int>().barOvl(1); // expected-warning{{int bad i}} Warnings<int>().barOvl(short(0)); Warnings<int>().barOvl(short(1)); // expected-warning{{short bad i}} } } namespace template_specialization { template <typename T> struct Foo { void foo() _diagnose_if(1, "override me", "error"); // expected-note{{from 'diagnose_if'}} void bar(int i) _diagnose_if(i, "bad i", "error"); // expected-note{{from 'diagnose_if'}} void baz(int i); }; template <> struct Foo<int> { void foo(); void bar(int i); void baz(int i) _diagnose_if(i, "bad i", "error"); // expected-note{{from 'diagnose_if'}} }; void runAll() { Foo<double>().foo(); // expected-error{{override me}} Foo<int>().foo(); Foo<double>().bar(1); // expected-error{{bad i}} Foo<int>().bar(1); Foo<double>().baz(1); Foo<int>().baz(1); // expected-error{{bad i}} } } namespace late_constexpr { constexpr int foo(); constexpr int foo(int a); void bar() _diagnose_if(foo(), "bad foo", "error"); // expected-note{{from 'diagnose_if'}} void bar(int a) _diagnose_if(foo(a), "bad foo", "error"); // expected-note{{from 'diagnose_if'}} void early() { bar(); bar(0); bar(1); } constexpr int foo() { return 1; } constexpr int foo(int a) { return a; } void late() { bar(); // expected-error{{bad foo}} bar(0); bar(1); // expected-error{{bad foo}} } } namespace late_parsed { struct Foo { int i; constexpr Foo(int i): i(i) {} constexpr bool isFooable() const { return i; } void go() const _diagnose_if(isFooable(), "oh no", "error") {} // expected-note{{from 'diagnose_if'}} operator int() const _diagnose_if(isFooable(), "oh no", "error") { return 1; } // expected-note{{from 'diagnose_if'}} void go2() const _diagnose_if(isFooable(), "oh no", "error") // expected-note{{from 'diagnose_if'}} __attribute__((enable_if(true, ""))) {} void go2() const _diagnose_if(isFooable(), "oh no", "error") {} constexpr int go3() const _diagnose_if(isFooable(), "oh no", "error") __attribute__((enable_if(true, ""))) { return 1; } constexpr int go4() const _diagnose_if(isFooable(), "oh no", "error") { return 1; } constexpr int go4() const _diagnose_if(isFooable(), "oh no", "error") __attribute__((enable_if(true, ""))) { return 1; } // We hope to support emitting these errors in the future. For now, though... constexpr int runGo() const { return go3() + go4(); } }; void go(const Foo &f) _diagnose_if(f.isFooable(), "oh no", "error") {} // expected-note{{from 'diagnose_if'}} void run() { Foo(0).go(); Foo(1).go(); // expected-error{{oh no}} (void)int(Foo(0)); (void)int(Foo(1)); // expected-error{{oh no}} Foo(0).go2(); Foo(1).go2(); // expected-error{{oh no}} go(Foo(0)); go(Foo(1)); // expected-error{{oh no}} } } namespace member_templates { struct Foo { int i; constexpr Foo(int i): i(i) {} constexpr bool bad() const { return i; } template <typename T> T getVal() _diagnose_if(bad(), "oh no", "error") { // expected-note{{from 'diagnose_if'}} return T(); } template <typename T> constexpr T getVal2() const _diagnose_if(bad(), "oh no", "error") { // expected-note{{from 'diagnose_if'}} return T(); } template <typename T> constexpr operator T() const _diagnose_if(bad(), "oh no", "error") { // expected-note{{from 'diagnose_if'}} return T(); } // We hope to support emitting these errors in the future. int run() { return getVal<int>() + getVal2<int>() + int(*this); } }; void run() { Foo(0).getVal<int>(); Foo(1).getVal<int>(); // expected-error{{oh no}} Foo(0).getVal2<int>(); Foo(1).getVal2<int>(); // expected-error{{oh no}} (void)int(Foo(0)); (void)int(Foo(1)); // expected-error{{oh no}} } } namespace special_member_operators { struct Bar { int j; }; struct Foo { int i; constexpr Foo(int i): i(i) {} constexpr bool bad() const { return i; } const Bar *operator->() const _diagnose_if(bad(), "oh no", "error") { // expected-note{{from 'diagnose_if'}} return nullptr; } void operator()() const _diagnose_if(bad(), "oh no", "error") {} // expected-note{{from 'diagnose_if'}} }; struct ParenOverload { int i; constexpr ParenOverload(int i): i(i) {} constexpr bool bad() const { return i; } void operator()(double) const _diagnose_if(bad(), "oh no", "error") {} // expected-note{{from 'diagnose_if'}} void operator()(int) const _diagnose_if(bad(), "oh no", "error") {} // expected-note{{from 'diagnose_if'}} }; struct ParenTemplate { int i; constexpr ParenTemplate(int i): i(i) {} constexpr bool bad() const { return i; } template <typename T> void operator()(T) const _diagnose_if(bad(), "oh no", "error") {} // expected-note 2{{from 'diagnose_if'}} }; void run() { (void)Foo(0)->j; (void)Foo(1)->j; // expected-error{{oh no}} Foo(0)(); Foo(1)(); // expected-error{{oh no}} ParenOverload(0)(1); ParenOverload(0)(1.); ParenOverload(1)(1); // expected-error{{oh no}} ParenOverload(1)(1.); // expected-error{{oh no}} ParenTemplate(0)(1); ParenTemplate(0)(1.); ParenTemplate(1)(1); // expected-error{{oh no}} ParenTemplate(1)(1.); // expected-error{{oh no}} } void runLambda() { auto L1 = [](int i) _diagnose_if(i, "oh no", "error") {}; // expected-note{{from 'diagnose_if'}} L1(0); L1(1); // expected-error{{oh no}} } struct Brackets { int i; constexpr Brackets(int i): i(i) {} void operator[](int) _diagnose_if(i == 1, "oh no", "warning") // expected-note{{from 'diagnose_if'}} _diagnose_if(i == 2, "oh no", "error"); // expected-note{{from 'diagnose_if'}} }; void runBrackets(int i) { Brackets{0}[i]; Brackets{1}[i]; // expected-warning{{oh no}} Brackets{2}[i]; // expected-error{{oh no}} } struct Unary { int i; constexpr Unary(int i): i(i) {} void operator+() _diagnose_if(i == 1, "oh no", "warning") // expected-note{{from 'diagnose_if'}} _diagnose_if(i == 2, "oh no", "error"); // expected-note{{from 'diagnose_if'}} }; void runUnary() { +Unary{0}; +Unary{1}; // expected-warning{{oh no}} +Unary{2}; // expected-error{{oh no}} } struct PostInc { void operator++(int i) _diagnose_if(i == 1, "oh no", "warning") // expected-note{{from 'diagnose_if'}} _diagnose_if(i == 2, "oh no", "error"); // expected-note{{from 'diagnose_if'}} }; void runPostInc() { PostInc{}++; PostInc{}.operator++(1); // expected-warning{{oh no}} PostInc{}.operator++(2); // expected-error{{oh no}} } } namespace ctors { struct Foo { int I; constexpr Foo(int I): I(I) {} constexpr const Foo &operator=(const Foo &) const _diagnose_if(I, "oh no", "error") { // expected-note{{from 'diagnose_if'}} return *this; } constexpr const Foo &operator=(const Foo &&) const _diagnose_if(I, "oh no", "error") { // expected-note{{from 'diagnose_if'}} return *this; } }; struct Bar { int I; constexpr Bar(int I) _diagnose_if(I == 1, "oh no", "warning") // expected-note{{from 'diagnose_if'}} _diagnose_if(I == 2, "oh no", "error"): I(I) {} // expected-note{{from 'diagnose_if'}} }; void run() { constexpr Foo F{0}; constexpr Foo F2{1}; F2 = F; // expected-error{{oh no}} F2 = Foo{2}; // expected-error{{oh no}} Bar{0}; Bar{1}; // expected-warning{{oh no}} Bar{2}; // expected-error{{oh no}} } } namespace ref_init { struct Bar {}; struct Baz {}; struct Foo { int i; constexpr Foo(int i): i(i) {} operator const Bar &() const _diagnose_if(i, "oh no", "warning"); // expected-note{{from 'diagnose_if'}} operator const Baz &() const _diagnose_if(i, "oh no", "error"); // expected-note{{from 'diagnose_if'}} }; void fooBar(const Bar &b); void fooBaz(const Baz &b); void run() { fooBar(Foo{0}); fooBar(Foo{1}); // expected-warning{{oh no}} fooBaz(Foo{0}); fooBaz(Foo{1}); // expected-error{{oh no}} } } namespace udl { void operator""_fn(char c)_diagnose_if(c == 1, "oh no", "warning") // expected-note{{from 'diagnose_if'}} _diagnose_if(c == 2, "oh no", "error"); // expected-note{{from 'diagnose_if'}} void run() { '\0'_fn; '\1'_fn; // expected-warning{{oh no}} '\2'_fn; // expected-error{{oh no}} } } namespace PR31638 { struct String { String(char const* __s) _diagnose_if(__s == nullptr, "oh no ptr", "warning"); // expected-note{{from 'diagnose_if'}} String(int __s) _diagnose_if(__s != 0, "oh no int", "warning"); // expected-note{{from 'diagnose_if'}} }; void run() { String s(nullptr); // expected-warning{{oh no ptr}} String ss(42); // expected-warning{{oh no int}} } } namespace PR31639 { struct Foo { Foo(int I) __attribute__((diagnose_if(I, "oh no", "error"))); // expected-note{{from 'diagnose_if'}} }; void bar() { Foo f(1); } // expected-error{{oh no}} } namespace user_defined_conversion { struct Foo { int i; constexpr Foo(int i): i(i) {} operator size_t() const _diagnose_if(i == 1, "oh no", "warning") // expected-note{{from 'diagnose_if'}} _diagnose_if(i == 2, "oh no", "error"); // expected-note{{from 'diagnose_if'}} }; void run() { // `new T[N]`, where N is implicitly convertible to size_t, calls // PerformImplicitConversion directly. This lets us test the diagnostic logic // in PerformImplicitConversion. new int[Foo{0}]; new int[Foo{1}]; // expected-warning{{oh no}} new int[Foo{2}]; // expected-error{{oh no}} } } namespace std { template <typename T> struct initializer_list { const T *ptr; size_t elems; constexpr size_t size() const { return elems; } }; } namespace initializer_lists { struct Foo { Foo(std::initializer_list<int> l) _diagnose_if(l.size() == 1, "oh no", "warning") // expected-note{{from 'diagnose_if'}} _diagnose_if(l.size() == 2, "oh no", "error") {} // expected-note{{from 'diagnose_if'}} }; void run() { Foo{std::initializer_list<int>{}}; Foo{std::initializer_list<int>{1}}; // expected-warning{{oh no}} Foo{std::initializer_list<int>{1, 2}}; // expected-error{{oh no}} Foo{std::initializer_list<int>{1, 2, 3}}; } } namespace range_for_loop { namespace adl { struct Foo { int i; constexpr Foo(int i): i(i) {} }; void **begin(const Foo &f) _diagnose_if(f.i, "oh no", "warning"); void **end(const Foo &f) _diagnose_if(f.i, "oh no", "warning"); struct Bar { int i; constexpr Bar(int i): i(i) {} }; void **begin(const Bar &b) _diagnose_if(b.i, "oh no", "error"); void **end(const Bar &b) _diagnose_if(b.i, "oh no", "error"); } void run() { for (void *p : adl::Foo(0)) {} // FIXME: This should emit diagnostics. It seems that our constexpr // evaluator isn't able to evaluate `adl::Foo(1)` as a constant, though. for (void *p : adl::Foo(1)) {} for (void *p : adl::Bar(0)) {} // FIXME: Same thing. for (void *p : adl::Bar(1)) {} } } namespace operator_new { struct Foo { int j; static void *operator new(size_t i) _diagnose_if(i, "oh no", "warning"); }; struct Bar { int j; static void *operator new(size_t i) _diagnose_if(!i, "oh no", "warning"); }; void run() { // FIXME: This should emit a diagnostic. new Foo(); // This is here because we sometimes pass a dummy argument `operator new`. We // should ignore this, rather than complaining about it. new Bar(); } } namespace contextual_implicit_conv { struct Foo { int i; constexpr Foo(int i): i(i) {} constexpr operator int() const _diagnose_if(i == 1, "oh no", "warning") // expected-note{{from 'diagnose_if'}} _diagnose_if(i == 2, "oh no", "error") { // expected-note{{from 'diagnose_if'}} return i; } }; void run() { switch (constexpr Foo i = 0) { default: break; } switch (constexpr Foo i = 1) { default: break; } // expected-warning{{oh no}} switch (constexpr Foo i = 2) { default: break; } // expected-error{{oh no}} } }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_parallel_for_simd_misc_messages.c
312
// RUN: %clang_cc1 -fsyntax-only -fopenmp -verify %s // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute parallel for simd'}} #pragma omp target teams distribute parallel for simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp target teams distribute parallel for simd'}} #pragma omp target teams distribute parallel for simd foo void test_no_clause() { int i; #pragma omp target teams distribute parallel for simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp target teams distribute parallel for simd' must be a for loop}} #pragma omp target teams distribute parallel for simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp target teams distribute parallel for simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd; for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp target teams distribute parallel for simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp target teams distribute parallel for simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} #pragma omp target teams distribute parallel for simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp target teams distribute parallel for simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target teams distribute parallel for simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp target teams distribute parallel for simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-error@+4 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp target teams distribute parallel for simd collapse(2) firstprivate(i) for (i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) #pragma omp parallel for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute parallel for simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute parallel for simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute parallel for simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute parallel for simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp target teams distribute parallel for simd firstprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp target teams distribute parallel for simd firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp target teams distribute parallel for simd lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp target teams distribute parallel for simd lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute parallel for simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp target teams distribute parallel for simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_parallel_codegen.cpp
802
// Test host codegen. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32 // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-DAG: %ident_t = type { i32, i32, i32, i32, i8* } // CHECK-DAG: [[STR:@.+]] = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00" // CHECK-DAG: [[DEF_LOC:@.+]] = private unnamed_addr constant %ident_t { i32 0, i32 2, i32 0, i32 0, i8* getelementptr inbounds ([23 x i8], [23 x i8]* [[STR]], i32 0, i32 0) } // CHECK-DAG: [[TT:%.+]] = type { i64, i8 } // CHECK-DAG: [[S1:%.+]] = type { double } // CHECK-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 } // CHECK-DAG: [[DEVTY:%.+]] = type { i8*, i8*, [[ENTTY]]*, [[ENTTY]]* } // CHECK-DAG: [[DSCTY:%.+]] = type { i32, [[DEVTY]]*, [[ENTTY]]*, [[ENTTY]]* } // TCHECK: [[ENTTY:%.+]] = type { i8*, i8*, i{{32|64}}, i32, i32 } // We have 8 target regions, but only 7 that actually will generate offloading // code, only 6 will have mapped arguments, and only 4 have all-constant map // sizes. // CHECK-DAG: [[SIZET2:@.+]] = private unnamed_addr constant [1 x i{{32|64}}] [i[[SZ:32|64]] 2] // CHECK-DAG: [[MAPT2:@.+]] = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: [[SIZET3:@.+]] = private unnamed_addr constant [2 x i[[SZ]]] [i[[SZ]] 4, i[[SZ]] 2] // CHECK-DAG: [[MAPT3:@.+]] = private unnamed_addr constant [2 x i32] [i32 288, i32 288] // CHECK-DAG: [[MAPT4:@.+]] = private unnamed_addr constant [9 x i32] [i32 288, i32 35, i32 288, i32 35, i32 35, i32 288, i32 288, i32 35, i32 35] // CHECK-DAG: [[SIZET5:@.+]] = private unnamed_addr constant [3 x i[[SZ]]] [i[[SZ]] 4, i[[SZ]] 2, i[[SZ]] 40] // CHECK-DAG: [[MAPT5:@.+]] = private unnamed_addr constant [3 x i32] [i32 288, i32 288, i32 35] // CHECK-DAG: [[SIZET6:@.+]] = private unnamed_addr constant [4 x i[[SZ]]] [i[[SZ]] 4, i[[SZ]] 2, i[[SZ]] 1, i[[SZ]] 40] // CHECK-DAG: [[MAPT6:@.+]] = private unnamed_addr constant [4 x i32] [i32 288, i32 288, i32 288, i32 35] // CHECK-DAG: [[MAPT7:@.+]] = private unnamed_addr constant [5 x i32] [i32 35, i32 288, i32 288, i32 288, i32 35] // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK-NOT: @{{.+}} = constant [[ENTTY]] // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] // CHECK: [[DEVBEGIN:@.+]] = external constant i8 // CHECK: [[DEVEND:@.+]] = external constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }] // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] } // Check target registration is registered as a Ctor. // CHECK: appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* bitcast (void (i8*)* [[REGFN:@.+]] to void ()*), i8* null }] template<typename tx, typename ty> struct TT{ tx X; ty Y; }; // CHECK: define {{.*}}[[FOO:@.+]]( int foo(int n) { int a = 0; short aa = 0; float b[10]; float bn[n]; double c[5][10]; double cn[5][n]; TT<long long, char> d; // CHECK: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 0, i8** null, i8** null, i[[SZ]]* null, i32* null, i32 1, i32 0) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT0:@.+]]() // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] #pragma omp target parallel { } // CHECK: store i32 0, i32* [[RHV:%.+]], align 4 // CHECK: store i32 -1, i32* [[RHV]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: call void [[HVT1:@.+]](i[[SZ]] {{[^,]+}}) #pragma omp target parallel if(target: 0) { a += 1; } // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 1, i8** [[BP:%[^,]+]], i8** [[P:%[^,]+]], i[[SZ]]* getelementptr inbounds ([1 x i[[SZ]]], [1 x i[[SZ]]]* [[SIZET2]], i32 0, i32 0), i32* getelementptr inbounds ([1 x i32], [1 x i32]* [[MAPT2]], i32 0, i32 0), i32 1, i32 0) // CHECK-DAG: [[BP]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BPR:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[P]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[PR:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BPR]], i32 0, i32 [[IDX0:[0-9]+]] // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[PR]], i32 0, i32 [[IDX0]] // CHECK-DAG: store i8* [[BP0:%[^,]+]], i8** [[BPADDR0]] // CHECK-DAG: store i8* [[P0:%[^,]+]], i8** [[PADDR0]] // CHECK-DAG: [[BP0]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK-DAG: [[P0]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT2:@.+]](i[[SZ]] {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] #pragma omp target parallel if(target: 1) { aa += 1; } // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 10 // CHECK: br i1 [[IF]], label %[[IFTHEN:[^,]+]], label %[[IFELSE:[^,]+]] // CHECK: [[IFTHEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 2, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* getelementptr inbounds ([2 x i[[SZ]]], [2 x i[[SZ]]]* [[SIZET3]], i32 0, i32 0), i32* getelementptr inbounds ([2 x i32], [2 x i32]* [[MAPT3]], i32 0, i32 0), i32 1, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP]], i32 0, i32 0 // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P]], i32 0, i32 0 // CHECK-DAG: store i8* [[BP0:%[^,]+]], i8** [[BPADDR0]] // CHECK-DAG: store i8* [[P0:%[^,]+]], i8** [[PADDR0]] // CHECK-DAG: [[BP0]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK-DAG: [[P0]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP]], i32 0, i32 1 // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P]], i32 0, i32 1 // CHECK-DAG: store i8* [[BP1:%[^,]+]], i8** [[BPADDR1]] // CHECK-DAG: store i8* [[P1:%[^,]+]], i8** [[PADDR1]] // CHECK-DAG: [[BP1]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK-DAG: [[P1]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFELSE]] // CHECK: store i32 -1, i32* [[RHV]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFEND]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT3:@.+]]({{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] #pragma omp target parallel if(target: n>10) { a += 1; aa += 1; } // We capture 3 VLA sizes in this target region // CHECK-64: [[A_VAL:%.+]] = load i32, i32* %{{.+}}, // CHECK-64: [[A_ADDR:%.+]] = bitcast i[[SZ]]* [[A_CADDR:%.+]] to i32* // CHECK-64: store i32 [[A_VAL]], i32* [[A_ADDR]], // CHECK-64: [[A_CVAL:%.+]] = load i[[SZ]], i[[SZ]]* [[A_CADDR]], // CHECK-32: [[A_VAL:%.+]] = load i32, i32* %{{.+}}, // CHECK-32: store i32 [[A_VAL]], i32* [[A_CADDR:%.+]], // CHECK-32: [[A_CVAL:%.+]] = load i[[SZ]], i[[SZ]]* [[A_CADDR]], // CHECK: [[BNSIZE:%.+]] = mul nuw i[[SZ]] [[VLA0:%.+]], 4 // CHECK: [[CNELEMSIZE2:%.+]] = mul nuw i[[SZ]] 5, [[VLA1:%.+]] // CHECK: [[CNSIZE:%.+]] = mul nuw i[[SZ]] [[CNELEMSIZE2]], 8 // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 20 // CHECK: br i1 [[IF]], label %[[TRY:[^,]+]], label %[[FAIL:[^,]+]] // CHECK: [[TRY]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 9, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* [[SR:%[^,]+]], i32* getelementptr inbounds ([9 x i32], [9 x i32]* [[MAPT4]], i32 0, i32 0), i32 1, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[SR]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[SADDR0:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX0:[0-9]+]] // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX0]] // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX0]] // CHECK-DAG: [[SADDR1:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX1:[0-9]+]] // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX1]] // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX1]] // CHECK-DAG: [[SADDR2:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX2:[0-9]+]] // CHECK-DAG: [[BPADDR2:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX2]] // CHECK-DAG: [[PADDR2:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX2]] // CHECK-DAG: [[SADDR3:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX3:[0-9]+]] // CHECK-DAG: [[BPADDR3:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX3]] // CHECK-DAG: [[PADDR3:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX3]] // CHECK-DAG: [[SADDR4:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX4:[0-9]+]] // CHECK-DAG: [[BPADDR4:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX4]] // CHECK-DAG: [[PADDR4:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX4]] // CHECK-DAG: [[SADDR5:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX5:[0-9]+]] // CHECK-DAG: [[BPADDR5:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX5]] // CHECK-DAG: [[PADDR5:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX5]] // CHECK-DAG: [[SADDR6:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX6:[0-9]+]] // CHECK-DAG: [[BPADDR6:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX6]] // CHECK-DAG: [[PADDR6:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX6]] // CHECK-DAG: [[SADDR7:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX7:[0-9]+]] // CHECK-DAG: [[BPADDR7:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX7]] // CHECK-DAG: [[PADDR7:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX7]] // CHECK-DAG: [[SADDR8:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX8:[0-9]+]] // CHECK-DAG: [[BPADDR8:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX8]] // CHECK-DAG: [[PADDR8:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX8]] // The names below are not necessarily consistent with the names used for the // addresses above as some are repeated. // CHECK-DAG: [[BP0:%[^,]+]] = inttoptr i[[SZ]] [[VLA0]] to i8* // CHECK-DAG: [[P0:%[^,]+]] = inttoptr i[[SZ]] [[VLA0]] to i8* // CHECK-DAG: store i8* [[BP0]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P0]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP1:%[^,]+]] = inttoptr i[[SZ]] [[VLA1]] to i8* // CHECK-DAG: [[P1:%[^,]+]] = inttoptr i[[SZ]] [[VLA1]] to i8* // CHECK-DAG: store i8* [[BP1]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P1]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: store i8* inttoptr (i[[SZ]] 5 to i8*), i8** {{%[^,]+}} // CHECK-DAG: store i8* inttoptr (i[[SZ]] 5 to i8*), i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP3:%[^,]+]] = inttoptr i[[SZ]] [[A_CVAL]] to i8* // CHECK-DAG: [[P3:%[^,]+]] = inttoptr i[[SZ]] [[A_CVAL]] to i8* // CHECK-DAG: store i8* [[BP3]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P3]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 4, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP4:%[^,]+]] = bitcast [10 x float]* %{{.+}} to i8* // CHECK-DAG: [[P4:%[^,]+]] = bitcast [10 x float]* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP4]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P4]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 40, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP5:%[^,]+]] = bitcast float* %{{.+}} to i8* // CHECK-DAG: [[P5:%[^,]+]] = bitcast float* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP5]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P5]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] [[BNSIZE]], i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP6:%[^,]+]] = bitcast [5 x [10 x double]]* %{{.+}} to i8* // CHECK-DAG: [[P6:%[^,]+]] = bitcast [5 x [10 x double]]* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP6]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P6]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 400, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP7:%[^,]+]] = bitcast double* %{{.+}} to i8* // CHECK-DAG: [[P7:%[^,]+]] = bitcast double* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP7]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P7]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] [[CNSIZE]], i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP8:%[^,]+]] = bitcast [[TT]]* %{{.+}} to i8* // CHECK-DAG: [[P8:%[^,]+]] = bitcast [[TT]]* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP8]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P8]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{12|16}}, i[[SZ]]* {{%[^,]+}} // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT4:@.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] #pragma omp target parallel if(target: n>20) { a += 1; b[2] += 1.0; bn[3] += 1.0; c[1][2] += 1.0; cn[1][3] += 1.0; d.X += 1; d.Y += 1; } return a; } // Check that the offloading functions are emitted and that the arguments are // correct and loaded correctly for the target regions in foo(). // CHECK: define internal void [[HVT0]]() // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* [[OMP_OUTLINED:@.+]] to void (i32*, i32*, ...)*)) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED]](i32* noalias %.global_tid., i32* noalias %.bound_tid.) // CHECK: ret void // CHECK-NEXT: } // CHECK: define internal void [[HVT1]](i[[SZ]] %{{.+}}) // Create stack storage and store argument in there. // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_CASTED:%.+]] = alloca i[[SZ]], align // CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK-64: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i32* // CHECK-64: [[AA:%.+]] = load i32, i32* [[AA_CADDR]], align // CHECK-32: [[AA:%.+]] = load i32, i32* [[AA_ADDR]], align // CHECK-64: [[AA_C:%.+]] = bitcast i[[SZ]]* [[AA_CASTED]] to i32* // CHECK-64: store i32 [[AA]], i32* [[AA_C]], align // CHECK-32: store i32 [[AA]], i32* [[AA_CASTED]], align // CHECK: [[PARAM:%.+]] = load i[[SZ]], i[[SZ]]* [[AA_CASTED]], align // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]])* [[OMP_OUTLINED1:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[PARAM]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED1]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}) // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK-64: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i32* // CHECK-64: [[AA:%.+]] = load i32, i32* [[AA_CADDR]], align // CHECK-32: [[AA:%.+]] = load i32, i32* [[AA_ADDR]], align // CHECK: ret void // CHECK-NEXT: } // CHECK: define internal void [[HVT2]](i[[SZ]] %{{.+}}) // Create stack storage and store argument in there. // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_CASTED:%.+]] = alloca i[[SZ]], align // CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK: [[AA:%.+]] = load i16, i16* [[AA_CADDR]], align // CHECK: [[AA_C:%.+]] = bitcast i[[SZ]]* [[AA_CASTED]] to i16* // CHECK: store i16 [[AA]], i16* [[AA_C]], align // CHECK: [[PARAM:%.+]] = load i[[SZ]], i[[SZ]]* [[AA_CASTED]], align // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]])* [[OMP_OUTLINED2:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[PARAM]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED2]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}) // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK: [[AA:%.+]] = load i16, i16* [[AA_CADDR]], align // CHECK: ret void // CHECK-NEXT: } // CHECK: define internal void [[HVT3]] // Create stack storage and store argument in there. // CHECK: [[A_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[A_CASTED:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_CASTED:%.+]] = alloca i[[SZ]], align // CHECK-DAG: store i[[SZ]] %{{.+}}, i[[SZ]]* [[A_ADDR]], align // CHECK-DAG: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK-64-DAG:[[A_CADDR:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i32* // CHECK-DAG: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK-64-DAG:[[A:%.+]] = load i32, i32* [[A_CADDR]], align // CHECK-32-DAG:[[A:%.+]] = load i32, i32* [[A_ADDR]], align // CHECK-64-DAG:[[A_C:%.+]] = bitcast i[[SZ]]* [[A_CASTED]] to i32* // CHECK-64-DAG:store i32 [[A]], i32* [[A_C]], align // CHECK-32-DAG:store i32 [[A]], i32* [[A_CASTED]], align // CHECK-DAG: [[AA:%.+]] = load i16, i16* [[AA_CADDR]], align // CHECK-DAG: [[AA_C:%.+]] = bitcast i[[SZ]]* [[AA_CASTED]] to i16* // CHECK-DAG: store i16 [[AA]], i16* [[AA_C]], align // CHECK-DAG: [[PARAM1:%.+]] = load i[[SZ]], i[[SZ]]* [[A_CASTED]], align // CHECK-DAG: [[PARAM2:%.+]] = load i[[SZ]], i[[SZ]]* [[AA_CASTED]], align // CHECK-DAG: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 2, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]])* [[OMP_OUTLINED3:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[PARAM1]], i[[SZ]] [[PARAM2]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED3]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}) // CHECK: [[A_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK-DAG: store i[[SZ]] %{{.+}}, i[[SZ]]* [[A_ADDR]], align // CHECK-DAG: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK-64-DAG:[[A_CADDR:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i32* // CHECK-DAG: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK: ret void // CHECK-NEXT: } // CHECK: define internal void [[HVT4]] // Create local storage for each capture. // CHECK: [[LOCAL_A:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_B:%.+]] = alloca [10 x float]* // CHECK: [[LOCAL_VLA1:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_BN:%.+]] = alloca float* // CHECK: [[LOCAL_C:%.+]] = alloca [5 x [10 x double]]* // CHECK: [[LOCAL_VLA2:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_VLA3:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_CN:%.+]] = alloca double* // CHECK: [[LOCAL_D:%.+]] = alloca [[TT]]* // CHECK: [[LOCAL_A_CASTED:%.+]] = alloca i[[SZ]] // CHECK-DAG: store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]] // CHECK-DAG: store [10 x float]* [[ARG_B:%.+]], [10 x float]** [[LOCAL_B]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA1:%.+]], i[[SZ]]* [[LOCAL_VLA1]] // CHECK-DAG: store float* [[ARG_BN:%.+]], float** [[LOCAL_BN]] // CHECK-DAG: store [5 x [10 x double]]* [[ARG_C:%.+]], [5 x [10 x double]]** [[LOCAL_C]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA2:%.+]], i[[SZ]]* [[LOCAL_VLA2]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA3:%.+]], i[[SZ]]* [[LOCAL_VLA3]] // CHECK-DAG: store double* [[ARG_CN:%.+]], double** [[LOCAL_CN]] // CHECK-DAG: store [[TT]]* [[ARG_D:%.+]], [[TT]]** [[LOCAL_D]] // CHECK-64-DAG:[[CONV_AP:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32* // CHECK-DAG: [[REF_B:%.+]] = load [10 x float]*, [10 x float]** [[LOCAL_B]], // CHECK-DAG: [[VAL_VLA1:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA1]], // CHECK-DAG: [[REF_BN:%.+]] = load float*, float** [[LOCAL_BN]], // CHECK-DAG: [[REF_C:%.+]] = load [5 x [10 x double]]*, [5 x [10 x double]]** [[LOCAL_C]], // CHECK-DAG: [[VAL_VLA2:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA2]], // CHECK-DAG: [[VAL_VLA3:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA3]], // CHECK-DAG: [[REF_CN:%.+]] = load double*, double** [[LOCAL_CN]], // CHECK-DAG: [[REF_D:%.+]] = load [[TT]]*, [[TT]]** [[LOCAL_D]], // CHECK-64-DAG:[[CONV_A:%.+]] = load i32, i32* [[CONV_AP]] // CHECK-64-DAG:[[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_A_CASTED]] to i32* // CHECK-64-DAG:store i32 [[CONV_A]], i32* [[CONV]], align // CHECK-32-DAG:[[LOCAL_AV:%.+]] = load i32, i32* [[LOCAL_A]] // CHECK-32-DAG:store i32 [[LOCAL_AV]], i32* [[LOCAL_A_CASTED]], align // CHECK-DAG: [[REF_A:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_A_CASTED]], // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 9, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], [10 x float]*, i[[SZ]], float*, [5 x [10 x double]]*, i[[SZ]], i[[SZ]], double*, [[TT]]*)* [[OMP_OUTLINED4:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[REF_A]], [10 x float]* [[REF_B]], i[[SZ]] [[VAL_VLA1]], float* [[REF_BN]], [5 x [10 x double]]* [[REF_C]], i[[SZ]] [[VAL_VLA2]], i[[SZ]] [[VAL_VLA3]], double* [[REF_CN]], [[TT]]* [[REF_D]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED4]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, [10 x float]* {{.+}}, i[[SZ]] %{{.+}}, float* %{{.+}}, [5 x [10 x double]]* {{.+}}, i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, double* %{{.+}}, [[TT]]* {{.+}}) // To reduce complexity, we're only going as far as validating the signature of the outlined parallel function. template<typename tx> tx ftemplate(int n) { tx a = 0; short aa = 0; tx b[10]; #pragma omp target parallel if(target: n>40) { a += 1; aa += 1; b[2] += 1; } return a; } static int fstatic(int n) { int a = 0; short aa = 0; char aaa = 0; int b[10]; #pragma omp target parallel if(target: n>50) { a += 1; aa += 1; aaa += 1; b[2] += 1; } return a; } struct S1 { double a; int r1(int n){ int b = n+1; short int c[2][n]; #pragma omp target parallel if(target: n>60) { this->a = (double)b + 1.5; c[1][1] = ++a; } return c[1][1] + (int)b; } }; // CHECK: define {{.*}}@{{.*}}bar{{.*}} int bar(int n){ int a = 0; // CHECK: call {{.*}}i32 [[FOO]](i32 {{.*}}) a += foo(n); S1 S; // CHECK: call {{.*}}i32 [[FS1:@.+]]([[S1]]* {{.*}}, i32 {{.*}}) a += S.r1(n); // CHECK: call {{.*}}i32 [[FSTATIC:@.+]](i32 {{.*}}) a += fstatic(n); // CHECK: call {{.*}}i32 [[FTEMPLATE:@.+]](i32 {{.*}}) a += ftemplate<int>(n); return a; } // // CHECK: define {{.*}}[[FS1]] // // CHECK: i8* @llvm.stacksave() // CHECK-64: [[B_ADDR:%.+]] = bitcast i[[SZ]]* [[B_CADDR:%.+]] to i32* // CHECK-64: store i32 %{{.+}}, i32* [[B_ADDR]], // CHECK-64: [[B_CVAL:%.+]] = load i[[SZ]], i[[SZ]]* [[B_CADDR]], // CHECK-32: store i32 %{{.+}}, i32* [[B_ADDR:%.+]], // CHECK-32: [[B_CVAL:%.+]] = load i[[SZ]], i[[SZ]]* [[B_ADDR]], // We capture 2 VLA sizes in this target region // CHECK: [[CELEMSIZE2:%.+]] = mul nuw i[[SZ]] 2, [[VLA0:%.+]] // CHECK: [[CSIZE:%.+]] = mul nuw i[[SZ]] [[CELEMSIZE2]], 2 // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 60 // CHECK: br i1 [[IF]], label %[[TRY:[^,]+]], label %[[FAIL:[^,]+]] // CHECK: [[TRY]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 5, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* [[SR:%[^,]+]], i32* getelementptr inbounds ([5 x i32], [5 x i32]* [[MAPT7]], i32 0, i32 0), i32 1, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP:%.+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P:%.+]], i32 0, i32 0 // CHECK-DAG: [[SR]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S:%.+]], i32 0, i32 0 // CHECK-DAG: [[SADDR0:%.+]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S]], i32 [[IDX0:[0-9]+]] // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP]], i32 [[IDX0]] // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P]], i32 [[IDX0]] // CHECK-DAG: [[SADDR1:%.+]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S]], i32 [[IDX1:[0-9]+]] // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP]], i32 [[IDX1]] // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P]], i32 [[IDX1]] // CHECK-DAG: [[SADDR2:%.+]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S]], i32 [[IDX2:[0-9]+]] // CHECK-DAG: [[BPADDR2:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP]], i32 [[IDX2]] // CHECK-DAG: [[PADDR2:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P]], i32 [[IDX2]] // CHECK-DAG: [[SADDR3:%.+]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S]], i32 [[IDX3:[0-9]+]] // CHECK-DAG: [[BPADDR3:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP]], i32 [[IDX3]] // CHECK-DAG: [[PADDR3:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P]], i32 [[IDX3]] // The names below are not necessarily consistent with the names used for the // addresses above as some are repeated. // CHECK-DAG: [[BP0:%[^,]+]] = inttoptr i[[SZ]] [[VLA0]] to i8* // CHECK-DAG: [[P0:%[^,]+]] = inttoptr i[[SZ]] [[VLA0]] to i8* // CHECK-DAG: store i8* [[BP0]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P0]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: store i8* inttoptr (i[[SZ]] 2 to i8*), i8** {{%[^,]+}} // CHECK-DAG: store i8* inttoptr (i[[SZ]] 2 to i8*), i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP2:%[^,]+]] = inttoptr i[[SZ]] [[B_CVAL]] to i8* // CHECK-DAG: [[P2:%[^,]+]] = inttoptr i[[SZ]] [[B_CVAL]] to i8* // CHECK-DAG: store i8* [[BP2]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P2]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 4, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP3:%[^,]+]] = bitcast [[S1]]* %{{.+}} to i8* // CHECK-DAG: [[P3:%[^,]+]] = bitcast [[S1]]* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP3]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P3]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 8, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP4:%[^,]+]] = bitcast i16* %{{.+}} to i8* // CHECK-DAG: [[P4:%[^,]+]] = bitcast i16* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP4]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P4]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] [[CSIZE]], i[[SZ]]* {{%[^,]+}} // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT7:@.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] // // CHECK: define {{.*}}[[FSTATIC]] // // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 50 // CHECK: br i1 [[IF]], label %[[IFTHEN:[^,]+]], label %[[IFELSE:[^,]+]] // CHECK: [[IFTHEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 4, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* getelementptr inbounds ([4 x i[[SZ]]], [4 x i[[SZ]]]* [[SIZET6]], i32 0, i32 0), i32* getelementptr inbounds ([4 x i32], [4 x i32]* [[MAPT6]], i32 0, i32 0), i32 1, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP:%.+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P:%.+]], i32 0, i32 0 // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP]], i32 0, i32 0 // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P]], i32 0, i32 0 // CHECK-DAG: store i8* [[BP0:%[^,]+]], i8** [[BPADDR0]] // CHECK-DAG: store i8* [[P0:%[^,]+]], i8** [[PADDR0]] // CHECK-DAG: [[BP0]] = inttoptr i[[SZ]] [[VAL0:%.+]] to i8* // CHECK-DAG: [[P0]] = inttoptr i[[SZ]] [[VAL0]] to i8* // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP]], i32 0, i32 1 // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P]], i32 0, i32 1 // CHECK-DAG: store i8* [[BP1:%[^,]+]], i8** [[BPADDR1]] // CHECK-DAG: store i8* [[P1:%[^,]+]], i8** [[PADDR1]] // CHECK-DAG: [[BP1]] = inttoptr i[[SZ]] [[VAL1:%.+]] to i8* // CHECK-DAG: [[P1]] = inttoptr i[[SZ]] [[VAL1]] to i8* // CHECK-DAG: [[BPADDR2:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP]], i32 0, i32 2 // CHECK-DAG: [[PADDR2:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P]], i32 0, i32 2 // CHECK-DAG: store i8* [[BP2:%[^,]+]], i8** [[BPADDR2]] // CHECK-DAG: store i8* [[P2:%[^,]+]], i8** [[PADDR2]] // CHECK-DAG: [[BPADDR3:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP]], i32 0, i32 3 // CHECK-DAG: [[PADDR3:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P]], i32 0, i32 3 // CHECK-DAG: store i8* [[BP3:%[^,]+]], i8** [[BPADDR3]] // CHECK-DAG: store i8* [[P3:%[^,]+]], i8** [[PADDR3]] // CHECK-DAG: [[BP3]] = bitcast [10 x i32]* %{{.+}} to i8* // CHECK-DAG: [[P3]] = bitcast [10 x i32]* %{{.+}} to i8* // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFELSE]] // CHECK: store i32 -1, i32* [[RHV]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFEND]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT6:@.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] // // CHECK: define {{.*}}[[FTEMPLATE]] // // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 40 // CHECK: br i1 [[IF]], label %[[IFTHEN:[^,]+]], label %[[IFELSE:[^,]+]] // CHECK: [[IFTHEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 3, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* getelementptr inbounds ([3 x i[[SZ]]], [3 x i[[SZ]]]* [[SIZET5]], i32 0, i32 0), i32* getelementptr inbounds ([3 x i32], [3 x i32]* [[MAPT5]], i32 0, i32 0), i32 1, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[BP:%.+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[P:%.+]], i32 0, i32 0 // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[BP]], i32 0, i32 0 // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[P]], i32 0, i32 0 // CHECK-DAG: store i8* [[BP0:%[^,]+]], i8** [[BPADDR0]] // CHECK-DAG: store i8* [[P0:%[^,]+]], i8** [[PADDR0]] // CHECK-DAG: [[BP0]] = inttoptr i[[SZ]] [[VAL0:%.+]] to i8* // CHECK-DAG: [[P0]] = inttoptr i[[SZ]] [[VAL0]] to i8* // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[BP]], i32 0, i32 1 // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[P]], i32 0, i32 1 // CHECK-DAG: store i8* [[BP1:%[^,]+]], i8** [[BPADDR1]] // CHECK-DAG: store i8* [[P1:%[^,]+]], i8** [[PADDR1]] // CHECK-DAG: [[BP1]] = inttoptr i[[SZ]] [[VAL1:%.+]] to i8* // CHECK-DAG: [[P1]] = inttoptr i[[SZ]] [[VAL1]] to i8* // CHECK-DAG: [[BPADDR2:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[BP]], i32 0, i32 2 // CHECK-DAG: [[PADDR2:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[P]], i32 0, i32 2 // CHECK-DAG: store i8* [[BP2:%[^,]+]], i8** [[BPADDR2]] // CHECK-DAG: store i8* [[P2:%[^,]+]], i8** [[PADDR2]] // CHECK-DAG: [[BP2]] = bitcast [10 x i32]* %{{.+}} to i8* // CHECK-DAG: [[P2]] = bitcast [10 x i32]* %{{.+}} to i8* // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFELSE]] // CHECK: store i32 -1, i32* [[RHV]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFEND]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT5:@.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] // Check that the offloading functions are emitted and that the arguments are // correct and loaded correctly for the target regions of the callees of bar(). // CHECK: define internal void [[HVT7]] // Create local storage for each capture. // CHECK: [[LOCAL_THIS:%.+]] = alloca [[S1]]* // CHECK: [[LOCAL_B:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_VLA1:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_VLA2:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_C:%.+]] = alloca i16* // CHECK: [[LOCAL_B_CASTED:%.+]] = alloca i[[SZ]] // CHECK-DAG: store [[S1]]* [[ARG_THIS:%.+]], [[S1]]** [[LOCAL_THIS]] // CHECK-DAG: store i[[SZ]] [[ARG_B:%.+]], i[[SZ]]* [[LOCAL_B]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA1:%.+]], i[[SZ]]* [[LOCAL_VLA1]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA2:%.+]], i[[SZ]]* [[LOCAL_VLA2]] // CHECK-DAG: store i16* [[ARG_C:%.+]], i16** [[LOCAL_C]] // Store captures in the context. // CHECK-DAG: [[REF_THIS:%.+]] = load [[S1]]*, [[S1]]** [[LOCAL_THIS]], // CHECK-64-DAG:[[CONV_BP:%.+]] = bitcast i[[SZ]]* [[LOCAL_B]] to i32* // CHECK-DAG: [[VAL_VLA1:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA1]], // CHECK-DAG: [[VAL_VLA2:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA2]], // CHECK-DAG: [[REF_C:%.+]] = load i16*, i16** [[LOCAL_C]], // CHECK-64-DAG:[[CONV_B:%.+]] = load i32, i32* [[CONV_BP]] // CHECK-64-DAG:[[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_B_CASTED]] to i32* // CHECK-64-DAG:store i32 [[CONV_B]], i32* [[CONV]], align // CHECK-32-DAG:[[LOCAL_BV:%.+]] = load i32, i32* [[LOCAL_B]] // CHECK-32-DAG:store i32 [[LOCAL_BV]], i32* [[LOCAL_B_CASTED]], align // CHECK-DAG: [[REF_B:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_B_CASTED]], // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 5, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, [[S1]]*, i[[SZ]], i[[SZ]], i[[SZ]], i16*)* [[OMP_OUTLINED5:@.+]] to void (i32*, i32*, ...)*), [[S1]]* [[REF_THIS]], i[[SZ]] [[REF_B]], i[[SZ]] [[VAL_VLA1]], i[[SZ]] [[VAL_VLA2]], i16* [[REF_C]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED5]](i32* noalias %.global_tid., i32* noalias %.bound_tid., [[S1]]* %{{.+}}, i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, i16* %{{.+}}) // To reduce complexity, we're only going as far as validating the signature of the outlined parallel function. // CHECK: define internal void [[HVT6]] // Create local storage for each capture. // CHECK: [[LOCAL_A:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AA:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AAA:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_B:%.+]] = alloca [10 x i32]* // CHECK: [[LOCAL_A_CASTED:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AA_CASTED:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AAA_CASTED:%.+]] = alloca i[[SZ]] // CHECK-DAG: store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]] // CHECK-DAG: store i[[SZ]] [[ARG_AA:%.+]], i[[SZ]]* [[LOCAL_AA]] // CHECK-DAG: store i[[SZ]] [[ARG_AAA:%.+]], i[[SZ]]* [[LOCAL_AAA]] // CHECK-DAG: store [10 x i32]* [[ARG_B:%.+]], [10 x i32]** [[LOCAL_B]] // Store captures in the context. // CHECK-64-DAG:[[CONV_AP:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32* // CHECK-DAG: [[CONV_AAP:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA]] to i16* // CHECK-DAG: [[CONV_AAAP:%.+]] = bitcast i[[SZ]]* [[LOCAL_AAA]] to i8* // CHECK-DAG: [[REF_B:%.+]] = load [10 x i32]*, [10 x i32]** [[LOCAL_B]], // CHECK-64-DAG:[[CONV_A:%.+]] = load i32, i32* [[CONV_AP]] // CHECK-64-DAG:[[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_A_CASTED]] to i32* // CHECK-64-DAG:store i32 [[CONV_A]], i32* [[CONV]], align // CHECK-32-DAG:[[LOCAL_AV:%.+]] = load i32, i32* [[LOCAL_A]] // CHECK-32-DAG:store i32 [[LOCAL_AV]], i32* [[LOCAL_A_CASTED]], align // CHECK-DAG: [[REF_A:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_A_CASTED]], // CHECK-DAG: [[CONV_AA:%.+]] = load i16, i16* [[CONV_AAP]] // CHECK-DAG: [[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA_CASTED]] to i16* // CHECK-DAG: store i16 [[CONV_AA]], i16* [[CONV]], align // CHECK-DAG: [[REF_AA:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_AA_CASTED]], // CHECK-DAG: [[CONV_AAA:%.+]] = load i8, i8* [[CONV_AAAP]] // CHECK-DAG: [[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_AAA_CASTED]] to i8* // CHECK-DAG: store i8 [[CONV_AAA]], i8* [[CONV]], align // CHECK-DAG: [[REF_AAA:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_AAA_CASTED]], // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 4, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]], i[[SZ]], [10 x i32]*)* [[OMP_OUTLINED6:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[REF_A]], i[[SZ]] [[REF_AA]], i[[SZ]] [[REF_AAA]], [10 x i32]* [[REF_B]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED6]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, [10 x i32]* {{.+}}) // To reduce complexity, we're only going as far as validating the signature of the outlined parallel function. // CHECK: define internal void [[HVT5]] // Create local storage for each capture. // CHECK: [[LOCAL_A:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AA:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_B:%.+]] = alloca [10 x i32]* // CHECK: [[LOCAL_A_CASTED:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AA_CASTED:%.+]] = alloca i[[SZ]] // CHECK-DAG: store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]] // CHECK-DAG: store i[[SZ]] [[ARG_AA:%.+]], i[[SZ]]* [[LOCAL_AA]] // CHECK-DAG: store [10 x i32]* [[ARG_B:%.+]], [10 x i32]** [[LOCAL_B]] // Store captures in the context. // CHECK-64-DAG:[[CONV_AP:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32* // CHECK-DAG: [[CONV_AAP:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA]] to i16* // CHECK-DAG: [[REF_B:%.+]] = load [10 x i32]*, [10 x i32]** [[LOCAL_B]], // CHECK-64-DAG:[[CONV_A:%.+]] = load i32, i32* [[CONV_AP]] // CHECK-64-DAG:[[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_A_CASTED]] to i32* // CHECK-64-DAG:store i32 [[CONV_A]], i32* [[CONV]], align // CHECK-32-DAG:[[LOCAL_AV:%.+]] = load i32, i32* [[LOCAL_A]] // CHECK-32-DAG:store i32 [[LOCAL_AV]], i32* [[LOCAL_A_CASTED]], align // CHECK-DAG: [[REF_A:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_A_CASTED]], // CHECK-DAG: [[CONV_AA:%.+]] = load i16, i16* [[CONV_AAP]] // CHECK-DAG: [[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA_CASTED]] to i16* // CHECK-DAG: store i16 [[CONV_AA]], i16* [[CONV]], align // CHECK-DAG: [[REF_AA:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_AA_CASTED]], // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 3, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]], [10 x i32]*)* [[OMP_OUTLINED7:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[REF_A]], i[[SZ]] [[REF_AA]], [10 x i32]* [[REF_B]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED7]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, [10 x i32]* {{.+}}) // To reduce complexity, we're only going as far as validating the signature of the outlined parallel function. #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_codegen.cpp
802
// Test host codegen. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32 // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-DAG: %ident_t = type { i32, i32, i32, i32, i8* } // CHECK-DAG: [[STR:@.+]] = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00" // CHECK-DAG: [[DEF_LOC:@.+]] = private unnamed_addr constant %ident_t { i32 0, i32 2, i32 0, i32 0, i8* getelementptr inbounds ([23 x i8], [23 x i8]* [[STR]], i32 0, i32 0) } // CHECK-DAG: [[TT:%.+]] = type { i64, i8 } // CHECK-DAG: [[S1:%.+]] = type { double } // CHECK-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 } // CHECK-DAG: [[DEVTY:%.+]] = type { i8*, i8*, [[ENTTY]]*, [[ENTTY]]* } // CHECK-DAG: [[DSCTY:%.+]] = type { i32, [[DEVTY]]*, [[ENTTY]]*, [[ENTTY]]* } // TCHECK: [[ENTTY:%.+]] = type { i8*, i8*, i{{32|64}}, i32, i32 } // We have 8 target regions, but only 7 that actually will generate offloading // code, only 6 will have mapped arguments, and only 4 have all-constant map // sizes. // CHECK-DAG: [[SIZET2:@.+]] = private unnamed_addr constant [1 x i{{32|64}}] [i[[SZ:32|64]] 2] // CHECK-DAG: [[MAPT2:@.+]] = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: [[SIZET3:@.+]] = private unnamed_addr constant [2 x i[[SZ]]] [i[[SZ]] 4, i[[SZ]] 2] // CHECK-DAG: [[MAPT3:@.+]] = private unnamed_addr constant [2 x i32] [i32 288, i32 288] // CHECK-DAG: [[MAPT4:@.+]] = private unnamed_addr constant [9 x i32] [i32 288, i32 35, i32 288, i32 35, i32 35, i32 288, i32 288, i32 35, i32 35] // CHECK-DAG: [[SIZET5:@.+]] = private unnamed_addr constant [3 x i[[SZ]]] [i[[SZ]] 4, i[[SZ]] 2, i[[SZ]] 40] // CHECK-DAG: [[MAPT5:@.+]] = private unnamed_addr constant [3 x i32] [i32 288, i32 288, i32 35] // CHECK-DAG: [[SIZET6:@.+]] = private unnamed_addr constant [4 x i[[SZ]]] [i[[SZ]] 4, i[[SZ]] 2, i[[SZ]] 1, i[[SZ]] 40] // CHECK-DAG: [[MAPT6:@.+]] = private unnamed_addr constant [4 x i32] [i32 288, i32 288, i32 288, i32 35] // CHECK-DAG: [[MAPT7:@.+]] = private unnamed_addr constant [5 x i32] [i32 35, i32 288, i32 288, i32 288, i32 35] // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK-NOT: @{{.+}} = constant [[ENTTY]] // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] // CHECK: [[DEVBEGIN:@.+]] = external constant i8 // CHECK: [[DEVEND:@.+]] = external constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }] // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] } // Check target registration is registered as a Ctor. // CHECK: appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* bitcast (void (i8*)* [[REGFN:@.+]] to void ()*), i8* null }] template<typename tx, typename ty> struct TT{ tx X; ty Y; }; // CHECK: define {{.*}}[[FOO:@.+]]( int foo(int n) { int a = 0; short aa = 0; float b[10]; float bn[n]; double c[5][10]; double cn[5][n]; TT<long long, char> d; // CHECK: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 0, i8** null, i8** null, i[[SZ]]* null, i32* null, i32 0, i32 0) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT0:@.+]]() // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] #pragma omp target teams { } // CHECK: store i32 0, i32* [[RHV:%.+]], align 4 // CHECK: store i32 -1, i32* [[RHV]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: call void [[HVT1:@.+]](i[[SZ]] {{[^,]+}}) #pragma omp target teams if(target: 0) { a += 1; } // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 1, i8** [[BP:%[^,]+]], i8** [[P:%[^,]+]], i[[SZ]]* getelementptr inbounds ([1 x i[[SZ]]], [1 x i[[SZ]]]* [[SIZET2]], i32 0, i32 0), i32* getelementptr inbounds ([1 x i32], [1 x i32]* [[MAPT2]], i32 0, i32 0), i32 0, i32 0) // CHECK-DAG: [[BP]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BPR:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[P]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[PR:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[BPR]], i32 0, i32 [[IDX0:[0-9]+]] // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [1 x i8*], [1 x i8*]* [[PR]], i32 0, i32 [[IDX0]] // CHECK-DAG: store i8* [[BP0:%[^,]+]], i8** [[BPADDR0]] // CHECK-DAG: store i8* [[P0:%[^,]+]], i8** [[PADDR0]] // CHECK-DAG: [[BP0]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK-DAG: [[P0]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT2:@.+]](i[[SZ]] {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] #pragma omp target teams if(target: 1) { aa += 1; } // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 10 // CHECK: br i1 [[IF]], label %[[IFTHEN:[^,]+]], label %[[IFELSE:[^,]+]] // CHECK: [[IFTHEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 2, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* getelementptr inbounds ([2 x i[[SZ]]], [2 x i[[SZ]]]* [[SIZET3]], i32 0, i32 0), i32* getelementptr inbounds ([2 x i32], [2 x i32]* [[MAPT3]], i32 0, i32 0), i32 0, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP]], i32 0, i32 0 // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P]], i32 0, i32 0 // CHECK-DAG: store i8* [[BP0:%[^,]+]], i8** [[BPADDR0]] // CHECK-DAG: store i8* [[P0:%[^,]+]], i8** [[PADDR0]] // CHECK-DAG: [[BP0]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK-DAG: [[P0]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[BP]], i32 0, i32 1 // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [2 x i8*], [2 x i8*]* [[P]], i32 0, i32 1 // CHECK-DAG: store i8* [[BP1:%[^,]+]], i8** [[BPADDR1]] // CHECK-DAG: store i8* [[P1:%[^,]+]], i8** [[PADDR1]] // CHECK-DAG: [[BP1]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK-DAG: [[P1]] = inttoptr i[[SZ]] %{{.+}} to i8* // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFELSE]] // CHECK: store i32 -1, i32* [[RHV]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFEND]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT3:@.+]]({{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] #pragma omp target teams if(target: n>10) { a += 1; aa += 1; } // We capture 3 VLA sizes in this target region // CHECK-64: [[A_VAL:%.+]] = load i32, i32* %{{.+}}, // CHECK-64: [[A_ADDR:%.+]] = bitcast i[[SZ]]* [[A_CADDR:%.+]] to i32* // CHECK-64: store i32 [[A_VAL]], i32* [[A_ADDR]], // CHECK-64: [[A_CVAL:%.+]] = load i[[SZ]], i[[SZ]]* [[A_CADDR]], // CHECK-32: [[A_VAL:%.+]] = load i32, i32* %{{.+}}, // CHECK-32: store i32 [[A_VAL]], i32* [[A_CADDR:%.+]], // CHECK-32: [[A_CVAL:%.+]] = load i[[SZ]], i[[SZ]]* [[A_CADDR]], // CHECK: [[BNSIZE:%.+]] = mul nuw i[[SZ]] [[VLA0:%.+]], 4 // CHECK: [[CNELEMSIZE2:%.+]] = mul nuw i[[SZ]] 5, [[VLA1:%.+]] // CHECK: [[CNSIZE:%.+]] = mul nuw i[[SZ]] [[CNELEMSIZE2]], 8 // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 20 // CHECK: br i1 [[IF]], label %[[TRY:[^,]+]], label %[[FAIL:[^,]+]] // CHECK: [[TRY]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 9, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* [[SR:%[^,]+]], i32* getelementptr inbounds ([9 x i32], [9 x i32]* [[MAPT4]], i32 0, i32 0), i32 0, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[SR]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S:%[^,]+]], i32 0, i32 0 // CHECK-DAG: [[SADDR0:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX0:[0-9]+]] // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX0]] // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX0]] // CHECK-DAG: [[SADDR1:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX1:[0-9]+]] // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX1]] // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX1]] // CHECK-DAG: [[SADDR2:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX2:[0-9]+]] // CHECK-DAG: [[BPADDR2:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX2]] // CHECK-DAG: [[PADDR2:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX2]] // CHECK-DAG: [[SADDR3:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX3:[0-9]+]] // CHECK-DAG: [[BPADDR3:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX3]] // CHECK-DAG: [[PADDR3:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX3]] // CHECK-DAG: [[SADDR4:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX4:[0-9]+]] // CHECK-DAG: [[BPADDR4:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX4]] // CHECK-DAG: [[PADDR4:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX4]] // CHECK-DAG: [[SADDR5:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX5:[0-9]+]] // CHECK-DAG: [[BPADDR5:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX5]] // CHECK-DAG: [[PADDR5:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX5]] // CHECK-DAG: [[SADDR6:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX6:[0-9]+]] // CHECK-DAG: [[BPADDR6:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX6]] // CHECK-DAG: [[PADDR6:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX6]] // CHECK-DAG: [[SADDR7:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX7:[0-9]+]] // CHECK-DAG: [[BPADDR7:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX7]] // CHECK-DAG: [[PADDR7:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX7]] // CHECK-DAG: [[SADDR8:%.+]] = getelementptr inbounds [9 x i[[SZ]]], [9 x i[[SZ]]]* [[S]], i32 0, i32 [[IDX8:[0-9]+]] // CHECK-DAG: [[BPADDR8:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[BP]], i32 0, i32 [[IDX8]] // CHECK-DAG: [[PADDR8:%.+]] = getelementptr inbounds [9 x i8*], [9 x i8*]* [[P]], i32 0, i32 [[IDX8]] // The names below are not necessarily consistent with the names used for the // addresses above as some are repeated. // CHECK-DAG: [[BP0:%[^,]+]] = inttoptr i[[SZ]] [[VLA0]] to i8* // CHECK-DAG: [[P0:%[^,]+]] = inttoptr i[[SZ]] [[VLA0]] to i8* // CHECK-DAG: store i8* [[BP0]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P0]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP1:%[^,]+]] = inttoptr i[[SZ]] [[VLA1]] to i8* // CHECK-DAG: [[P1:%[^,]+]] = inttoptr i[[SZ]] [[VLA1]] to i8* // CHECK-DAG: store i8* [[BP1]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P1]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: store i8* inttoptr (i[[SZ]] 5 to i8*), i8** {{%[^,]+}} // CHECK-DAG: store i8* inttoptr (i[[SZ]] 5 to i8*), i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP3:%[^,]+]] = inttoptr i[[SZ]] [[A_CVAL]] to i8* // CHECK-DAG: [[P3:%[^,]+]] = inttoptr i[[SZ]] [[A_CVAL]] to i8* // CHECK-DAG: store i8* [[BP3]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P3]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 4, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP4:%[^,]+]] = bitcast [10 x float]* %{{.+}} to i8* // CHECK-DAG: [[P4:%[^,]+]] = bitcast [10 x float]* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP4]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P4]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 40, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP5:%[^,]+]] = bitcast float* %{{.+}} to i8* // CHECK-DAG: [[P5:%[^,]+]] = bitcast float* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP5]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P5]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] [[BNSIZE]], i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP6:%[^,]+]] = bitcast [5 x [10 x double]]* %{{.+}} to i8* // CHECK-DAG: [[P6:%[^,]+]] = bitcast [5 x [10 x double]]* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP6]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P6]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 400, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP7:%[^,]+]] = bitcast double* %{{.+}} to i8* // CHECK-DAG: [[P7:%[^,]+]] = bitcast double* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP7]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P7]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] [[CNSIZE]], i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP8:%[^,]+]] = bitcast [[TT]]* %{{.+}} to i8* // CHECK-DAG: [[P8:%[^,]+]] = bitcast [[TT]]* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP8]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P8]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{12|16}}, i[[SZ]]* {{%[^,]+}} // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT4:@.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] #pragma omp target teams if(target: n>20) { a += 1; b[2] += 1.0; bn[3] += 1.0; c[1][2] += 1.0; cn[1][3] += 1.0; d.X += 1; d.Y += 1; } return a; } // Check that the offloading functions are emitted and that the arguments are // correct and loaded correctly for the target regions in foo(). // CHECK: define internal void [[HVT0]]() // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* [[OMP_OUTLINED:@.+]] to void (i32*, i32*, ...)*)) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED]](i32* noalias %.global_tid., i32* noalias %.bound_tid.) // CHECK: ret void // CHECK-NEXT: } // CHECK: define internal void [[HVT1]](i[[SZ]] %{{.+}}) // Create stack storage and store argument in there. // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_CASTED:%.+]] = alloca i[[SZ]], align // CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK-64: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i32* // CHECK-64: [[AA:%.+]] = load i32, i32* [[AA_CADDR]], align // CHECK-32: [[AA:%.+]] = load i32, i32* [[AA_ADDR]], align // CHECK-64: [[AA_C:%.+]] = bitcast i[[SZ]]* [[AA_CASTED]] to i32* // CHECK-64: store i32 [[AA]], i32* [[AA_C]], align // CHECK-32: store i32 [[AA]], i32* [[AA_CASTED]], align // CHECK: [[PARAM:%.+]] = load i[[SZ]], i[[SZ]]* [[AA_CASTED]], align // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]])* [[OMP_OUTLINED1:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[PARAM]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED1]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}) // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK-64: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i32* // CHECK-64: [[AA:%.+]] = load i32, i32* [[AA_CADDR]], align // CHECK-32: [[AA:%.+]] = load i32, i32* [[AA_ADDR]], align // CHECK: ret void // CHECK-NEXT: } // CHECK: define internal void [[HVT2]](i[[SZ]] %{{.+}}) // Create stack storage and store argument in there. // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_CASTED:%.+]] = alloca i[[SZ]], align // CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK: [[AA:%.+]] = load i16, i16* [[AA_CADDR]], align // CHECK: [[AA_C:%.+]] = bitcast i[[SZ]]* [[AA_CASTED]] to i16* // CHECK: store i16 [[AA]], i16* [[AA_C]], align // CHECK: [[PARAM:%.+]] = load i[[SZ]], i[[SZ]]* [[AA_CASTED]], align // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]])* [[OMP_OUTLINED2:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[PARAM]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED2]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}) // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK: [[AA:%.+]] = load i16, i16* [[AA_CADDR]], align // CHECK: ret void // CHECK-NEXT: } // CHECK: define internal void [[HVT3]] // Create stack storage and store argument in there. // CHECK: [[A_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[A_CASTED:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_CASTED:%.+]] = alloca i[[SZ]], align // CHECK-DAG: store i[[SZ]] %{{.+}}, i[[SZ]]* [[A_ADDR]], align // CHECK-DAG: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK-64-DAG:[[A_CADDR:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i32* // CHECK-DAG: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK-64-DAG:[[A:%.+]] = load i32, i32* [[A_CADDR]], align // CHECK-32-DAG:[[A:%.+]] = load i32, i32* [[A_ADDR]], align // CHECK-64-DAG:[[A_C:%.+]] = bitcast i[[SZ]]* [[A_CASTED]] to i32* // CHECK-64-DAG:store i32 [[A]], i32* [[A_C]], align // CHECK-32-DAG:store i32 [[A]], i32* [[A_CASTED]], align // CHECK-DAG: [[AA:%.+]] = load i16, i16* [[AA_CADDR]], align // CHECK-DAG: [[AA_C:%.+]] = bitcast i[[SZ]]* [[AA_CASTED]] to i16* // CHECK-DAG: store i16 [[AA]], i16* [[AA_C]], align // CHECK-DAG: [[PARAM1:%.+]] = load i[[SZ]], i[[SZ]]* [[A_CASTED]], align // CHECK-DAG: [[PARAM2:%.+]] = load i[[SZ]], i[[SZ]]* [[AA_CASTED]], align // CHECK-DAG: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 2, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]])* [[OMP_OUTLINED3:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[PARAM1]], i[[SZ]] [[PARAM2]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED3]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}) // CHECK: [[A_ADDR:%.+]] = alloca i[[SZ]], align // CHECK: [[AA_ADDR:%.+]] = alloca i[[SZ]], align // CHECK-DAG: store i[[SZ]] %{{.+}}, i[[SZ]]* [[A_ADDR]], align // CHECK-DAG: store i[[SZ]] %{{.+}}, i[[SZ]]* [[AA_ADDR]], align // CHECK-64-DAG:[[A_CADDR:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i32* // CHECK-DAG: [[AA_CADDR:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK: ret void // CHECK-NEXT: } // CHECK: define internal void [[HVT4]] // Create local storage for each capture. // CHECK: [[LOCAL_A:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_B:%.+]] = alloca [10 x float]* // CHECK: [[LOCAL_VLA1:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_BN:%.+]] = alloca float* // CHECK: [[LOCAL_C:%.+]] = alloca [5 x [10 x double]]* // CHECK: [[LOCAL_VLA2:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_VLA3:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_CN:%.+]] = alloca double* // CHECK: [[LOCAL_D:%.+]] = alloca [[TT]]* // CHECK: [[LOCAL_A_CASTED:%.+]] = alloca i[[SZ]] // CHECK-DAG: store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]] // CHECK-DAG: store [10 x float]* [[ARG_B:%.+]], [10 x float]** [[LOCAL_B]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA1:%.+]], i[[SZ]]* [[LOCAL_VLA1]] // CHECK-DAG: store float* [[ARG_BN:%.+]], float** [[LOCAL_BN]] // CHECK-DAG: store [5 x [10 x double]]* [[ARG_C:%.+]], [5 x [10 x double]]** [[LOCAL_C]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA2:%.+]], i[[SZ]]* [[LOCAL_VLA2]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA3:%.+]], i[[SZ]]* [[LOCAL_VLA3]] // CHECK-DAG: store double* [[ARG_CN:%.+]], double** [[LOCAL_CN]] // CHECK-DAG: store [[TT]]* [[ARG_D:%.+]], [[TT]]** [[LOCAL_D]] // CHECK-64-DAG:[[CONV_AP:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32* // CHECK-DAG: [[REF_B:%.+]] = load [10 x float]*, [10 x float]** [[LOCAL_B]], // CHECK-DAG: [[VAL_VLA1:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA1]], // CHECK-DAG: [[REF_BN:%.+]] = load float*, float** [[LOCAL_BN]], // CHECK-DAG: [[REF_C:%.+]] = load [5 x [10 x double]]*, [5 x [10 x double]]** [[LOCAL_C]], // CHECK-DAG: [[VAL_VLA2:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA2]], // CHECK-DAG: [[VAL_VLA3:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA3]], // CHECK-DAG: [[REF_CN:%.+]] = load double*, double** [[LOCAL_CN]], // CHECK-DAG: [[REF_D:%.+]] = load [[TT]]*, [[TT]]** [[LOCAL_D]], // CHECK-64-DAG:[[CONV_A:%.+]] = load i32, i32* [[CONV_AP]] // CHECK-64-DAG:[[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_A_CASTED]] to i32* // CHECK-64-DAG:store i32 [[CONV_A]], i32* [[CONV]], align // CHECK-32-DAG:[[LOCAL_AV:%.+]] = load i32, i32* [[LOCAL_A]] // CHECK-32-DAG:store i32 [[LOCAL_AV]], i32* [[LOCAL_A_CASTED]], align // CHECK-DAG: [[REF_A:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_A_CASTED]], // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 9, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], [10 x float]*, i[[SZ]], float*, [5 x [10 x double]]*, i[[SZ]], i[[SZ]], double*, [[TT]]*)* [[OMP_OUTLINED4:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[REF_A]], [10 x float]* [[REF_B]], i[[SZ]] [[VAL_VLA1]], float* [[REF_BN]], [5 x [10 x double]]* [[REF_C]], i[[SZ]] [[VAL_VLA2]], i[[SZ]] [[VAL_VLA3]], double* [[REF_CN]], [[TT]]* [[REF_D]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED4]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, [10 x float]* {{.+}}, i[[SZ]] %{{.+}}, float* %{{.+}}, [5 x [10 x double]]* {{.+}}, i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, double* %{{.+}}, [[TT]]* {{.+}}) // To reduce complexity, we're only going as far as validating the signature of the outlined parallel function. template<typename tx> tx ftemplate(int n) { tx a = 0; short aa = 0; tx b[10]; #pragma omp target teams if(target: n>40) { a += 1; aa += 1; b[2] += 1; } return a; } static int fstatic(int n) { int a = 0; short aa = 0; char aaa = 0; int b[10]; #pragma omp target teams if(target: n>50) { a += 1; aa += 1; aaa += 1; b[2] += 1; } return a; } struct S1 { double a; int r1(int n){ int b = n+1; short int c[2][n]; #pragma omp target teams if(target: n>60) { this->a = (double)b + 1.5; c[1][1] = ++a; } return c[1][1] + (int)b; } }; // CHECK: define {{.*}}@{{.*}}bar{{.*}} int bar(int n){ int a = 0; // CHECK: call {{.*}}i32 [[FOO]](i32 {{.*}}) a += foo(n); S1 S; // CHECK: call {{.*}}i32 [[FS1:@.+]]([[S1]]* {{.*}}, i32 {{.*}}) a += S.r1(n); // CHECK: call {{.*}}i32 [[FSTATIC:@.+]](i32 {{.*}}) a += fstatic(n); // CHECK: call {{.*}}i32 [[FTEMPLATE:@.+]](i32 {{.*}}) a += ftemplate<int>(n); return a; } // // CHECK: define {{.*}}[[FS1]] // // CHECK: i8* @llvm.stacksave() // CHECK-64: [[B_ADDR:%.+]] = bitcast i[[SZ]]* [[B_CADDR:%.+]] to i32* // CHECK-64: store i32 %{{.+}}, i32* [[B_ADDR]], // CHECK-64: [[B_CVAL:%.+]] = load i[[SZ]], i[[SZ]]* [[B_CADDR]], // CHECK-32: store i32 %{{.+}}, i32* [[B_ADDR:%.+]], // CHECK-32: [[B_CVAL:%.+]] = load i[[SZ]], i[[SZ]]* [[B_ADDR]], // We capture 2 VLA sizes in this target region // CHECK: [[CELEMSIZE2:%.+]] = mul nuw i[[SZ]] 2, [[VLA0:%.+]] // CHECK: [[CSIZE:%.+]] = mul nuw i[[SZ]] [[CELEMSIZE2]], 2 // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 60 // CHECK: br i1 [[IF]], label %[[TRY:[^,]+]], label %[[FAIL:[^,]+]] // CHECK: [[TRY]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 5, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* [[SR:%[^,]+]], i32* getelementptr inbounds ([5 x i32], [5 x i32]* [[MAPT7]], i32 0, i32 0), i32 0, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP:%.+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P:%.+]], i32 0, i32 0 // CHECK-DAG: [[SR]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S:%.+]], i32 0, i32 0 // CHECK-DAG: [[SADDR0:%.+]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S]], i32 [[IDX0:[0-9]+]] // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP]], i32 [[IDX0]] // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P]], i32 [[IDX0]] // CHECK-DAG: [[SADDR1:%.+]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S]], i32 [[IDX1:[0-9]+]] // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP]], i32 [[IDX1]] // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P]], i32 [[IDX1]] // CHECK-DAG: [[SADDR2:%.+]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S]], i32 [[IDX2:[0-9]+]] // CHECK-DAG: [[BPADDR2:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP]], i32 [[IDX2]] // CHECK-DAG: [[PADDR2:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P]], i32 [[IDX2]] // CHECK-DAG: [[SADDR3:%.+]] = getelementptr inbounds [5 x i[[SZ]]], [5 x i[[SZ]]]* [[S]], i32 [[IDX3:[0-9]+]] // CHECK-DAG: [[BPADDR3:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[BP]], i32 [[IDX3]] // CHECK-DAG: [[PADDR3:%.+]] = getelementptr inbounds [5 x i8*], [5 x i8*]* [[P]], i32 [[IDX3]] // The names below are not necessarily consistent with the names used for the // addresses above as some are repeated. // CHECK-DAG: [[BP0:%[^,]+]] = inttoptr i[[SZ]] [[VLA0]] to i8* // CHECK-DAG: [[P0:%[^,]+]] = inttoptr i[[SZ]] [[VLA0]] to i8* // CHECK-DAG: store i8* [[BP0]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P0]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: store i8* inttoptr (i[[SZ]] 2 to i8*), i8** {{%[^,]+}} // CHECK-DAG: store i8* inttoptr (i[[SZ]] 2 to i8*), i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] {{4|8}}, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP2:%[^,]+]] = inttoptr i[[SZ]] [[B_CVAL]] to i8* // CHECK-DAG: [[P2:%[^,]+]] = inttoptr i[[SZ]] [[B_CVAL]] to i8* // CHECK-DAG: store i8* [[BP2]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P2]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 4, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP3:%[^,]+]] = bitcast [[S1]]* %{{.+}} to i8* // CHECK-DAG: [[P3:%[^,]+]] = bitcast [[S1]]* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP3]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P3]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] 8, i[[SZ]]* {{%[^,]+}} // CHECK-DAG: [[BP4:%[^,]+]] = bitcast i16* %{{.+}} to i8* // CHECK-DAG: [[P4:%[^,]+]] = bitcast i16* %{{.+}} to i8* // CHECK-DAG: store i8* [[BP4]], i8** {{%[^,]+}} // CHECK-DAG: store i8* [[P4]], i8** {{%[^,]+}} // CHECK-DAG: store i[[SZ]] [[CSIZE]], i[[SZ]]* {{%[^,]+}} // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:[^,]+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT7:@.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] // // CHECK: define {{.*}}[[FSTATIC]] // // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 50 // CHECK: br i1 [[IF]], label %[[IFTHEN:[^,]+]], label %[[IFELSE:[^,]+]] // CHECK: [[IFTHEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 4, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* getelementptr inbounds ([4 x i[[SZ]]], [4 x i[[SZ]]]* [[SIZET6]], i32 0, i32 0), i32* getelementptr inbounds ([4 x i32], [4 x i32]* [[MAPT6]], i32 0, i32 0), i32 0, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP:%.+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P:%.+]], i32 0, i32 0 // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP]], i32 0, i32 0 // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P]], i32 0, i32 0 // CHECK-DAG: store i8* [[BP0:%[^,]+]], i8** [[BPADDR0]] // CHECK-DAG: store i8* [[P0:%[^,]+]], i8** [[PADDR0]] // CHECK-DAG: [[BP0]] = inttoptr i[[SZ]] [[VAL0:%.+]] to i8* // CHECK-DAG: [[P0]] = inttoptr i[[SZ]] [[VAL0]] to i8* // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP]], i32 0, i32 1 // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P]], i32 0, i32 1 // CHECK-DAG: store i8* [[BP1:%[^,]+]], i8** [[BPADDR1]] // CHECK-DAG: store i8* [[P1:%[^,]+]], i8** [[PADDR1]] // CHECK-DAG: [[BP1]] = inttoptr i[[SZ]] [[VAL1:%.+]] to i8* // CHECK-DAG: [[P1]] = inttoptr i[[SZ]] [[VAL1]] to i8* // CHECK-DAG: [[BPADDR2:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP]], i32 0, i32 2 // CHECK-DAG: [[PADDR2:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P]], i32 0, i32 2 // CHECK-DAG: store i8* [[BP2:%[^,]+]], i8** [[BPADDR2]] // CHECK-DAG: store i8* [[P2:%[^,]+]], i8** [[PADDR2]] // CHECK-DAG: [[BPADDR3:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[BP]], i32 0, i32 3 // CHECK-DAG: [[PADDR3:%.+]] = getelementptr inbounds [4 x i8*], [4 x i8*]* [[P]], i32 0, i32 3 // CHECK-DAG: store i8* [[BP3:%[^,]+]], i8** [[BPADDR3]] // CHECK-DAG: store i8* [[P3:%[^,]+]], i8** [[PADDR3]] // CHECK-DAG: [[BP3]] = bitcast [10 x i32]* %{{.+}} to i8* // CHECK-DAG: [[P3]] = bitcast [10 x i32]* %{{.+}} to i8* // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFELSE]] // CHECK: store i32 -1, i32* [[RHV]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFEND]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT6:@.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] // // CHECK: define {{.*}}[[FTEMPLATE]] // // CHECK: [[IF:%.+]] = icmp sgt i32 {{[^,]+}}, 40 // CHECK: br i1 [[IF]], label %[[IFTHEN:[^,]+]], label %[[IFELSE:[^,]+]] // CHECK: [[IFTHEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 3, i8** [[BPR:%[^,]+]], i8** [[PR:%[^,]+]], i[[SZ]]* getelementptr inbounds ([3 x i[[SZ]]], [3 x i[[SZ]]]* [[SIZET5]], i32 0, i32 0), i32* getelementptr inbounds ([3 x i32], [3 x i32]* [[MAPT5]], i32 0, i32 0), i32 0, i32 0) // CHECK-DAG: [[BPR]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[BP:%.+]], i32 0, i32 0 // CHECK-DAG: [[PR]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[P:%.+]], i32 0, i32 0 // CHECK-DAG: [[BPADDR0:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[BP]], i32 0, i32 0 // CHECK-DAG: [[PADDR0:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[P]], i32 0, i32 0 // CHECK-DAG: store i8* [[BP0:%[^,]+]], i8** [[BPADDR0]] // CHECK-DAG: store i8* [[P0:%[^,]+]], i8** [[PADDR0]] // CHECK-DAG: [[BP0]] = inttoptr i[[SZ]] [[VAL0:%.+]] to i8* // CHECK-DAG: [[P0]] = inttoptr i[[SZ]] [[VAL0]] to i8* // CHECK-DAG: [[BPADDR1:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[BP]], i32 0, i32 1 // CHECK-DAG: [[PADDR1:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[P]], i32 0, i32 1 // CHECK-DAG: store i8* [[BP1:%[^,]+]], i8** [[BPADDR1]] // CHECK-DAG: store i8* [[P1:%[^,]+]], i8** [[PADDR1]] // CHECK-DAG: [[BP1]] = inttoptr i[[SZ]] [[VAL1:%.+]] to i8* // CHECK-DAG: [[P1]] = inttoptr i[[SZ]] [[VAL1]] to i8* // CHECK-DAG: [[BPADDR2:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[BP]], i32 0, i32 2 // CHECK-DAG: [[PADDR2:%.+]] = getelementptr inbounds [3 x i8*], [3 x i8*]* [[P]], i32 0, i32 2 // CHECK-DAG: store i8* [[BP2:%[^,]+]], i8** [[BPADDR2]] // CHECK-DAG: store i8* [[P2:%[^,]+]], i8** [[PADDR2]] // CHECK-DAG: [[BP2]] = bitcast [10 x i32]* %{{.+}} to i8* // CHECK-DAG: [[P2]] = bitcast [10 x i32]* %{{.+}} to i8* // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFELSE]] // CHECK: store i32 -1, i32* [[RHV]], align 4 // CHECK-NEXT: br label %[[IFEND:.+]] // CHECK: [[IFEND]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align 4 // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // CHECK: [[FAIL]] // CHECK: call void [[HVT5:@.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}) // CHECK-NEXT: br label %[[END]] // CHECK: [[END]] // Check that the offloading functions are emitted and that the arguments are // correct and loaded correctly for the target regions of the callees of bar(). // CHECK: define internal void [[HVT7]] // Create local storage for each capture. // CHECK: [[LOCAL_THIS:%.+]] = alloca [[S1]]* // CHECK: [[LOCAL_B:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_VLA1:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_VLA2:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_C:%.+]] = alloca i16* // CHECK: [[LOCAL_B_CASTED:%.+]] = alloca i[[SZ]] // CHECK-DAG: store [[S1]]* [[ARG_THIS:%.+]], [[S1]]** [[LOCAL_THIS]] // CHECK-DAG: store i[[SZ]] [[ARG_B:%.+]], i[[SZ]]* [[LOCAL_B]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA1:%.+]], i[[SZ]]* [[LOCAL_VLA1]] // CHECK-DAG: store i[[SZ]] [[ARG_VLA2:%.+]], i[[SZ]]* [[LOCAL_VLA2]] // CHECK-DAG: store i16* [[ARG_C:%.+]], i16** [[LOCAL_C]] // Store captures in the context. // CHECK-DAG: [[REF_THIS:%.+]] = load [[S1]]*, [[S1]]** [[LOCAL_THIS]], // CHECK-64-DAG:[[CONV_BP:%.+]] = bitcast i[[SZ]]* [[LOCAL_B]] to i32* // CHECK-DAG: [[VAL_VLA1:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA1]], // CHECK-DAG: [[VAL_VLA2:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_VLA2]], // CHECK-DAG: [[REF_C:%.+]] = load i16*, i16** [[LOCAL_C]], // CHECK-64-DAG:[[CONV_B:%.+]] = load i32, i32* [[CONV_BP]] // CHECK-64-DAG:[[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_B_CASTED]] to i32* // CHECK-64-DAG:store i32 [[CONV_B]], i32* [[CONV]], align // CHECK-32-DAG:[[LOCAL_BV:%.+]] = load i32, i32* [[LOCAL_B]] // CHECK-32-DAG:store i32 [[LOCAL_BV]], i32* [[LOCAL_B_CASTED]], align // CHECK-DAG: [[REF_B:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_B_CASTED]], // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 5, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, [[S1]]*, i[[SZ]], i[[SZ]], i[[SZ]], i16*)* [[OMP_OUTLINED5:@.+]] to void (i32*, i32*, ...)*), [[S1]]* [[REF_THIS]], i[[SZ]] [[REF_B]], i[[SZ]] [[VAL_VLA1]], i[[SZ]] [[VAL_VLA2]], i16* [[REF_C]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED5]](i32* noalias %.global_tid., i32* noalias %.bound_tid., [[S1]]* %{{.+}}, i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, i16* %{{.+}}) // To reduce complexity, we're only going as far as validating the signature of the outlined parallel function. // CHECK: define internal void [[HVT6]] // Create local storage for each capture. // CHECK: [[LOCAL_A:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AA:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AAA:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_B:%.+]] = alloca [10 x i32]* // CHECK: [[LOCAL_A_CASTED:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AA_CASTED:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AAA_CASTED:%.+]] = alloca i[[SZ]] // CHECK-DAG: store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]] // CHECK-DAG: store i[[SZ]] [[ARG_AA:%.+]], i[[SZ]]* [[LOCAL_AA]] // CHECK-DAG: store i[[SZ]] [[ARG_AAA:%.+]], i[[SZ]]* [[LOCAL_AAA]] // CHECK-DAG: store [10 x i32]* [[ARG_B:%.+]], [10 x i32]** [[LOCAL_B]] // Store captures in the context. // CHECK-64-DAG:[[CONV_AP:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32* // CHECK-DAG: [[CONV_AAP:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA]] to i16* // CHECK-DAG: [[CONV_AAAP:%.+]] = bitcast i[[SZ]]* [[LOCAL_AAA]] to i8* // CHECK-DAG: [[REF_B:%.+]] = load [10 x i32]*, [10 x i32]** [[LOCAL_B]], // CHECK-64-DAG:[[CONV_A:%.+]] = load i32, i32* [[CONV_AP]] // CHECK-64-DAG:[[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_A_CASTED]] to i32* // CHECK-64-DAG:store i32 [[CONV_A]], i32* [[CONV]], align // CHECK-32-DAG:[[LOCAL_AV:%.+]] = load i32, i32* [[LOCAL_A]] // CHECK-32-DAG:store i32 [[LOCAL_AV]], i32* [[LOCAL_A_CASTED]], align // CHECK-DAG: [[REF_A:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_A_CASTED]], // CHECK-DAG: [[CONV_AA:%.+]] = load i16, i16* [[CONV_AAP]] // CHECK-DAG: [[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA_CASTED]] to i16* // CHECK-DAG: store i16 [[CONV_AA]], i16* [[CONV]], align // CHECK-DAG: [[REF_AA:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_AA_CASTED]], // CHECK-DAG: [[CONV_AAA:%.+]] = load i8, i8* [[CONV_AAAP]] // CHECK-DAG: [[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_AAA_CASTED]] to i8* // CHECK-DAG: store i8 [[CONV_AAA]], i8* [[CONV]], align // CHECK-DAG: [[REF_AAA:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_AAA_CASTED]], // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 4, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]], i[[SZ]], [10 x i32]*)* [[OMP_OUTLINED6:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[REF_A]], i[[SZ]] [[REF_AA]], i[[SZ]] [[REF_AAA]], [10 x i32]* [[REF_B]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED6]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, [10 x i32]* {{.+}}) // To reduce complexity, we're only going as far as validating the signature of the outlined parallel function. // CHECK: define internal void [[HVT5]] // Create local storage for each capture. // CHECK: [[LOCAL_A:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AA:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_B:%.+]] = alloca [10 x i32]* // CHECK: [[LOCAL_A_CASTED:%.+]] = alloca i[[SZ]] // CHECK: [[LOCAL_AA_CASTED:%.+]] = alloca i[[SZ]] // CHECK-DAG: store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]] // CHECK-DAG: store i[[SZ]] [[ARG_AA:%.+]], i[[SZ]]* [[LOCAL_AA]] // CHECK-DAG: store [10 x i32]* [[ARG_B:%.+]], [10 x i32]** [[LOCAL_B]] // Store captures in the context. // CHECK-64-DAG:[[CONV_AP:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32* // CHECK-DAG: [[CONV_AAP:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA]] to i16* // CHECK-DAG: [[REF_B:%.+]] = load [10 x i32]*, [10 x i32]** [[LOCAL_B]], // CHECK-64-DAG:[[CONV_A:%.+]] = load i32, i32* [[CONV_AP]] // CHECK-64-DAG:[[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_A_CASTED]] to i32* // CHECK-64-DAG:store i32 [[CONV_A]], i32* [[CONV]], align // CHECK-32-DAG:[[LOCAL_AV:%.+]] = load i32, i32* [[LOCAL_A]] // CHECK-32-DAG:store i32 [[LOCAL_AV]], i32* [[LOCAL_A_CASTED]], align // CHECK-DAG: [[REF_A:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_A_CASTED]], // CHECK-DAG: [[CONV_AA:%.+]] = load i16, i16* [[CONV_AAP]] // CHECK-DAG: [[CONV:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA_CASTED]] to i16* // CHECK-DAG: store i16 [[CONV_AA]], i16* [[CONV]], align // CHECK-DAG: [[REF_AA:%.+]] = load i[[SZ]], i[[SZ]]* [[LOCAL_AA_CASTED]], // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 3, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]], [10 x i32]*)* [[OMP_OUTLINED7:@.+]] to void (i32*, i32*, ...)*), i[[SZ]] [[REF_A]], i[[SZ]] [[REF_AA]], [10 x i32]* [[REF_B]]) // // // CHECK: define internal {{.*}}void [[OMP_OUTLINED7]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i[[SZ]] %{{.+}}, i[[SZ]] %{{.+}}, [10 x i32]* {{.+}}) // To reduce complexity, we're only going as far as validating the signature of the outlined parallel function. #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_parallel_for_simd_map_messages.cpp
281
// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 100 %s void foo() { } bool foobool(int argc) { return argc; } struct S1; // expected-note 2 {{declared here}} extern S1 a; class S2 { mutable int a; public: S2():a(0) { } S2(S2 &s2):a(s2.a) { } static float S2s; // expected-note 4 {{mappable type cannot contain static members}} static const float S2sc; // expected-note 4 {{mappable type cannot contain static members}} }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3():a(0) { } S3(S3 &s3):a(s3.a) { } }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} S5(const S5 &s5):a(s5.a) { } public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}} typedef int from; template <typename T, int I> // expected-note {{declared here}} T tmain(T argc) { const T d = 5; const T da[5] = { 0 }; S4 e(4); S5 g(5); T i, t[20]; T &j = i; T *k = &j; T x; T y; T to, tofrom, always; const T (&l)[5] = da; #pragma omp target teams distribute parallel for simd map // expected-error {{expected '(' after 'map'}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected expression}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map() // expected-error {{expected expression}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(alloc) // expected-error {{use of undeclared identifier 'alloc'}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to argc // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected ',' or ')' in 'map' clause}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to:) // expected-error {{expected expression}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(from: argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(x: y) // expected-error {{incorrect map type, expected one of 'to', 'from', 'tofrom', 'alloc', 'release', or 'delete'}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(l[-1:]) // expected-error 2 {{array section must be a subset of the original array}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(l[:-1]) // expected-error 2 {{section length is evaluated to a negative value -1}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(tofrom: t[:I]) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(T: a) // expected-error {{incorrect map type, expected one of 'to', 'from', 'tofrom', 'alloc', 'release', or 'delete'}} expected-error {{incomplete type 'S1' where a complete type is required}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(T) // expected-error {{'T' does not refer to a value}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(I) // expected-error 2 {{expected expression containing only member accesses and/or array sections based on named variables}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(S2::S2s) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(S2::S2sc) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to: x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to: to) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to, x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to x) // expected-error {{expected ',' or ')' in 'map' clause}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(tofrom: argc > 0 ? x : y) // expected-error 2 {{expected expression containing only member accesses and/or array sections based on named variables}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(argc) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(S1) // expected-error {{'S1' does not refer to a value}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(a, b, c, d, f) // expected-error {{incomplete type 'S1' where a complete type is required}} expected-error 2 {{type 'S2' is not mappable to target}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(ba) // expected-error 2 {{type 'S2' is not mappable to target}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(ca) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(da) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(S2::S2s) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(S2::S2sc) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(e, g) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(h) // expected-error {{threadprivate variables are not allowed in 'map' clause}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(k), map(k) // expected-error 2 {{variable already marked as mapped in current construct}} expected-note 2 {{used here}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(k), map(k[:5]) // expected-error 2 {{pointer cannot be mapped along with a section derived from itself}} expected-note 2 {{used here}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(da) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(da[:4]) for (i = 0; i < argc; ++i) foo(); #pragma omp target data map(k, j, l) // expected-note 2 {{used here}} #pragma omp target teams distribute parallel for simd map(k[:4]) // expected-error 2 {{pointer cannot be mapped along with a section derived from itself}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(j) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(l) map(l[:5]) // expected-error 2 {{variable already marked as mapped in current construct}} expected-note 2 {{used here}} for (i = 0; i < argc; ++i) foo(); #pragma omp target data map(k[:4], j, l[:5]) // expected-note 2 {{used here}} { #pragma omp target teams distribute parallel for simd map(k) // expected-error 2 {{pointer cannot be mapped along with a section derived from itself}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(j) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(l) for (i = 0; i < argc; ++i) foo(); } #pragma omp target teams distribute parallel for simd map(always, tofrom: x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(always: x) // expected-error {{missing map type}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(tofrom, always: x) // expected-error {{incorrect map type modifier, expected 'always'}} expected-error {{incorrect map type, expected one of 'to', 'from', 'tofrom', 'alloc', 'release', or 'delete'}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(always, tofrom: always, tofrom, x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(tofrom j) // expected-error {{expected ',' or ')' in 'map' clause}} for (i = 0; i < argc; ++i) foo(); return 0; } int main(int argc, char **argv) { const int d = 5; const int da[5] = { 0 }; S4 e(4); S5 g(5); int i; int &j = i; int *k = &j; int x; int y; int to, tofrom, always; const int (&l)[5] = da; #pragma omp target teams distribute parallel for simd map // expected-error {{expected '(' after 'map'}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected expression}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map() // expected-error {{expected expression}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(alloc) // expected-error {{use of undeclared identifier 'alloc'}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to argc // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected ',' or ')' in 'map' clause}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to:) // expected-error {{expected expression}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(from: argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(x: y) // expected-error {{incorrect map type, expected one of 'to', 'from', 'tofrom', 'alloc', 'release', or 'delete'}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(l[-1:]) // expected-error {{array section must be a subset of the original array}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(l[:-1]) // expected-error {{section length is evaluated to a negative value -1}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to: x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to: to) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to, x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(to x) // expected-error {{expected ',' or ')' in 'map' clause}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(tofrom: argc > 0 ? argv[1] : argv[2]) // expected-error {{expected expression containing only member accesses and/or array sections based on named variables}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(argc) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(S1) // expected-error {{'S1' does not refer to a value}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(a, b, c, d, f) // expected-error {{incomplete type 'S1' where a complete type is required}} expected-error 2 {{type 'S2' is not mappable to target}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(argv[1]) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(ba) // expected-error 2 {{type 'S2' is not mappable to target}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(ca) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(da) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(S2::S2s) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(S2::S2sc) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(e, g) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(h) // expected-error {{threadprivate variables are not allowed in 'map' clause}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(k), map(k) // expected-error {{variable already marked as mapped in current construct}} expected-note {{used here}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(k), map(k[:5]) // expected-error {{pointer cannot be mapped along with a section derived from itself}} expected-note {{used here}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(da) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(da[:4]) for (i = 0; i < argc; ++i) foo(); #pragma omp target data map(k, j, l) // expected-note {{used here}} #pragma omp target teams distribute parallel for simd map(k[:4]) // expected-error {{pointer cannot be mapped along with a section derived from itself}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(j) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(l) map(l[:5]) // expected-error 1 {{variable already marked as mapped in current construct}} expected-note 1 {{used here}} for (i = 0; i < argc; ++i) foo(); #pragma omp target data map(k[:4], j, l[:5]) // expected-note {{used here}} { #pragma omp target teams distribute parallel for simd map(k) // expected-error {{pointer cannot be mapped along with a section derived from itself}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(j) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(l) for (i = 0; i < argc; ++i) foo(); } #pragma omp target teams distribute parallel for simd map(always, tofrom: x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(always: x) // expected-error {{missing map type}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(tofrom, always: x) // expected-error {{incorrect map type modifier, expected 'always'}} expected-error {{incorrect map type, expected one of 'to', 'from', 'tofrom', 'alloc', 'release', or 'delete'}} for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(always, tofrom: always, tofrom, x) for (i = 0; i < argc; ++i) foo(); #pragma omp target teams distribute parallel for simd map(tofrom j) // expected-error {{expected ',' or ')' in 'map' clause}} for (i = 0; i < argc; ++i) foo(); return tmain<int, 3>(argc)+tmain<from, 4>(argc); // expected-note {{in instantiation of function template specialization 'tmain<int, 3>' requested here}} expected-note {{in instantiation of function template specialization 'tmain<int, 4>' requested here}} }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_simd_is_device_ptr_messages.cpp
337
// RUN: %clang_cc1 -std=c++11 -verify -fopenmp %s struct ST { int *a; }; typedef int arr[10]; typedef ST STarr[10]; struct SA { const int d = 5; const int da[5] = { 0 }; ST e; ST g[10]; STarr &rg = g; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; arr &raa = aa; void func(int arg) { #pragma omp target teams distribute simd is_device_ptr // expected-error {{expected '(' after 'is_device_ptr'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected expression}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr() // expected-error {{expected expression}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(alloc) // expected-error {{use of undeclared identifier 'alloc'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(arg // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(i) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(j) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(k) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(z) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(aa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(raa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(e) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(g) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(rg) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(k,i,j) // expected-error2 {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(d) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(da) // OK for (int i=0; i<100; i++) ; return; } }; struct SB { unsigned A; unsigned B; float Arr[100]; float *Ptr; float *foo() { return &Arr[0]; } }; struct SC { unsigned A : 2; unsigned B : 3; unsigned C; unsigned D; float Arr[100]; SB S; SB ArrS[100]; SB *PtrS; SB *&RPtrS; float *Ptr; SC(SB *&_RPtrS) : RPtrS(_RPtrS) {} }; union SD { unsigned A; float B; }; struct S1; extern S1 a; class S2 { mutable int a; public: S2():a(0) { } S2(S2 &s2):a(s2.a) { } static float S2s; static const float S2sc; }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3():a(0) { } S3(S3 &s3):a(s3.a) { } }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} S5(const S5 &s5):a(s5.a) { } public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) typedef struct { int a; } S6; template <typename T, int I> T tmain(T argc) { const T d = 5; const T da[5] = { 0 }; S4 e(4); S5 g(5); S6 h[10]; auto &rh = h; T i; T &j = i; T *k = &j; T *&z = k; T aa[10]; auto &raa = aa; S6 *ps; #pragma omp target teams distribute simd is_device_ptr // expected-error {{expected '(' after 'is_device_ptr'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected expression}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr() // expected-error {{expected expression}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(alloc) // expected-error {{use of undeclared identifier 'alloc'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(i) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(j) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(k) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(z) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(aa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(raa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(e) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(g) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(h) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(rh) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(k,i,j) // expected-error2 {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(d) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(da) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd map(ps) is_device_ptr(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(ps) map(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd map(ps->a) is_device_ptr(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(ps) map(ps->a) // expected-error{{pointer cannot be mapped along with a section derived from itself}} expected-note{{used here}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(ps) firstprivate(ps) // expected-error{{firstprivate variable cannot be in a is_device_ptr clause in '#pragma omp target teams distribute simd' directive}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd firstprivate(ps) is_device_ptr(ps) // expected-error{{firstprivate variable cannot be in a is_device_ptr clause in '#pragma omp target teams distribute simd' directive}} expected-note{{defined as firstprivate}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(ps) private(ps) // expected-error{{private variable cannot be in a is_device_ptr clause in '#pragma omp target teams distribute simd' directive}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd private(ps) is_device_ptr(ps) // expected-error{{private variable cannot be in a is_device_ptr clause in '#pragma omp target teams distribute simd' directive}} expected-note{{defined as private}} for (int i=0; i<100; i++) ; return 0; } int main(int argc, char **argv) { const int d = 5; const int da[5] = { 0 }; S4 e(4); S5 g(5); S6 h[10]; auto &rh = h; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; auto &raa = aa; S6 *ps; #pragma omp target teams distribute simd is_device_ptr // expected-error {{expected '(' after 'is_device_ptr'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr( // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected expression}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr() // expected-error {{expected expression}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(alloc) // expected-error {{use of undeclared identifier 'alloc'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(i) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(j) // expected-error {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(k) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(z) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(aa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(raa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(e) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(g) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(h) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(rh) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(k,i,j) // expected-error2 {{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(d) // expected-error{{expected pointer, array, reference to pointer, or reference to array in 'is_device_ptr clause'}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(da) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd map(ps) is_device_ptr(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(ps) map(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd map(ps->a) is_device_ptr(ps) // expected-error{{variable already marked as mapped in current construct}} expected-note{{used here}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(ps) map(ps->a) // expected-error{{pointer cannot be mapped along with a section derived from itself}} expected-note{{used here}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(ps) firstprivate(ps) // expected-error{{firstprivate variable cannot be in a is_device_ptr clause in '#pragma omp target teams distribute simd' directive}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd firstprivate(ps) is_device_ptr(ps) // expected-error{{firstprivate variable cannot be in a is_device_ptr clause in '#pragma omp target teams distribute simd' directive}} expected-note{{defined as firstprivate}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(ps) private(ps) // expected-error{{private variable cannot be in a is_device_ptr clause in '#pragma omp target teams distribute simd' directive}} for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd private(ps) is_device_ptr(ps) // expected-error{{private variable cannot be in a is_device_ptr clause in '#pragma omp target teams distribute simd' directive}} expected-note{{defined as private}} for (int i=0; i<100; i++) ; return tmain<int, 3>(argc); // expected-note {{in instantiation of function template specialization 'tmain<int, 3>' requested here}} }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_simd_loop_messages.cpp
627
// RUN: %clang_cc1 -fsyntax-only -fopenmp -x c++ -std=c++11 -fexceptions -fcxx-exceptions -verify %s class S { int a; S() : a(0) {} public: S(int v) : a(v) {} S(const S &s) : a(s.a) {} }; static int sii; // expected-note@+1 {{defined as threadprivate or thread local}} #pragma omp threadprivate(sii) static int globalii; int test_iteration_spaces() { const int N = 100; float a[N], b[N], c[N]; int ii, jj, kk; float fii; double dii; #pragma omp target teams distribute simd for (int i = 0; i < 10; i += 1) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute simd for (char i = 0; i < 10; i++) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute simd for (char i = 0; i < 10; i += '\1') { c[i] = a[i] + b[i]; } #pragma omp target teams distribute simd for (long long i = 0; i < 10; i++) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute simd // expected-error@+1 {{expression must have integral or unscoped enumeration type, not 'double'}} for (long long i = 0; i < 10; i += 1.5) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute simd for (long long i = 0; i < 'z'; i += 1u) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute simd // expected-error@+1 {{variable must be of integer or random access iterator type}} for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } #pragma omp target teams distribute simd // expected-error@+1 {{variable must be of integer or random access iterator type}} for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } #pragma omp target teams distribute simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (int &ref = ii; ref < 10; ref++) { } #pragma omp target teams distribute simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (int i; i < 10; i++) c[i] = a[i]; #pragma omp target teams distribute simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (int i = 0, j = 0; i < 10; ++i) c[i] = a[i]; #pragma omp target teams distribute simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-warning@+2 {{expression result unused}} // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (ii + 1; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (c[ii] = 0; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute simd // Ok to skip parenthesises. for (((ii)) = 0; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} for (int i = 0; i; i++) c[i] = a[i]; #pragma omp target teams distribute simd // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'i'}} for (int i = 0; jj < kk; ii++) c[i] = a[i]; #pragma omp target teams distribute simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} for (int i = 0; !!i; i++) c[i] = a[i]; #pragma omp target teams distribute simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} for (int i = 0; i != 1; i++) c[i] = a[i]; #pragma omp target teams distribute simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} for (int i = 0;; i++) c[i] = a[i]; // Ok. #pragma omp target teams distribute simd for (int i = 11; i > 10; i--) c[i] = a[i]; // Ok. #pragma omp target teams distribute simd for (int i = 0; i < 10; ++i) c[i] = a[i]; // Ok. #pragma omp target teams distribute simd for (ii = 0; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} for (ii = 0; ii < 10; ++jj) c[ii] = a[jj]; #pragma omp target teams distribute simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} for (ii = 0; ii < 10; ++++ii) c[ii] = a[ii]; // Ok but undefined behavior (in general, cannot check that incr // is really loop-invariant). #pragma omp target teams distribute simd for (ii = 0; ii < 10; ii = ii + ii) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{expression must have integral or unscoped enumeration type, not 'float'}} for (ii = 0; ii < 10; ii = ii + 1.0f) c[ii] = a[ii]; // Ok - step was converted to integer type. #pragma omp target teams distribute simd for (ii = 0; ii < 10; ii = ii + (int)1.1f) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} for (ii = 0; ii < 10; jj = ii + 2) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-warning@+2 {{relational comparison result unused}} // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} for (ii = 0; ii<10; jj> kk + 2) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} for (ii = 0; ii < 10;) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-warning@+2 {{expression result unused}} // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} for (ii = 0; ii < 10; !ii) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} for (ii = 0; ii < 10; ii ? ++ii : ++jj) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} for (ii = 0; ii < 10; ii = ii < 10) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} for (ii = 0; ii < 10; ii = ii + 0) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} for (ii = 0; ii < 10; ii = ii + (int)(0.8 - 0.45)) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} for (ii = 0; (ii) < 10; ii -= 25) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} for (ii = 0; (ii < 10); ii -= 0) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'ii' to decrease on each iteration of OpenMP for loop}} for (ii = 0; ii > 10; (ii += 0)) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} for (ii = 0; ii < 10; (ii) = (1 - 1) + (ii)) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'ii' to decrease on each iteration of OpenMP for loop}} for ((ii = 0); ii > 10; (ii -= 0)) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} for (ii = 0; (ii < 10); (ii -= 0)) c[ii] = a[ii]; #pragma omp target teams distribute simd firstprivate(ii) // expected-note {{defined as firstprivate}} // expected-error@+1 {{loop iteration variable in the associated loop of 'omp target teams distribute simd' directive may not be firstprivate, predetermined as linear}} for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; #pragma omp target teams distribute simd private(ii) // expected-note {{defined as private}} // expected-error@+1 {{loop iteration variable in the associated loop of 'omp target teams distribute simd' directive may not be private, predetermined as linear}} for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; #pragma omp target teams distribute simd lastprivate(ii) // expected-note {{defined as lastprivate}} // expected-error@+1 {{loop iteration variable in the associated loop of 'omp target teams distribute simd' directive may not be lastprivate, predetermined as linear}} for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; #pragma omp target teams distribute simd // expected-error@+1 {{loop iteration variable in the associated loop of 'omp target teams distribute simd' directive may not be threadprivate or thread local, predetermined as linear}} for (sii = 0; sii < 10; sii++) c[sii] = a[sii]; { #pragma omp target teams distribute simd collapse(2) for (ii = 0; ii < 10; ii += 1) for (globalii = 0; globalii < 10; globalii += 1) c[globalii] += a[globalii] + ii; } #pragma omp target teams distribute simd // expected-error@+1 {{statement after '#pragma omp target teams distribute simd' must be a for loop}} for (auto &item : a) { item = item + 1; } #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'i' to increase on each iteration of OpenMP for loop}} for (unsigned i = 9; i < 10; i--) { c[i] = a[i] + b[i]; } int(*lb)[4] = nullptr; #pragma omp target teams distribute simd for (int(*p)[4] = lb; p < lb + 8; ++p) { } #pragma omp target teams distribute simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (int a{0}; a < 10; ++a) { } return 0; } // Iterators allowed in openmp for-loops. namespace std { struct random_access_iterator_tag {}; template <class Iter> struct iterator_traits { typedef typename Iter::difference_type difference_type; typedef typename Iter::iterator_category iterator_category; }; template <class Iter> typename iterator_traits<Iter>::difference_type distance(Iter first, Iter last) { return first - last; } } class Iter0 { public: Iter0() {} Iter0(const Iter0 &) {} Iter0 operator++() { return *this; } Iter0 operator--() { return *this; } bool operator<(Iter0 a) { return true; } }; // expected-note@+2 {{candidate function not viable: no known conversion from 'GoodIter' to 'Iter0' for 1st argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'Iter0' for 1st argument}} int operator-(Iter0 a, Iter0 b) { return 0; } class Iter1 { public: Iter1(float f = 0.0f, double d = 0.0) {} Iter1(const Iter1 &) {} Iter1 operator++() { return *this; } Iter1 operator--() { return *this; } bool operator<(Iter1 a) { return true; } bool operator>=(Iter1 a) { return false; } }; class GoodIter { public: GoodIter() {} GoodIter(const GoodIter &) {} GoodIter(int fst, int snd) {} GoodIter &operator=(const GoodIter &that) { return *this; } GoodIter &operator=(const Iter0 &that) { return *this; } GoodIter &operator+=(int x) { return *this; } explicit GoodIter(void *) {} GoodIter operator++() { return *this; } GoodIter operator--() { return *this; } bool operator!() { return true; } bool operator<(GoodIter a) { return true; } bool operator<=(GoodIter a) { return true; } bool operator>=(GoodIter a) { return false; } typedef int difference_type; typedef std::random_access_iterator_tag iterator_category; }; // expected-note@+2 {{candidate function not viable: no known conversion from 'const Iter0' to 'GoodIter' for 2nd argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'GoodIter' for 1st argument}} int operator-(GoodIter a, GoodIter b) { return 0; } // expected-note@+1 3 {{candidate function not viable: requires single argument 'a', but 2 arguments were provided}} GoodIter operator-(GoodIter a) { return a; } // expected-note@+2 {{candidate function not viable: no known conversion from 'const Iter0' to 'int' for 2nd argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'GoodIter' for 1st argument}} GoodIter operator-(GoodIter a, int v) { return GoodIter(); } // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter0' to 'GoodIter' for 1st argument}} GoodIter operator+(GoodIter a, int v) { return GoodIter(); } // expected-note@+2 {{candidate function not viable: no known conversion from 'GoodIter' to 'int' for 1st argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'int' for 1st argument}} GoodIter operator-(int v, GoodIter a) { return GoodIter(); } // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter0' to 'int' for 1st argument}} GoodIter operator+(int v, GoodIter a) { return GoodIter(); } int test_with_random_access_iterator() { GoodIter begin, end; Iter0 begin0, end0; #pragma omp target teams distribute simd for (GoodIter I = begin; I < end; ++I) ++I; #pragma omp target teams distribute simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter &I = begin; I < end; ++I) ++I; #pragma omp target teams distribute simd for (GoodIter I = begin; I >= end; --I) ++I; #pragma omp target teams distribute simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter I(begin); I < end; ++I) ++I; #pragma omp target teams distribute simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter I(nullptr); I < end; ++I) ++I; #pragma omp target teams distribute simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter I(0); I < end; ++I) ++I; #pragma omp target teams distribute simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter I(1, 2); I < end; ++I) ++I; #pragma omp target teams distribute simd for (begin = GoodIter(0); begin < end; ++begin) ++begin; #pragma omp target teams distribute simd // expected-error@+2 {{invalid operands to binary expression ('GoodIter' and 'const Iter0')}} // expected-error@+1 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} for (begin = begin0; begin < end; ++begin) ++begin; #pragma omp target teams distribute simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (++begin; begin < end; ++begin) ++begin; #pragma omp target teams distribute simd for (begin = end; begin < end; ++begin) ++begin; #pragma omp target teams distribute simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} for (GoodIter I = begin; I - I; ++I) ++I; #pragma omp target teams distribute simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} for (GoodIter I = begin; begin < end; ++I) ++I; #pragma omp target teams distribute simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} for (GoodIter I = begin; !I; ++I) ++I; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (GoodIter I = begin; I >= end; I = I + 1) ++I; #pragma omp target teams distribute simd for (GoodIter I = begin; I >= end; I = I - 1) ++I; #pragma omp target teams distribute simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'I'}} for (GoodIter I = begin; I >= end; I = -I) ++I; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (GoodIter I = begin; I >= end; I = 2 + I) ++I; #pragma omp target teams distribute simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'I'}} for (GoodIter I = begin; I >= end; I = 2 - I) ++I; #pragma omp target teams distribute simd // expected-error@+1 {{invalid operands to binary expression ('Iter0' and 'int')}} for (Iter0 I = begin0; I < end0; ++I) ++I; #pragma omp target teams distribute simd // Initializer is constructor without params. // expected-error@+2 {{invalid operands to binary expression ('Iter0' and 'int')}} // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (Iter0 I; I < end0; ++I) ++I; Iter1 begin1, end1; #pragma omp target teams distribute simd // expected-error@+2 {{invalid operands to binary expression ('Iter1' and 'Iter1')}} // expected-error@+1 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} for (Iter1 I = begin1; I < end1; ++I) ++I; #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (Iter1 I = begin1; I >= end1; ++I) ++I; #pragma omp target teams distribute simd // expected-error@+4 {{invalid operands to binary expression ('Iter1' and 'float')}} // expected-error@+3 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} // Initializer is constructor with all default params. // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (Iter1 I; I < end1; ++I) { } return 0; } template <typename IT, int ST> class TC { public: int dotest_lt(IT begin, IT end) { #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to increase on each iteration of OpenMP for loop}} for (IT I = begin; I < end; I = I + ST) { ++I; } #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to increase on each iteration of OpenMP for loop}} for (IT I = begin; I <= end; I += ST) { ++I; } #pragma omp target teams distribute simd for (IT I = begin; I < end; ++I) { ++I; } } static IT step() { return IT(ST); } }; template <typename IT, int ST = 0> int dotest_gt(IT begin, IT end) { #pragma omp target teams distribute simd // expected-note@+2 2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (IT I = begin; I >= end; I = I + ST) { ++I; } #pragma omp target teams distribute simd // expected-note@+2 2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (IT I = begin; I >= end; I += ST) { ++I; } #pragma omp target teams distribute simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (IT I = begin; I >= end; ++I) { ++I; } #pragma omp target teams distribute simd for (IT I = begin; I < end; I += TC<int, ST>::step()) { ++I; } } void test_with_template() { GoodIter begin, end; TC<GoodIter, 100> t1; TC<GoodIter, -100> t2; t1.dotest_lt(begin, end); t2.dotest_lt(begin, end); // expected-note {{in instantiation of member function 'TC<GoodIter, -100>::dotest_lt' requested here}} dotest_gt(begin, end); // expected-note {{in instantiation of function template specialization 'dotest_gt<GoodIter, 0>' requested here}} dotest_gt<unsigned, -10>(0, 100); // expected-note {{in instantiation of function template specialization 'dotest_gt<unsigned int, -10>' requested here}} } void test_loop_break() { const int N = 100; float a[N], b[N], c[N]; #pragma omp target teams distribute simd for (int i = 0; i < 10; i++) { c[i] = a[i] + b[i]; for (int j = 0; j < 10; ++j) { if (a[i] > b[j]) break; // OK in nested loop } switch (i) { case 1: b[i]++; break; default: break; } if (c[i] > 10) break; // expected-error {{'break' statement cannot be used in OpenMP for loop}} if (c[i] > 11) break; // expected-error {{'break' statement cannot be used in OpenMP for loop}} } #pragma omp target teams distribute simd for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { c[i] = a[i] + b[i]; if (c[i] > 10) { if (c[i] < 20) { break; // OK } } } } } void test_loop_eh() { const int N = 100; float a[N], b[N], c[N]; #pragma omp target teams distribute simd for (int i = 0; i < 10; i++) { c[i] = a[i] + b[i]; try { // expected-error {{'try' statement cannot be used in OpenMP simd region}} for (int j = 0; j < 10; ++j) { if (a[i] > b[j]) throw a[i]; // expected-error {{throw' statement cannot be used in OpenMP simd region}} } throw a[i]; // expected-error {{throw' statement cannot be used in OpenMP simd region}} } catch (float f) { if (f > 0.1) throw a[i]; // expected-error {{throw' statement cannot be used in OpenMP simd region}} return; // expected-error {{cannot return from OpenMP region}} } switch (i) { case 1: b[i]++; break; default: break; } for (int j = 0; j < 10; j++) { if (c[i] > 10) throw c[i]; // expected-error {{throw' statement cannot be used in OpenMP simd region}} } } if (c[9] > 10) throw c[9]; // OK #pragma omp target teams distribute simd for (int i = 0; i < 10; ++i) { struct S { void g() { throw 0; } }; } } void test_loop_firstprivate_lastprivate() { S s(4); #pragma omp target teams distribute simd lastprivate(s) firstprivate(s) for (int i = 0; i < 16; ++i) ; } void test_ordered() { #pragma omp target teams distribute simd ordered // expected-error {{unexpected OpenMP clause 'ordered' in directive '#pragma omp target teams distribute simd'}} for (int i = 0; i < 16; ++i) ; } void test_nowait() { // expected-error@+1 {{directive '#pragma omp target teams distribute simd' cannot contain more than one 'nowait' clause}} #pragma omp target teams distribute simd nowait nowait for (int i = 0; i < 16; ++i) ; }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_parallel_for_simd_is_device_ptr_ast_print.cpp
318
// RUN: %clang_cc1 -verify -fopenmp -std=c++11 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER struct ST { int *a; }; typedef int arr[10]; typedef ST STarr[10]; struct SA { const int da[5] = { 0 }; ST g[10]; STarr &rg = g; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; arr &raa = aa; void func(int arg) { #pragma omp target teams distribute parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(aa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(raa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(g) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(rg) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(da) // OK for (int i=0; i<100; i++) ; return; } }; // CHECK: struct SA // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: ST g[10]; // CHECK-NEXT: STarr &rg = this->g; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = this->i; // CHECK-NEXT: int *k = &this->j; // CHECK-NEXT: int *&z = this->k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: arr &raa = this->aa; // CHECK-NEXT: func( // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->g) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->rg) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(this->da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; struct SB { unsigned A; unsigned B; float Arr[100]; float *Ptr; float *foo() { return &Arr[0]; } }; struct SC { unsigned A : 2; unsigned B : 3; unsigned C; unsigned D; float Arr[100]; SB S; SB ArrS[100]; SB *PtrS; SB *&RPtrS; float *Ptr; SC(SB *&_RPtrS) : RPtrS(_RPtrS) {} }; union SD { unsigned A; float B; }; struct S1; extern S1 a; class S2 { mutable int a; public: S2():a(0) { } S2(S2 &s2):a(s2.a) { } static float S2s; static const float S2sc; }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3():a(0) { } S3(S3 &s3):a(s3.a) { } }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} S5(const S5 &s5):a(s5.a) { } public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) typedef struct { int a; } S6; template <typename T> T tmain(T argc) { const T da[5] = { 0 }; S6 h[10]; auto &rh = h; T i; T &j = i; T *k = &j; T *&z = k; T aa[10]; auto &raa = aa; #pragma omp target teams distribute parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(aa) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(raa) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(h) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(rh) for (int i=0; i<100; i++) ; #pragma omp target teams distribute parallel for simd is_device_ptr(da) for (int i=0; i<100; i++) ; return 0; } // CHECK: template<> int tmain<int>(int argc) { // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK: template<> int *tmain<int *>(int *argc) { // CHECK-NEXT: int *const da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int *i; // CHECK-NEXT: int *&j = i; // CHECK-NEXT: int **k = &j; // CHECK-NEXT: int **&z = k; // CHECK-NEXT: int *aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-LABEL: int main(int argc, char **argv) { int main(int argc, char **argv) { const int da[5] = { 0 }; S6 h[10]; auto &rh = h; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; auto &raa = aa; // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; #pragma omp target teams distribute parallel for simd is_device_ptr(k) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(k) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(z) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(z) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(aa) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(aa) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(raa) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(raa) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(h) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(h) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(rh) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(rh) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute parallel for simd is_device_ptr(da) // CHECK-NEXT: #pragma omp target teams distribute parallel for simd is_device_ptr(da) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; return tmain<int>(argc) + *tmain<int *>(&argc); } #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/distribute_private_codegen.cpp
206
// RUN: %clang_cc1 -DLAMBDA -verify -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix LAMBDA --check-prefix LAMBDA-64 // RUN: %clang_cc1 -DLAMBDA -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -DLAMBDA -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix LAMBDA --check-prefix LAMBDA-64 // RUN: %clang_cc1 -DLAMBDA -verify -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix LAMBDA --check-prefix LAMBDA-32 // RUN: %clang_cc1 -DLAMBDA -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -DLAMBDA -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix LAMBDA --check-prefix LAMBDA-32 // RUN: %clang_cc1 -verify -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // expected-no-diagnostics #ifndef HEADER #define HEADER template <class T> struct S { T f; S(T a) : f(a) {} S() : f() {} operator T() { return T(); } ~S() {} }; // CHECK: [[S_FLOAT_TY:%.+]] = type { float } // CHECK: [[S_INT_TY:%.+]] = type { i{{[0-9]+}} } template <typename T> T tmain() { S<T> test; T t_var = T(); T vec[] = {1, 2}; S<T> s_arr[] = {1, 2}; S<T> &var = test; #pragma omp target #pragma omp teams #pragma omp distribute private(t_var, vec, s_arr, s_arr, var, var) for (int i = 0; i < 2; ++i) { vec[i] = t_var; s_arr[i] = var; } return T(); } int main() { static int svar; volatile double g; volatile double &g1 = g; #ifdef LAMBDA // LAMBDA-LABEL: @main // LAMBDA: call{{.*}} void [[OUTER_LAMBDA:@.+]]( [&]() { static float sfvar; // LAMBDA: define{{.*}} internal{{.*}} void [[OUTER_LAMBDA]]( // LAMBDA: call i{{[0-9]+}} @__tgt_target_teams( // LAMBDA: call void [[OFFLOADING_FUN:@.+]]( // LAMBDA: define{{.+}} void [[OFFLOADING_FUN]]() // LAMBDA: call {{.*}}void {{.+}} @__kmpc_fork_teams({{.+}}, i32 0, {{.+}}* [[OMP_OUTLINED:@.+]] to {{.+}}) #pragma omp target #pragma omp teams #pragma omp distribute private(g, g1, svar, sfvar) for (int i = 0; i < 2; ++i) { // LAMBDA: define{{.*}} internal{{.*}} void [[OMP_OUTLINED]](i32* noalias %{{.+}}, i32* noalias %{{.+}}) // LAMBDA: [[G_PRIVATE_ADDR:%.+]] = alloca double, // LAMBDA: [[G1_PRIVATE_ADDR:%.+]] = alloca double, // LAMBDA: [[TMP_PRIVATE_ADDR:%.+]] = alloca double*, // LAMBDA: [[SVAR_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}}, // LAMBDA: [[SFVAR_PRIVATE_ADDR:%.+]] = alloca float, // LAMBDA: store double* [[G1_PRIVATE_ADDR]], double** [[TMP_PRIVATE_ADDR]], g = 1; g1 = 1; svar = 3; sfvar = 4.0; // LAMBDA: call {{.*}}void @__kmpc_for_static_init_4( // LAMBDA: store double 1.0{{.+}}, double* [[G_PRIVATE_ADDR]], // LAMBDA: store i{{[0-9]+}} 3, i{{[0-9]+}}* [[SVAR_PRIVATE_ADDR]], // LAMBDA: store float 4.0{{.+}}, float* [[SFVAR_PRIVATE_ADDR]], // LAMBDA: [[G_PRIVATE_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 0 // LAMBDA: store double* [[G_PRIVATE_ADDR]], double** [[G_PRIVATE_ADDR_REF]], // LAMBDA: [[TMP_PRIVATE_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 1 // LAMBDA: [[G1_PRIVATE_ADDR_FROM_TMP:%.+]] = load double*, double** [[TMP_PRIVATE_ADDR]], // LAMBDA: store double* [[G1_PRIVATE_ADDR_FROM_TMP]], double** [[TMP_PRIVATE_ADDR_REF]], // LAMBDA: [[SVAR_PRIVATE_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 2 // LAMBDA: store i{{[0-9]+}}* [[SVAR_PRIVATE_ADDR]], i{{[0-9]+}}** [[SVAR_PRIVATE_ADDR_REF]] // LAMBDA: [[SFVAR_PRIVATE_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 3 // LAMBDA: store float* [[SFVAR_PRIVATE_ADDR]], float** [[SFVAR_PRIVATE_ADDR_REF]] // LAMBDA: call{{.*}} void [[INNER_LAMBDA:@.+]](%{{.+}}* [[ARG]]) // LAMBDA: call {{.*}}void @__kmpc_for_static_fini( [&]() { // LAMBDA: define {{.+}} void [[INNER_LAMBDA]](%{{.+}}* [[ARG_PTR:%.+]]) // LAMBDA: store %{{.+}}* [[ARG_PTR]], %{{.+}}** [[ARG_PTR_REF:%.+]], g = 2; g1 = 2; svar = 4; sfvar = 8.0; // LAMBDA: [[ARG_PTR:%.+]] = load %{{.+}}*, %{{.+}}** [[ARG_PTR_REF]] // LAMBDA: [[G_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 0 // LAMBDA: [[G_REF:%.+]] = load double*, double** [[G_PTR_REF]] // LAMBDA: store double 2.0{{.+}}, double* [[G_REF]] // LAMBDA: [[TMP_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 1 // LAMBDA: [[G1_REF:%.+]] = load double*, double** [[TMP_PTR_REF]] // LAMBDA: store double 2.0{{.+}}, double* [[G1_REF]], // LAMBDA: [[SVAR_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 2 // LAMBDA: [[SVAR_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[SVAR_PTR_REF]] // LAMBDA: store i{{[0-9]+}} 4, i{{[0-9]+}}* [[SVAR_REF]] // LAMBDA: [[SFVAR_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 3 // LAMBDA: [[SFVAR_REF:%.+]] = load float*, float** [[SFVAR_PTR_REF]] // LAMBDA: store float 8.0{{.+}}, float* [[SFVAR_REF]] }(); } }(); return 0; #else S<float> test; int t_var = 0; int vec[] = {1, 2}; S<float> s_arr[] = {1, 2}; S<float> &var = test; #pragma omp target #pragma omp teams #pragma omp distribute private(t_var, vec, s_arr, s_arr, var, var, svar) for (int i = 0; i < 2; ++i) { vec[i] = t_var; s_arr[i] = var; } int i; #pragma omp target #pragma omp teams #pragma omp distribute private(i) for (i = 0; i < 2; ++i) { ; } return tmain<int>(); #endif } // CHECK: define{{.*}} i{{[0-9]+}} @main() // CHECK: [[TEST:%.+]] = alloca [[S_FLOAT_TY]], // CHECK: call {{.*}} [[S_FLOAT_TY_DEF_CONSTR:@.+]]([[S_FLOAT_TY]]* [[TEST]]) // CHECK: call i{{[0-9]+}} @__tgt_target_teams( // CHECK: call void [[OFFLOAD_FUN:@.+]]( // CHECK: ret // CHECK: define{{.+}} [[OFFLOAD_FUN]]() // CHECK: call void (%{{.+}}*, i{{[0-9]+}}, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)*, ...) @__kmpc_fork_teams(%{{.+}}* @{{.+}}, i{{[0-9]+}} 0, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)* bitcast (void (i{{[0-9]+}}*, i{{[0-9]+}}*)* [[OMP_OUTLINED:@.+]] to void // CHECK: ret // // CHECK: define internal void [[OMP_OUTLINED]](i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}) // CHECK: [[T_VAR_PRIV:%.+]] = alloca i{{[0-9]+}}, // CHECK: [[VEC_PRIV:%.+]] = alloca [2 x i{{[0-9]+}}], // CHECK: [[S_ARR_PRIV:%.+]] = alloca [2 x [[S_FLOAT_TY]]], // CHECK-NOT: alloca [2 x [[S_FLOAT_TY]]], // CHECK: [[VAR_PRIV:%.+]] = alloca [[S_FLOAT_TY]], // CHECK-NOT: alloca [[S_FLOAT_TY]], // CHECK: [[S_VAR_PRIV:%.+]] = alloca i{{[0-9]+}}, // CHECK: store i{{[0-9]+}}* [[GTID_ADDR]], i{{[0-9]+}}** [[GTID_ADDR_REF:%.+]] // CHECK-NOT: [[T_VAR_PRIV]] // CHECK-NOT: [[VEC_PRIV]] // CHECK: {{.+}}: // CHECK: [[S_ARR_PRIV_ITEM:%.+]] = phi [[S_FLOAT_TY]]* // CHECK: call {{.*}} [[S_FLOAT_TY_DEF_CONSTR]]([[S_FLOAT_TY]]* [[S_ARR_PRIV_ITEM]]) // CHECK-NOT: [[T_VAR_PRIV]] // CHECK-NOT: [[VEC_PRIV]] // CHECK: call {{.*}} [[S_FLOAT_TY_DEF_CONSTR]]([[S_FLOAT_TY]]* [[VAR_PRIV]]) // CHECK: call void @__kmpc_for_static_init_4( // CHECK: call void @__kmpc_for_static_fini( // CHECK: ret void // CHECK: define{{.*}} i{{[0-9]+}} [[TMAIN_INT:@.+]]() // CHECK: [[TEST:%.+]] = alloca [[S_INT_TY]], // CHECK: call {{.*}} [[S_INT_TY_DEF_CONSTR:@.+]]([[S_INT_TY]]* [[TEST]]) // CHECK: call i{{[0-9]+}} @__tgt_target_teams( // CHECK: call void [[OFFLOAD_FUN_1:@.+]]( // CHECK: ret // CHECK: define internal void [[OFFLOAD_FUN_1]]() // CHECK: call void (%{{.+}}*, i{{[0-9]+}}, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)*, ...) @__kmpc_fork_teams(%{{.+}}* @{{.+}}, i{{[0-9]+}} 0, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)* bitcast (void (i{{[0-9]+}}*, i{{[0-9]+}}*)* [[OMP_OUTLINED_1:@.+]] to void // CHECK: ret // // CHECK: define internal void [[OMP_OUTLINED_1]](i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}) // CHECK: [[T_VAR_PRIV:%.+]] = alloca i{{[0-9]+}}, // CHECK: [[VEC_PRIV:%.+]] = alloca [2 x i{{[0-9]+}}], // CHECK: [[S_ARR_PRIV:%.+]] = alloca [2 x [[S_INT_TY]]], // CHECK-NOT: alloca [2 x [[S_INT_TY]]], // CHECK: [[VAR_PRIV:%.+]] = alloca [[S_INT_TY]], // CHECK-NOT: alloca [[S_INT_TY]], // CHECK: store i{{[0-9]+}}* [[GTID_ADDR]], i{{[0-9]+}}** [[GTID_ADDR_REF:%.+]] // CHECK-NOT: [[T_VAR_PRIV]] // CHECK-NOT: [[VEC_PRIV]] // CHECK: {{.+}}: // CHECK: [[S_ARR_PRIV_ITEM:%.+]] = phi [[S_INT_TY]]* // CHECK: call {{.*}} [[S_INT_TY_DEF_CONSTR]]([[S_INT_TY]]* [[S_ARR_PRIV_ITEM]]) // CHECK-NOT: [[T_VAR_PRIV]] // CHECK-NOT: [[VEC_PRIV]] // CHECK: call {{.*}} [[S_INT_TY_DEF_CONSTR]]([[S_INT_TY]]* [[VAR_PRIV]]) // CHECK: call void @__kmpc_for_static_init_4( // CHECK: call void @__kmpc_for_static_fini( // CHECK: ret void #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_parallel_for_is_device_ptr_ast_print.cpp
315
// RUN: %clang_cc1 -verify -fopenmp -std=c++11 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER void foo() {} struct ST { int *a; }; typedef int arr[10]; typedef ST STarr[10]; struct SA { const int da[5] = { 0 }; ST g[10]; STarr &rg = g; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; arr &raa = aa; void func(int arg) { #pragma omp target parallel for is_device_ptr(k) for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(z) for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(aa) // OK for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(raa) // OK for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(g) // OK for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(rg) // OK for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(da) // OK for (int i=0; i<100; i++) foo(); return; } }; // CHECK: struct SA // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: ST g[10]; // CHECK-NEXT: STarr &rg = this->g; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = this->i; // CHECK-NEXT: int *k = &this->j; // CHECK-NEXT: int *&z = this->k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: arr &raa = this->aa; // CHECK-NEXT: func( // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(this->k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(this->z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(this->aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(this->raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(this->g) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(this->rg) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(this->da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); struct SB { unsigned A; unsigned B; float Arr[100]; float *Ptr; float *foo() { return &Arr[0]; } }; struct SC { unsigned A : 2; unsigned B : 3; unsigned C; unsigned D; float Arr[100]; SB S; SB ArrS[100]; SB *PtrS; SB *&RPtrS; float *Ptr; SC(SB *&_RPtrS) : RPtrS(_RPtrS) {} }; union SD { unsigned A; float B; }; struct S1; extern S1 a; class S2 { mutable int a; public: S2():a(0) { } S2(S2 &s2):a(s2.a) { } static float S2s; static const float S2sc; }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3():a(0) { } S3(S3 &s3):a(s3.a) { } }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} S5(const S5 &s5):a(s5.a) { } public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) typedef struct { int a; } S6; template <typename T> T tmain(T argc) { const T da[5] = { 0 }; S6 h[10]; auto &rh = h; T i; T &j = i; T *k = &j; T *&z = k; T aa[10]; auto &raa = aa; #pragma omp target parallel for is_device_ptr(k) for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(z) for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(aa) for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(raa) for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(h) for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(rh) for (int i=0; i<100; i++) foo(); #pragma omp target parallel for is_device_ptr(da) for (int i=0; i<100; i++) foo(); return 0; } // CHECK: template<> int tmain<int>(int argc) { // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK: template<> int *tmain<int *>(int *argc) { // CHECK-NEXT: int *const da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int *i; // CHECK-NEXT: int *&j = i; // CHECK-NEXT: int **k = &j; // CHECK-NEXT: int **&z = k; // CHECK-NEXT: int *aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); // CHECK-LABEL: int main(int argc, char **argv) { int main(int argc, char **argv) { const int da[5] = { 0 }; S6 h[10]; auto &rh = h; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; auto &raa = aa; // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; #pragma omp target parallel for is_device_ptr(k) for (int i=0; i<100; i++) foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); #pragma omp target parallel for is_device_ptr(z) for (int i=0; i<100; i++) foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); #pragma omp target parallel for is_device_ptr(aa) for (int i=0; i<100; i++) foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); #pragma omp target parallel for is_device_ptr(raa) for (int i=0; i<100; i++) foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); #pragma omp target parallel for is_device_ptr(h) for (int i=0; i<100; i++) foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); #pragma omp target parallel for is_device_ptr(rh) for (int i=0; i<100; i++) foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); #pragma omp target parallel for is_device_ptr(da) for (int i=0; i<100; i++) foo(); // CHECK-NEXT: #pragma omp target parallel for is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: foo(); return tmain<int>(argc) + *tmain<int *>(&argc); } #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/nvptx_target_parallel_codegen.cpp
136
// Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -fexceptions -fcxx-exceptions -x c++ -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // expected-no-diagnostics #ifndef HEADER #define HEADER // Check that the execution mode of all 2 target regions on the gpu is set to SPMD Mode. // CHECK-DAG: {{@__omp_offloading_.+l26}}_exec_mode = weak constant i8 0 // CHECK-DAG: {{@__omp_offloading_.+l31}}_exec_mode = weak constant i8 0 template<typename tx> tx ftemplate(int n) { tx a = 0; short aa = 0; tx b[10]; #pragma omp target parallel if(target: 0) { a += 1; } #pragma omp target parallel map(tofrom: aa) { aa += 1; } #pragma omp target parallel map(tofrom:a, aa, b) if(target: n>40) { a += 1; aa += 1; b[2] += 1; } return a; } int bar(int n){ int a = 0; a += ftemplate<int>(n); return a; } // CHECK-NOT: define {{.*}}void {{@__omp_offloading_.+template.+l17}} // CHECK-LABEL: define {{.*}}void {{@__omp_offloading_.+template.+l26}}( // CHECK: [[AA_ADDR:%.+]] = alloca i16*, align // CHECK: store i16* {{%.+}}, i16** [[AA_ADDR]], align // CHECK: [[AA:%.+]] = load i16*, i16** [[AA_ADDR]], align // CHECK: [[THREAD_LIMIT:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK: call void @__kmpc_spmd_kernel_init(i32 [[THREAD_LIMIT]], // CHECK: br label {{%?}}[[EXEC:.+]] // // CHECK: [[EXEC]] // CHECK: {{call|invoke}} void [[OP1:@.+]](i32* null, i32* null, i16* [[AA]]) // CHECK: br label {{%?}}[[DONE:.+]] // // CHECK: [[DONE]] // CHECK: call void @__kmpc_spmd_kernel_deinit() // CHECK: br label {{%?}}[[EXIT:.+]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK: } // CHECK: define internal void [[OP1]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i16* {{[^%]*}}[[ARG:%.+]]) // CHECK: = alloca i32*, align // CHECK: = alloca i32*, align // CHECK: [[AA_ADDR:%.+]] = alloca i16*, align // CHECK: store i16* [[ARG]], i16** [[AA_ADDR]], align // CHECK: [[AA:%.+]] = load i16*, i16** [[AA_ADDR]], align // CHECK: [[VAL:%.+]] = load i16, i16* [[AA]], align // CHECK: store i16 {{%.+}}, i16* [[AA]], align // CHECK: ret void // CHECK: } // CHECK-LABEL: define {{.*}}void {{@__omp_offloading_.+template.+l31}}( // CHECK: [[A_ADDR:%.+]] = alloca i32*, align // CHECK: [[AA_ADDR:%.+]] = alloca i16*, align // CHECK: [[B_ADDR:%.+]] = alloca [10 x i32]*, align // CHECK: store i32* {{%.+}}, i32** [[A_ADDR]], align // CHECK: store i16* {{%.+}}, i16** [[AA_ADDR]], align // CHECK: store [10 x i32]* {{%.+}}, [10 x i32]** [[B_ADDR]], align // CHECK: [[A:%.+]] = load i32*, i32** [[A_ADDR]], align // CHECK: [[AA:%.+]] = load i16*, i16** [[AA_ADDR]], align // CHECK: [[B:%.+]] = load [10 x i32]*, [10 x i32]** [[B_ADDR]], align // CHECK: [[THREAD_LIMIT:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK: call void @__kmpc_spmd_kernel_init(i32 [[THREAD_LIMIT]], // CHECK: br label {{%?}}[[EXEC:.+]] // // CHECK: [[EXEC]] // CHECK: {{call|invoke}} void [[OP2:@.+]](i32* null, i32* null, i32* [[A]], i16* [[AA]], [10 x i32]* [[B]]) // CHECK: br label {{%?}}[[DONE:.+]] // // CHECK: [[DONE]] // CHECK: call void @__kmpc_spmd_kernel_deinit() // CHECK: br label {{%?}}[[EXIT:.+]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK: } // CHECK: define internal void [[OP2]](i32* noalias %.global_tid., i32* noalias %.bound_tid., i32* {{[^%]*}}[[ARG1:%.+]], i16* {{[^%]*}}[[ARG2:%.+]], [10 x i32]* {{[^%]*}}[[ARG3:%.+]]) // CHECK: = alloca i32*, align // CHECK: = alloca i32*, align // CHECK: [[A_ADDR:%.+]] = alloca i32*, align // CHECK: [[AA_ADDR:%.+]] = alloca i16*, align // CHECK: [[B_ADDR:%.+]] = alloca [10 x i32]*, align // CHECK: store i32* [[ARG1]], i32** [[A_ADDR]], align // CHECK: store i16* [[ARG2]], i16** [[AA_ADDR]], align // CHECK: store [10 x i32]* [[ARG3]], [10 x i32]** [[B_ADDR]], align // CHECK: [[A:%.+]] = load i32*, i32** [[A_ADDR]], align // CHECK: [[AA:%.+]] = load i16*, i16** [[AA_ADDR]], align // CHECK: [[B:%.+]] = load [10 x i32]*, [10 x i32]** [[B_ADDR]], align // CHECK: store i32 {{%.+}}, i32* [[A]], align // CHECK: store i16 {{%.+}}, i16* [[AA]], align // CHECK: [[ELT:%.+]] = getelementptr inbounds [10 x i32], [10 x i32]* [[B]], // CHECK: store i32 {{%.+}}, i32* [[ELT]], align // CHECK: ret void // CHECK: } #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
lib/CodeGen/CGOpenMPRuntimeNVPTX.cpp
590
//===---- CGOpenMPRuntimeNVPTX.cpp - Interface to OpenMP NVPTX Runtimes ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This provides a class for OpenMP runtime code generation specialized to NVPTX // targets. // //===----------------------------------------------------------------------===// #include "CGOpenMPRuntimeNVPTX.h" #include "clang/AST/DeclOpenMP.h" #include "CodeGenFunction.h" #include "clang/AST/StmtOpenMP.h" using namespace clang; using namespace CodeGen; namespace { enum OpenMPRTLFunctionNVPTX { /// \brief Call to void __kmpc_kernel_init(kmp_int32 thread_limit); OMPRTL_NVPTX__kmpc_kernel_init, /// \brief Call to void __kmpc_kernel_deinit(); OMPRTL_NVPTX__kmpc_kernel_deinit, /// \brief Call to void __kmpc_spmd_kernel_init(kmp_int32 thread_limit, /// short RequiresOMPRuntime, short RequiresDataSharing); OMPRTL_NVPTX__kmpc_spmd_kernel_init, /// \brief Call to void __kmpc_spmd_kernel_deinit(); OMPRTL_NVPTX__kmpc_spmd_kernel_deinit, /// \brief Call to void __kmpc_kernel_prepare_parallel(void /// *outlined_function); OMPRTL_NVPTX__kmpc_kernel_prepare_parallel, /// \brief Call to bool __kmpc_kernel_parallel(void **outlined_function); OMPRTL_NVPTX__kmpc_kernel_parallel, /// \brief Call to void __kmpc_kernel_end_parallel(); OMPRTL_NVPTX__kmpc_kernel_end_parallel, /// Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 /// global_tid); OMPRTL_NVPTX__kmpc_serialized_parallel, /// Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 /// global_tid); OMPRTL_NVPTX__kmpc_end_serialized_parallel, }; /// Pre(post)-action for different OpenMP constructs specialized for NVPTX. class NVPTXActionTy final : public PrePostActionTy { llvm::Value *EnterCallee; ArrayRef<llvm::Value *> EnterArgs; llvm::Value *ExitCallee; ArrayRef<llvm::Value *> ExitArgs; bool Conditional; llvm::BasicBlock *ContBlock = nullptr; public: NVPTXActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs, llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs, bool Conditional = false) : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee), ExitArgs(ExitArgs), Conditional(Conditional) {} void Enter(CodeGenFunction &CGF) override { llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs); if (Conditional) { llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes); auto *ThenBlock = CGF.createBasicBlock("omp_if.then"); ContBlock = CGF.createBasicBlock("omp_if.end"); // Generate the branch (If-stmt) CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock); CGF.EmitBlock(ThenBlock); } } void Done(CodeGenFunction &CGF) { // Emit the rest of blocks/branches CGF.EmitBranch(ContBlock); CGF.EmitBlock(ContBlock, true); } void Exit(CodeGenFunction &CGF) override { CGF.EmitRuntimeCall(ExitCallee, ExitArgs); } }; // A class to track the execution mode when codegening directives within // a target region. The appropriate mode (generic/spmd) is set on entry // to the target region and used by containing directives such as 'parallel' // to emit optimized code. class ExecutionModeRAII { private: CGOpenMPRuntimeNVPTX::ExecutionMode SavedMode; CGOpenMPRuntimeNVPTX::ExecutionMode &Mode; public: ExecutionModeRAII(CGOpenMPRuntimeNVPTX::ExecutionMode &Mode, CGOpenMPRuntimeNVPTX::ExecutionMode NewMode) : Mode(Mode) { SavedMode = Mode; Mode = NewMode; } ~ExecutionModeRAII() { Mode = SavedMode; } }; } // anonymous namespace /// Get the GPU warp size. static llvm::Value *getNVPTXWarpSize(CodeGenFunction &CGF) { CGBuilderTy &Bld = CGF.Builder; return Bld.CreateCall( llvm::Intrinsic::getDeclaration( &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_warpsize), llvm::None, "nvptx_warp_size"); } /// Get the id of the current thread on the GPU. static llvm::Value *getNVPTXThreadID(CodeGenFunction &CGF) { CGBuilderTy &Bld = CGF.Builder; return Bld.CreateCall( llvm::Intrinsic::getDeclaration( &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_tid_x), llvm::None, "nvptx_tid"); } /// Get the maximum number of threads in a block of the GPU. static llvm::Value *getNVPTXNumThreads(CodeGenFunction &CGF) { CGBuilderTy &Bld = CGF.Builder; return Bld.CreateCall( llvm::Intrinsic::getDeclaration( &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_read_ptx_sreg_ntid_x), llvm::None, "nvptx_num_threads"); } /// Get barrier to synchronize all threads in a block. static void getNVPTXCTABarrier(CodeGenFunction &CGF) { CGBuilderTy &Bld = CGF.Builder; Bld.CreateCall(llvm::Intrinsic::getDeclaration( &CGF.CGM.getModule(), llvm::Intrinsic::nvvm_barrier0)); } /// Synchronize all GPU threads in a block. static void syncCTAThreads(CodeGenFunction &CGF) { getNVPTXCTABarrier(CGF); } /// Get the value of the thread_limit clause in the teams directive. /// For the 'generic' execution mode, the runtime encodes thread_limit in /// the launch parameters, always starting thread_limit+warpSize threads per /// CTA. The threads in the last warp are reserved for master execution. /// For the 'spmd' execution mode, all threads in a CTA are part of the team. static llvm::Value *getThreadLimit(CodeGenFunction &CGF, bool IsInSpmdExecutionMode = false) { CGBuilderTy &Bld = CGF.Builder; return IsInSpmdExecutionMode ? getNVPTXNumThreads(CGF) : Bld.CreateSub(getNVPTXNumThreads(CGF), getNVPTXWarpSize(CGF), "thread_limit"); } /// Get the thread id of the OMP master thread. /// The master thread id is the first thread (lane) of the last warp in the /// GPU block. Warp size is assumed to be some power of 2. /// Thread id is 0 indexed. /// E.g: If NumThreads is 33, master id is 32. /// If NumThreads is 64, master id is 32. /// If NumThreads is 1024, master id is 992. static llvm::Value *getMasterThreadID(CodeGenFunction &CGF) { CGBuilderTy &Bld = CGF.Builder; llvm::Value *NumThreads = getNVPTXNumThreads(CGF); // We assume that the warp size is a power of 2. llvm::Value *Mask = Bld.CreateSub(getNVPTXWarpSize(CGF), Bld.getInt32(1)); return Bld.CreateAnd(Bld.CreateSub(NumThreads, Bld.getInt32(1)), Bld.CreateNot(Mask), "master_tid"); } CGOpenMPRuntimeNVPTX::WorkerFunctionState::WorkerFunctionState( CodeGenModule &CGM) : WorkerFn(nullptr), CGFI(nullptr) { createWorkerFunction(CGM); } void CGOpenMPRuntimeNVPTX::WorkerFunctionState::createWorkerFunction( CodeGenModule &CGM) { // Create an worker function with no arguments. CGFI = &CGM.getTypes().arrangeNullaryFunction(); WorkerFn = llvm::Function::Create( CGM.getTypes().GetFunctionType(*CGFI), llvm::GlobalValue::InternalLinkage, /* placeholder */ "_worker", &CGM.getModule()); CGM.SetInternalFunctionAttributes(/*D=*/nullptr, WorkerFn, *CGFI); } bool CGOpenMPRuntimeNVPTX::isInSpmdExecutionMode() const { return CurrentExecutionMode == CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd; } static CGOpenMPRuntimeNVPTX::ExecutionMode getExecutionModeForDirective(CodeGenModule &CGM, const OMPExecutableDirective &D) { OpenMPDirectiveKind DirectiveKind = D.getDirectiveKind(); switch (DirectiveKind) { case OMPD_target: case OMPD_target_teams: return CGOpenMPRuntimeNVPTX::ExecutionMode::Generic; case OMPD_target_parallel: return CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd; default: llvm_unreachable("Unsupported directive on NVPTX device."); } llvm_unreachable("Unsupported directive on NVPTX device."); } void CGOpenMPRuntimeNVPTX::emitGenericKernel(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { ExecutionModeRAII ModeRAII(CurrentExecutionMode, CGOpenMPRuntimeNVPTX::ExecutionMode::Generic); EntryFunctionState EST; WorkerFunctionState WST(CGM); Work.clear(); // Emit target region as a standalone region. class NVPTXPrePostActionTy : public PrePostActionTy { CGOpenMPRuntimeNVPTX &RT; CGOpenMPRuntimeNVPTX::EntryFunctionState &EST; CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST; public: NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT, CGOpenMPRuntimeNVPTX::EntryFunctionState &EST, CGOpenMPRuntimeNVPTX::WorkerFunctionState &WST) : RT(RT), EST(EST), WST(WST) {} void Enter(CodeGenFunction &CGF) override { RT.emitGenericEntryHeader(CGF, EST, WST); } void Exit(CodeGenFunction &CGF) override { RT.emitGenericEntryFooter(CGF, EST); } } Action(*this, EST, WST); CodeGen.setAction(Action); emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen); // Create the worker function emitWorkerFunction(WST); // Now change the name of the worker function to correspond to this target // region's entry function. WST.WorkerFn->setName(OutlinedFn->getName() + "_worker"); } // Setup NVPTX threads for master-worker OpenMP scheme. void CGOpenMPRuntimeNVPTX::emitGenericEntryHeader(CodeGenFunction &CGF, EntryFunctionState &EST, WorkerFunctionState &WST) { CGBuilderTy &Bld = CGF.Builder; llvm::BasicBlock *WorkerBB = CGF.createBasicBlock(".worker"); llvm::BasicBlock *MasterCheckBB = CGF.createBasicBlock(".mastercheck"); llvm::BasicBlock *MasterBB = CGF.createBasicBlock(".master"); EST.ExitBB = CGF.createBasicBlock(".exit"); auto *IsWorker = Bld.CreateICmpULT(getNVPTXThreadID(CGF), getThreadLimit(CGF)); Bld.CreateCondBr(IsWorker, WorkerBB, MasterCheckBB); CGF.EmitBlock(WorkerBB); CGF.EmitCallOrInvoke(WST.WorkerFn, llvm::None); CGF.EmitBranch(EST.ExitBB); CGF.EmitBlock(MasterCheckBB); auto *IsMaster = Bld.CreateICmpEQ(getNVPTXThreadID(CGF), getMasterThreadID(CGF)); Bld.CreateCondBr(IsMaster, MasterBB, EST.ExitBB); CGF.EmitBlock(MasterBB); // First action in sequential region: // Initialize the state of the OpenMP runtime library on the GPU. llvm::Value *Args[] = {getThreadLimit(CGF)}; CGF.EmitRuntimeCall( createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_init), Args); } void CGOpenMPRuntimeNVPTX::emitGenericEntryFooter(CodeGenFunction &CGF, EntryFunctionState &EST) { if (!EST.ExitBB) EST.ExitBB = CGF.createBasicBlock(".exit"); llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".termination.notifier"); CGF.EmitBranch(TerminateBB); CGF.EmitBlock(TerminateBB); // Signal termination condition. CGF.EmitRuntimeCall( createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_deinit), None); // Barrier to terminate worker threads. syncCTAThreads(CGF); // Master thread jumps to exit point. CGF.EmitBranch(EST.ExitBB); CGF.EmitBlock(EST.ExitBB); EST.ExitBB = nullptr; } void CGOpenMPRuntimeNVPTX::emitSpmdKernel(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { ExecutionModeRAII ModeRAII(CurrentExecutionMode, CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd); EntryFunctionState EST; // Emit target region as a standalone region. class NVPTXPrePostActionTy : public PrePostActionTy { CGOpenMPRuntimeNVPTX &RT; CGOpenMPRuntimeNVPTX::EntryFunctionState &EST; const OMPExecutableDirective &D; public: NVPTXPrePostActionTy(CGOpenMPRuntimeNVPTX &RT, CGOpenMPRuntimeNVPTX::EntryFunctionState &EST, const OMPExecutableDirective &D) : RT(RT), EST(EST), D(D) {} void Enter(CodeGenFunction &CGF) override { RT.emitSpmdEntryHeader(CGF, EST, D); } void Exit(CodeGenFunction &CGF) override { RT.emitSpmdEntryFooter(CGF, EST); } } Action(*this, EST, D); CodeGen.setAction(Action); emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen); return; } void CGOpenMPRuntimeNVPTX::emitSpmdEntryHeader( CodeGenFunction &CGF, EntryFunctionState &EST, const OMPExecutableDirective &D) { auto &Bld = CGF.Builder; // Setup BBs in entry function. llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute"); EST.ExitBB = CGF.createBasicBlock(".exit"); // Initialize the OMP state in the runtime; called by all active threads. // TODO: Set RequiresOMPRuntime and RequiresDataSharing parameters // based on code analysis of the target region. llvm::Value *Args[] = {getThreadLimit(CGF, /*IsInSpmdExecutionMode=*/true), /*RequiresOMPRuntime=*/Bld.getInt16(1), /*RequiresDataSharing=*/Bld.getInt16(1)}; CGF.EmitRuntimeCall( createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_init), Args); CGF.EmitBranch(ExecuteBB); CGF.EmitBlock(ExecuteBB); } void CGOpenMPRuntimeNVPTX::emitSpmdEntryFooter(CodeGenFunction &CGF, EntryFunctionState &EST) { if (!EST.ExitBB) EST.ExitBB = CGF.createBasicBlock(".exit"); llvm::BasicBlock *OMPDeInitBB = CGF.createBasicBlock(".omp.deinit"); CGF.EmitBranch(OMPDeInitBB); CGF.EmitBlock(OMPDeInitBB); // DeInitialize the OMP state in the runtime; called by all active threads. CGF.EmitRuntimeCall( createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_spmd_kernel_deinit), None); CGF.EmitBranch(EST.ExitBB); CGF.EmitBlock(EST.ExitBB); EST.ExitBB = nullptr; } // Create a unique global variable to indicate the execution mode of this target // region. The execution mode is either 'generic', or 'spmd' depending on the // target directive. This variable is picked up by the offload library to setup // the device appropriately before kernel launch. If the execution mode is // 'generic', the runtime reserves one warp for the master, otherwise, all // warps participate in parallel work. static void setPropertyExecutionMode(CodeGenModule &CGM, StringRef Name, CGOpenMPRuntimeNVPTX::ExecutionMode Mode) { (void)new llvm::GlobalVariable( CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, llvm::GlobalValue::WeakAnyLinkage, llvm::ConstantInt::get(CGM.Int8Ty, Mode), Name + Twine("_exec_mode")); } void CGOpenMPRuntimeNVPTX::emitWorkerFunction(WorkerFunctionState &WST) { auto &Ctx = CGM.getContext(); CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); CGF.disableDebugInfo(); CGF.StartFunction(GlobalDecl(), Ctx.VoidTy, WST.WorkerFn, *WST.CGFI, {}); emitWorkerLoop(CGF, WST); CGF.FinishFunction(); } void CGOpenMPRuntimeNVPTX::emitWorkerLoop(CodeGenFunction &CGF, WorkerFunctionState &WST) { // // The workers enter this loop and wait for parallel work from the master. // When the master encounters a parallel region it sets up the work + variable // arguments, and wakes up the workers. The workers first check to see if // they are required for the parallel region, i.e., within the # of requested // parallel threads. The activated workers load the variable arguments and // execute the parallel work. // CGBuilderTy &Bld = CGF.Builder; llvm::BasicBlock *AwaitBB = CGF.createBasicBlock(".await.work"); llvm::BasicBlock *SelectWorkersBB = CGF.createBasicBlock(".select.workers"); llvm::BasicBlock *ExecuteBB = CGF.createBasicBlock(".execute.parallel"); llvm::BasicBlock *TerminateBB = CGF.createBasicBlock(".terminate.parallel"); llvm::BasicBlock *BarrierBB = CGF.createBasicBlock(".barrier.parallel"); llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".exit"); CGF.EmitBranch(AwaitBB); // Workers wait for work from master. CGF.EmitBlock(AwaitBB); // Wait for parallel work syncCTAThreads(CGF); Address WorkFn = CGF.CreateDefaultAlignTempAlloca(CGF.Int8PtrTy, /*Name=*/"work_fn"); Address ExecStatus = CGF.CreateDefaultAlignTempAlloca(CGF.Int8Ty, /*Name=*/"exec_status"); CGF.InitTempAlloca(ExecStatus, Bld.getInt8(/*C=*/0)); CGF.InitTempAlloca(WorkFn, llvm::Constant::getNullValue(CGF.Int8PtrTy)); llvm::Value *Args[] = {WorkFn.getPointer()}; llvm::Value *Ret = CGF.EmitRuntimeCall( createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_parallel), Args); Bld.CreateStore(Bld.CreateZExt(Ret, CGF.Int8Ty), ExecStatus); // On termination condition (workid == 0), exit loop. llvm::Value *ShouldTerminate = Bld.CreateIsNull(Bld.CreateLoad(WorkFn), "should_terminate"); Bld.CreateCondBr(ShouldTerminate, ExitBB, SelectWorkersBB); // Activate requested workers. CGF.EmitBlock(SelectWorkersBB); llvm::Value *IsActive = Bld.CreateIsNotNull(Bld.CreateLoad(ExecStatus), "is_active"); Bld.CreateCondBr(IsActive, ExecuteBB, BarrierBB); // Signal start of parallel region. CGF.EmitBlock(ExecuteBB); // Process work items: outlined parallel functions. for (auto *W : Work) { // Try to match this outlined function. auto *ID = Bld.CreatePointerBitCastOrAddrSpaceCast(W, CGM.Int8PtrTy); llvm::Value *WorkFnMatch = Bld.CreateICmpEQ(Bld.CreateLoad(WorkFn), ID, "work_match"); llvm::BasicBlock *ExecuteFNBB = CGF.createBasicBlock(".execute.fn"); llvm::BasicBlock *CheckNextBB = CGF.createBasicBlock(".check.next"); Bld.CreateCondBr(WorkFnMatch, ExecuteFNBB, CheckNextBB); // Execute this outlined function. CGF.EmitBlock(ExecuteFNBB); // Insert call to work function. // FIXME: Pass arguments to outlined function from master thread. auto *Fn = cast<llvm::Function>(W); Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, /*Name=*/".zero.addr"); CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C=*/0)); llvm::Value *FnArgs[] = {ZeroAddr.getPointer(), ZeroAddr.getPointer()}; CGF.EmitCallOrInvoke(Fn, FnArgs); // Go to end of parallel region. CGF.EmitBranch(TerminateBB); CGF.EmitBlock(CheckNextBB); } // Signal end of parallel region. CGF.EmitBlock(TerminateBB); CGF.EmitRuntimeCall( createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_end_parallel), llvm::None); CGF.EmitBranch(BarrierBB); // All active and inactive workers wait at a barrier after parallel region. CGF.EmitBlock(BarrierBB); // Barrier after parallel region. syncCTAThreads(CGF); CGF.EmitBranch(AwaitBB); // Exit target region. CGF.EmitBlock(ExitBB); } /// \brief Returns specified OpenMP runtime function for the current OpenMP /// implementation. Specialized for the NVPTX device. /// \param Function OpenMP runtime function. /// \return Specified function. llvm::Constant * CGOpenMPRuntimeNVPTX::createNVPTXRuntimeFunction(unsigned Function) { llvm::Constant *RTLFn = nullptr; switch (static_cast<OpenMPRTLFunctionNVPTX>(Function)) { case OMPRTL_NVPTX__kmpc_kernel_init: { // Build void __kmpc_kernel_init(kmp_int32 thread_limit); llvm::Type *TypeParams[] = {CGM.Int32Ty}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_init"); break; } case OMPRTL_NVPTX__kmpc_kernel_deinit: { // Build void __kmpc_kernel_deinit(); llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_deinit"); break; } case OMPRTL_NVPTX__kmpc_spmd_kernel_init: { // Build void __kmpc_spmd_kernel_init(kmp_int32 thread_limit, // short RequiresOMPRuntime, short RequiresDataSharing); llvm::Type *TypeParams[] = {CGM.Int32Ty, CGM.Int16Ty, CGM.Int16Ty}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_init"); break; } case OMPRTL_NVPTX__kmpc_spmd_kernel_deinit: { // Build void __kmpc_spmd_kernel_deinit(); llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_spmd_kernel_deinit"); break; } case OMPRTL_NVPTX__kmpc_kernel_prepare_parallel: { /// Build void __kmpc_kernel_prepare_parallel( /// void *outlined_function); llvm::Type *TypeParams[] = {CGM.Int8PtrTy}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_prepare_parallel"); break; } case OMPRTL_NVPTX__kmpc_kernel_parallel: { /// Build bool __kmpc_kernel_parallel(void **outlined_function); llvm::Type *TypeParams[] = {CGM.Int8PtrPtrTy}; llvm::Type *RetTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy); llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, TypeParams, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_parallel"); break; } case OMPRTL_NVPTX__kmpc_kernel_end_parallel: { /// Build void __kmpc_kernel_end_parallel(); llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, llvm::None, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_kernel_end_parallel"); break; } case OMPRTL_NVPTX__kmpc_serialized_parallel: { // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 // global_tid); llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel"); break; } case OMPRTL_NVPTX__kmpc_end_serialized_parallel: { // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 // global_tid); llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel"); break; } } return RTLFn; } void CGOpenMPRuntimeNVPTX::createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t) { auto *F = dyn_cast<llvm::Function>(Addr); // TODO: Add support for global variables on the device after declare target // support. if (!F) return; llvm::Module *M = F->getParent(); llvm::LLVMContext &Ctx = M->getContext(); // Get "nvvm.annotations" metadata node llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations"); llvm::Metadata *MDVals[] = { llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, "kernel"), llvm::ConstantAsMetadata::get( llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), 1))}; // Append metadata to nvvm.annotations MD->addOperand(llvm::MDNode::get(Ctx, MDVals)); } void CGOpenMPRuntimeNVPTX::emitTargetOutlinedFunction( const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { if (!IsOffloadEntry) // Nothing to do. return; assert(!ParentName.empty() && "Invalid target region parent name!"); CGOpenMPRuntimeNVPTX::ExecutionMode Mode = getExecutionModeForDirective(CGM, D); switch (Mode) { case CGOpenMPRuntimeNVPTX::ExecutionMode::Generic: emitGenericKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen); break; case CGOpenMPRuntimeNVPTX::ExecutionMode::Spmd: emitSpmdKernel(D, ParentName, OutlinedFn, OutlinedFnID, IsOffloadEntry, CodeGen); break; case CGOpenMPRuntimeNVPTX::ExecutionMode::Unknown: llvm_unreachable( "Unknown programming model for OpenMP directive on NVPTX target."); } setPropertyExecutionMode(CGM, OutlinedFn->getName(), Mode); } CGOpenMPRuntimeNVPTX::CGOpenMPRuntimeNVPTX(CodeGenModule &CGM) : CGOpenMPRuntime(CGM), CurrentExecutionMode(ExecutionMode::Unknown) { if (!CGM.getLangOpts().OpenMPIsDevice) llvm_unreachable("OpenMP NVPTX can only handle device code."); } void CGOpenMPRuntimeNVPTX::emitProcBindClause(CodeGenFunction &CGF, OpenMPProcBindClauseKind ProcBind, SourceLocation Loc) { // Do nothing in case of Spmd mode and L0 parallel. // TODO: If in Spmd mode and L1 parallel emit the clause. if (isInSpmdExecutionMode()) return; CGOpenMPRuntime::emitProcBindClause(CGF, ProcBind, Loc); } void CGOpenMPRuntimeNVPTX::emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc) { // Do nothing in case of Spmd mode and L0 parallel. // TODO: If in Spmd mode and L1 parallel emit the clause. if (isInSpmdExecutionMode()) return; CGOpenMPRuntime::emitNumThreadsClause(CGF, NumThreads, Loc); } void CGOpenMPRuntimeNVPTX::emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc) {} llvm::Value *CGOpenMPRuntimeNVPTX::emitParallelOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { return CGOpenMPRuntime::emitParallelOutlinedFunction(D, ThreadIDVar, InnermostKind, CodeGen); } llvm::Value *CGOpenMPRuntimeNVPTX::emitTeamsOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { llvm::Value *OutlinedFunVal = CGOpenMPRuntime::emitTeamsOutlinedFunction( D, ThreadIDVar, InnermostKind, CodeGen); llvm::Function *OutlinedFun = cast<llvm::Function>(OutlinedFunVal); OutlinedFun->removeFnAttr(llvm::Attribute::NoInline); OutlinedFun->addFnAttr(llvm::Attribute::AlwaysInline); return OutlinedFun; } void CGOpenMPRuntimeNVPTX::emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Value *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars) { if (!CGF.HaveInsertPoint()) return; Address ZeroAddr = CGF.CreateTempAlloca(CGF.Int32Ty, CharUnits::fromQuantity(4), /*Name*/ ".zero.addr"); CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0)); llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; OutlinedFnArgs.push_back(ZeroAddr.getPointer()); OutlinedFnArgs.push_back(ZeroAddr.getPointer()); OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs); } void CGOpenMPRuntimeNVPTX::emitParallelCall( CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { if (!CGF.HaveInsertPoint()) return; if (isInSpmdExecutionMode()) emitSpmdParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond); else emitGenericParallelCall(CGF, Loc, OutlinedFn, CapturedVars, IfCond); } void CGOpenMPRuntimeNVPTX::emitGenericParallelCall( CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { llvm::Function *Fn = cast<llvm::Function>(OutlinedFn); auto &&L0ParallelGen = [this, Fn](CodeGenFunction &CGF, PrePostActionTy &) { CGBuilderTy &Bld = CGF.Builder; // Prepare for parallel region. Indicate the outlined function. llvm::Value *Args[] = {Bld.CreateBitOrPointerCast(Fn, CGM.Int8PtrTy)}; CGF.EmitRuntimeCall( createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_kernel_prepare_parallel), Args); // Activate workers. This barrier is used by the master to signal // work for the workers. syncCTAThreads(CGF); // OpenMP [2.5, Parallel Construct, p.49] // There is an implied barrier at the end of a parallel region. After the // end of a parallel region, only the master thread of the team resumes // execution of the enclosing task region. // // The master waits at this barrier until all workers are done. syncCTAThreads(CGF); // Remember for post-processing in worker loop. Work.push_back(Fn); }; auto *RTLoc = emitUpdateLocation(CGF, Loc); auto *ThreadID = getThreadID(CGF, Loc); llvm::Value *Args[] = {RTLoc, ThreadID}; auto &&SeqGen = [this, Fn, &CapturedVars, &Args](CodeGenFunction &CGF, PrePostActionTy &) { auto &&CodeGen = [this, Fn, &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &Action) { Action.Enter(CGF); llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; OutlinedFnArgs.push_back( llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); OutlinedFnArgs.push_back( llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); CGF.EmitCallOrInvoke(Fn, OutlinedFnArgs); }; RegionCodeGenTy RCG(CodeGen); NVPTXActionTy Action( createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_serialized_parallel), Args, createNVPTXRuntimeFunction(OMPRTL_NVPTX__kmpc_end_serialized_parallel), Args); RCG.setAction(Action); RCG(CGF); }; if (IfCond) emitOMPIfClause(CGF, IfCond, L0ParallelGen, SeqGen); else { CodeGenFunction::RunCleanupsScope Scope(CGF); RegionCodeGenTy ThenRCG(L0ParallelGen); ThenRCG(CGF); } } void CGOpenMPRuntimeNVPTX::emitSpmdParallelCall( CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) { // Just call the outlined function to execute the parallel region. // OutlinedFn(&GTid, &zero, CapturedStruct); // // TODO: Do something with IfCond when support for the 'if' clause // is added on Spmd target directives. llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; OutlinedFnArgs.push_back( llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); OutlinedFnArgs.push_back( llvm::ConstantPointerNull::get(CGM.Int32Ty->getPointerTo())); OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); CGF.EmitCallOrInvoke(OutlinedFn, OutlinedFnArgs); }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/nvptx_target_teams_codegen.cpp
222
// Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // RUN: %clang_cc1 -verify -fopenmp -fexceptions -fcxx-exceptions -x c++ -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // expected-no-diagnostics #ifndef HEADER #define HEADER // Check that the execution mode of all 2 target regions is set to Generic Mode. // CHECK-DAG: {{@__omp_offloading_.+l26}}_exec_mode = weak constant i8 1 // CHECK-DAG: {{@__omp_offloading_.+l31}}_exec_mode = weak constant i8 1 template<typename tx> tx ftemplate(int n) { tx a = 0; short aa = 0; tx b[10]; #pragma omp target teams if(0) { b[2] += 1; } #pragma omp target teams if(1) { a = '1'; } #pragma omp target teams if(n>40) { aa = 1; } return a; } int bar(int n){ int a = 0; a += ftemplate<char>(n); return a; } // CHECK-NOT: define {{.*}}void {{@__omp_offloading_.+template.+l21}}_worker() // CHECK-LABEL: define {{.*}}void {{@__omp_offloading_.+template.+l26}}_worker() // CHECK-DAG: [[OMP_EXEC_STATUS:%.+]] = alloca i8, // CHECK-DAG: [[OMP_WORK_FN:%.+]] = alloca i8*, // CHECK: store i8* null, i8** [[OMP_WORK_FN]], // CHECK: store i8 0, i8* [[OMP_EXEC_STATUS]], // CHECK: br label {{%?}}[[AWAIT_WORK:.+]] // // CHECK: [[AWAIT_WORK]] // CHECK: call void @llvm.nvvm.barrier0() // CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]]) // CHECK: [[KPRB:%.+]] = zext i1 [[KPR]] to i8 // store i8 [[KPRB]], i8* [[OMP_EXEC_STATUS]], align 1 // CHECK: [[WORK:%.+]] = load i8*, i8** [[OMP_WORK_FN]], // CHECK: [[SHOULD_EXIT:%.+]] = icmp eq i8* [[WORK]], null // CHECK: br i1 [[SHOULD_EXIT]], label {{%?}}[[EXIT:.+]], label {{%?}}[[SEL_WORKERS:.+]] // // CHECK: [[SEL_WORKERS]] // CHECK: [[ST:%.+]] = load i8, i8* [[OMP_EXEC_STATUS]] // CHECK: [[IS_ACTIVE:%.+]] = icmp ne i8 [[ST]], 0 // CHECK: br i1 [[IS_ACTIVE]], label {{%?}}[[EXEC_PARALLEL:.+]], label {{%?}}[[BAR_PARALLEL:.+]] // // CHECK: [[EXEC_PARALLEL]] // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]] // // CHECK: [[TERM_PARALLEL]] // CHECK: call void @__kmpc_kernel_end_parallel() // CHECK: br label {{%?}}[[BAR_PARALLEL]] // // CHECK: [[BAR_PARALLEL]] // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[AWAIT_WORK]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK: define {{.*}}void [[T1:@__omp_offloading_.+template.+l26]](i[[SZ:32|64]] [[A:%[^)]+]]) // CHECK: store i[[SZ]] [[A]], i[[SZ]]* [[A_ADDR:%.+]], align // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[A_ADDR]] to i8* // CHECK-DAG: [[TID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK-DAG: [[NTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[WS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK-DAG: [[TH_LIMIT:%.+]] = sub i32 [[NTH]], [[WS]] // CHECK: [[IS_WORKER:%.+]] = icmp ult i32 [[TID]], [[TH_LIMIT]] // CHECK: br i1 [[IS_WORKER]], label {{%?}}[[WORKER:.+]], label {{%?}}[[CHECK_MASTER:.+]] // // CHECK: [[WORKER]] // CHECK: {{call|invoke}} void [[T1]]_worker() // CHECK: br label {{%?}}[[EXIT:.+]] // // CHECK: [[CHECK_MASTER]] // CHECK-DAG: [[CMTID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK-DAG: [[CMNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[CMWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK: [[IS_MASTER:%.+]] = icmp eq i32 [[CMTID]], // CHECK: br i1 [[IS_MASTER]], label {{%?}}[[MASTER:.+]], label {{%?}}[[EXIT]] // // CHECK: [[MASTER]] // CHECK-DAG: [[MNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[MWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK: [[MTMP1:%.+]] = sub i32 [[MNTH]], [[MWS]] // CHECK: call void @__kmpc_kernel_init(i32 [[MTMP1]] // // CHECK-NOT: kmpc_fork_teams // CHECK: [[A_VAL:%.+]] = load i8, i8* [[CONV]], align // CHECK: [[ACP:%.+]] = bitcast i[[SZ]]* [[AC:%.+]] to i8* // CHECK: store i8 [[A_VAL]], i8* [[ACP]], align // CHECK: [[ACV:%.+]] = load i[[SZ]], i[[SZ]]* [[AC]], align // CHECK: store i[[SZ]] [[ACV]], i[[SZ]]* [[A_ADDR_T:%.+]], align // CHECK: [[CONV2:%.+]] = bitcast i[[SZ]]* [[A_ADDR_T]] to i8* // CHECK: store i8 49, i8* [[CONV2]], align // CHECK: br label {{%?}}[[TERMINATE:.+]] // // CHECK: [[TERMINATE]] // CHECK: call void @__kmpc_kernel_deinit() // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[EXIT]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK-LABEL: define {{.*}}void {{@__omp_offloading_.+template.+l31}}_worker() // CHECK-DAG: [[OMP_EXEC_STATUS:%.+]] = alloca i8, // CHECK-DAG: [[OMP_WORK_FN:%.+]] = alloca i8*, // CHECK: store i8* null, i8** [[OMP_WORK_FN]], // CHECK: store i8 0, i8* [[OMP_EXEC_STATUS]], // CHECK: br label {{%?}}[[AWAIT_WORK:.+]] // // CHECK: [[AWAIT_WORK]] // CHECK: call void @llvm.nvvm.barrier0() // CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]]) // CHECK: [[KPRB:%.+]] = zext i1 [[KPR]] to i8 // store i8 [[KPRB]], i8* [[OMP_EXEC_STATUS]], align 1 // CHECK: [[WORK:%.+]] = load i8*, i8** [[OMP_WORK_FN]], // CHECK: [[SHOULD_EXIT:%.+]] = icmp eq i8* [[WORK]], null // CHECK: br i1 [[SHOULD_EXIT]], label {{%?}}[[EXIT:.+]], label {{%?}}[[SEL_WORKERS:.+]] // // CHECK: [[SEL_WORKERS]] // CHECK: [[ST:%.+]] = load i8, i8* [[OMP_EXEC_STATUS]] // CHECK: [[IS_ACTIVE:%.+]] = icmp ne i8 [[ST]], 0 // CHECK: br i1 [[IS_ACTIVE]], label {{%?}}[[EXEC_PARALLEL:.+]], label {{%?}}[[BAR_PARALLEL:.+]] // // CHECK: [[EXEC_PARALLEL]] // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]] // // CHECK: [[TERM_PARALLEL]] // CHECK: call void @__kmpc_kernel_end_parallel() // CHECK: br label {{%?}}[[BAR_PARALLEL]] // // CHECK: [[BAR_PARALLEL]] // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[AWAIT_WORK]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK: define {{.*}}void [[T2:@__omp_offloading_.+template.+l31]](i[[SZ:32|64]] [[AA:%[^)]+]]) // CHECK: store i[[SZ]] [[AA]], i[[SZ]]* [[AA_ADDR:%.+]], align // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[AA_ADDR]] to i16* // CHECK-DAG: [[TID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK-DAG: [[NTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[WS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK-DAG: [[TH_LIMIT:%.+]] = sub i32 [[NTH]], [[WS]] // CHECK: [[IS_WORKER:%.+]] = icmp ult i32 [[TID]], [[TH_LIMIT]] // CHECK: br i1 [[IS_WORKER]], label {{%?}}[[WORKER:.+]], label {{%?}}[[CHECK_MASTER:.+]] // // CHECK: [[WORKER]] // CHECK: {{call|invoke}} void [[T2]]_worker() // CHECK: br label {{%?}}[[EXIT:.+]] // // CHECK: [[CHECK_MASTER]] // CHECK-DAG: [[CMTID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK-DAG: [[CMNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[CMWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK: [[IS_MASTER:%.+]] = icmp eq i32 [[CMTID]], // CHECK: br i1 [[IS_MASTER]], label {{%?}}[[MASTER:.+]], label {{%?}}[[EXIT]] // // CHECK: [[MASTER]] // CHECK-DAG: [[MNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[MWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK: [[MTMP1:%.+]] = sub i32 [[MNTH]], [[MWS]] // CHECK: call void @__kmpc_kernel_init(i32 [[MTMP1]] // // CHECK-NOT: kmpc_fork_teams // CHECK: [[AA_VAL:%.+]] = load i16, i16* [[CONV]], align // CHECK: [[ACP:%.+]] = bitcast i[[SZ]]* [[AC:%.+]] to i16* // CHECK: store i16 [[AA_VAL]], i16* [[ACP]], align // CHECK: [[ACV:%.+]] = load i[[SZ]], i[[SZ]]* [[AC]], align // CHECK: store i[[SZ]] [[ACV]], i[[SZ]]* [[AA_ADDR_T:%.+]], align // CHECK: [[CONV2:%.+]] = bitcast i[[SZ]]* [[AA_ADDR_T]] to i16* // CHECK: store i16 1, i16* [[CONV2]], align // CHECK: br label {{%?}}[[TERMINATE:.+]] // // CHECK: [[TERMINATE]] // CHECK: call void @__kmpc_kernel_deinit() // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[EXIT]] // // CHECK: [[EXIT]] // CHECK: ret void #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_simd_is_device_ptr_ast_print.cpp
318
// RUN: %clang_cc1 -verify -fopenmp -std=c++11 -ast-print %s | FileCheck %s // RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -std=c++11 -include-pch %t -fsyntax-only -verify %s -ast-print | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER struct ST { int *a; }; typedef int arr[10]; typedef ST STarr[10]; struct SA { const int da[5] = { 0 }; ST g[10]; STarr &rg = g; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; arr &raa = aa; void func(int arg) { #pragma omp target teams distribute simd is_device_ptr(k) for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(z) for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(aa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(raa) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(g) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(rg) // OK for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(da) // OK for (int i=0; i<100; i++) ; return; } }; // CHECK: struct SA // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: ST g[10]; // CHECK-NEXT: STarr &rg = this->g; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = this->i; // CHECK-NEXT: int *k = &this->j; // CHECK-NEXT: int *&z = this->k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: arr &raa = this->aa; // CHECK-NEXT: func( // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(this->k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(this->z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(this->aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(this->raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(this->g) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(this->rg) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(this->da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; struct SB { unsigned A; unsigned B; float Arr[100]; float *Ptr; float *foo() { return &Arr[0]; } }; struct SC { unsigned A : 2; unsigned B : 3; unsigned C; unsigned D; float Arr[100]; SB S; SB ArrS[100]; SB *PtrS; SB *&RPtrS; float *Ptr; SC(SB *&_RPtrS) : RPtrS(_RPtrS) {} }; union SD { unsigned A; float B; }; struct S1; extern S1 a; class S2 { mutable int a; public: S2():a(0) { } S2(S2 &s2):a(s2.a) { } static float S2s; static const float S2sc; }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3():a(0) { } S3(S3 &s3):a(s3.a) { } }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} S5(const S5 &s5):a(s5.a) { } public: S5(int v):a(v) { } }; S3 h; #pragma omp threadprivate(h) typedef struct { int a; } S6; template <typename T> T tmain(T argc) { const T da[5] = { 0 }; S6 h[10]; auto &rh = h; T i; T &j = i; T *k = &j; T *&z = k; T aa[10]; auto &raa = aa; #pragma omp target teams distribute simd is_device_ptr(k) for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(z) for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(aa) for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(raa) for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(h) for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(rh) for (int i=0; i<100; i++) ; #pragma omp target teams distribute simd is_device_ptr(da) for (int i=0; i<100; i++) ; return 0; } // CHECK: template<> int tmain<int>(int argc) { // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK: template<> int *tmain<int *>(int *argc) { // CHECK-NEXT: int *const da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int *i; // CHECK-NEXT: int *&j = i; // CHECK-NEXT: int **k = &j; // CHECK-NEXT: int **&z = k; // CHECK-NEXT: int *aa[10]; // CHECK-NEXT: auto &raa = aa; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(k) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(z) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(aa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(raa) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(h) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(rh) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(da) // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; // CHECK-LABEL: int main(int argc, char **argv) { int main(int argc, char **argv) { const int da[5] = { 0 }; S6 h[10]; auto &rh = h; int i; int &j = i; int *k = &j; int *&z = k; int aa[10]; auto &raa = aa; // CHECK-NEXT: const int da[5] = {0}; // CHECK-NEXT: S6 h[10]; // CHECK-NEXT: auto &rh = h; // CHECK-NEXT: int i; // CHECK-NEXT: int &j = i; // CHECK-NEXT: int *k = &j; // CHECK-NEXT: int *&z = k; // CHECK-NEXT: int aa[10]; // CHECK-NEXT: auto &raa = aa; #pragma omp target teams distribute simd is_device_ptr(k) // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(k) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute simd is_device_ptr(z) // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(z) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute simd is_device_ptr(aa) // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(aa) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute simd is_device_ptr(raa) // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(raa) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute simd is_device_ptr(h) // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(h) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute simd is_device_ptr(rh) // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(rh) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; #pragma omp target teams distribute simd is_device_ptr(da) // CHECK-NEXT: #pragma omp target teams distribute simd is_device_ptr(da) for (int i=0; i<100; i++) ; // CHECK-NEXT: for (int i = 0; i < 100; i++) // CHECK-NEXT: ; return tmain<int>(argc) + *tmain<int *>(&argc); } #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_parallel_for_simd_loop_messages.cpp
627
// RUN: %clang_cc1 -fsyntax-only -fopenmp -x c++ -std=c++11 -fexceptions -fcxx-exceptions -verify %s class S { int a; S() : a(0) {} public: S(int v) : a(v) {} S(const S &s) : a(s.a) {} }; static int sii; // expected-note@+1 {{defined as threadprivate or thread local}} #pragma omp threadprivate(sii) static int globalii; int test_iteration_spaces() { const int N = 100; float a[N], b[N], c[N]; int ii, jj, kk; float fii; double dii; #pragma omp target teams distribute parallel for simd for (int i = 0; i < 10; i += 1) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute parallel for simd for (char i = 0; i < 10; i++) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute parallel for simd for (char i = 0; i < 10; i += '\1') { c[i] = a[i] + b[i]; } #pragma omp target teams distribute parallel for simd for (long long i = 0; i < 10; i++) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute parallel for simd // expected-error@+1 {{expression must have integral or unscoped enumeration type, not 'double'}} for (long long i = 0; i < 10; i += 1.5) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute parallel for simd for (long long i = 0; i < 'z'; i += 1u) { c[i] = a[i] + b[i]; } #pragma omp target teams distribute parallel for simd // expected-error@+1 {{variable must be of integer or random access iterator type}} for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } #pragma omp target teams distribute parallel for simd // expected-error@+1 {{variable must be of integer or random access iterator type}} for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } #pragma omp target teams distribute parallel for simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (int &ref = ii; ref < 10; ref++) { } #pragma omp target teams distribute parallel for simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (int i; i < 10; i++) c[i] = a[i]; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (int i = 0, j = 0; i < 10; ++i) c[i] = a[i]; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute parallel for simd // expected-warning@+2 {{expression result unused}} // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (ii + 1; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (c[ii] = 0; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute parallel for simd // Ok to skip parenthesises. for (((ii)) = 0; ii < 10; ++ii) c[ii] = a[ii]; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} for (int i = 0; i; i++) c[i] = a[i]; #pragma omp target teams distribute parallel for simd // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'i'}} for (int i = 0; jj < kk; ii++) c[i] = a[i]; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} for (int i = 0; !!i; i++) c[i] = a[i]; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} for (int i = 0; i != 1; i++) c[i] = a[i]; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} for (int i = 0;; i++) c[i] = a[i]; // Ok. #pragma omp target teams distribute parallel for simd for (int i = 11; i > 10; i--) c[i] = a[i]; // Ok. #pragma omp target teams distribute parallel for simd for (int i = 0; i < 10; ++i) c[i] = a[i]; // Ok. #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ++ii) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ++jj) c[ii] = a[jj]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ++++ii) c[ii] = a[ii]; // Ok but undefined behavior (in general, cannot check that incr // is really loop-invariant). #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ii = ii + ii) c[ii] = a[ii]; // expected-error@+2 {{expression must have integral or unscoped enumeration type, not 'float'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ii = ii + 1.0f) c[ii] = a[ii]; // Ok - step was converted to integer type. #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ii = ii + (int)1.1f) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; jj = ii + 2) c[ii] = a[ii]; // expected-warning@+3 {{relational comparison result unused}} // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii<10; jj> kk + 2) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10;) c[ii] = a[ii]; // expected-warning@+3 {{expression result unused}} // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; !ii) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ii ? ++ii : ++jj) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ii = ii < 10) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ii = ii + 0) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; ii = ii + (int)(0.8 - 0.45)) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for (ii = 0; (ii) < 10; ii -= 25) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for (ii = 0; (ii < 10); ii -= 0) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be negative due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to decrease on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii > 10; (ii += 0)) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for (ii = 0; ii < 10; (ii) = (1 - 1) + (ii)) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be negative due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to decrease on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for ((ii = 0); ii > 10; (ii -= 0)) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for (ii = 0; (ii < 10); (ii -= 0)) c[ii] = a[ii]; // expected-error@+3 {{loop iteration variable in the associated loop of 'omp target teams distribute parallel for simd' directive may not be firstprivate, predetermined as linear}} // expected-note@+1 {{defined as firstprivate}} #pragma omp target teams distribute parallel for simd firstprivate(ii) for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; // expected-error@+2 {{loop iteration variable in the associated loop of 'omp target teams distribute parallel for simd' directive may not be private, predetermined as linear}} #pragma omp target teams distribute parallel for simd private(ii) // expected-note {{defined as private}} for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; // expected-error@+2 {{loop iteration variable in the associated loop of 'omp target teams distribute parallel for simd' directive may not be lastprivate, predetermined as linear}} #pragma omp target teams distribute parallel for simd lastprivate(ii) // expected-note {{defined as lastprivate}} for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; // expected-error@+2 {{loop iteration variable in the associated loop of 'omp target teams distribute parallel for simd' directive may not be threadprivate or thread local, predetermined as linear}} #pragma omp target teams distribute parallel for simd for (sii = 0; sii < 10; sii++) c[sii] = a[sii]; { #pragma omp target teams distribute parallel for simd collapse(2) for (ii = 0; ii < 10; ii += 1) for (globalii = 0; globalii < 10; globalii += 1) c[globalii] += a[globalii] + ii; } // expected-error@+2 {{statement after '#pragma omp target teams distribute parallel for simd' must be a for loop}} #pragma omp target teams distribute parallel for simd for (auto &item : a) { item = item + 1; } // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'i' to increase on each iteration of OpenMP for loop}} #pragma omp target teams distribute parallel for simd for (unsigned i = 9; i < 10; i--) { c[i] = a[i] + b[i]; } int(*lb)[4] = nullptr; #pragma omp target teams distribute parallel for simd for (int(*p)[4] = lb; p < lb + 8; ++p) { } // expected-warning@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp target teams distribute parallel for simd for (int a{0}; a < 10; ++a) { } return 0; } // Iterators allowed in openmp for-loops. namespace std { struct random_access_iterator_tag {}; template <class Iter> struct iterator_traits { typedef typename Iter::difference_type difference_type; typedef typename Iter::iterator_category iterator_category; }; template <class Iter> typename iterator_traits<Iter>::difference_type distance(Iter first, Iter last) { return first - last; } } class Iter0 { public: Iter0() {} Iter0(const Iter0 &) {} Iter0 operator++() { return *this; } Iter0 operator--() { return *this; } bool operator<(Iter0 a) { return true; } }; // expected-note@+2 {{candidate function not viable: no known conversion from 'GoodIter' to 'Iter0' for 1st argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'Iter0' for 1st argument}} int operator-(Iter0 a, Iter0 b) { return 0; } class Iter1 { public: Iter1(float f = 0.0f, double d = 0.0) {} Iter1(const Iter1 &) {} Iter1 operator++() { return *this; } Iter1 operator--() { return *this; } bool operator<(Iter1 a) { return true; } bool operator>=(Iter1 a) { return false; } }; class GoodIter { public: GoodIter() {} GoodIter(const GoodIter &) {} GoodIter(int fst, int snd) {} GoodIter &operator=(const GoodIter &that) { return *this; } GoodIter &operator=(const Iter0 &that) { return *this; } GoodIter &operator+=(int x) { return *this; } explicit GoodIter(void *) {} GoodIter operator++() { return *this; } GoodIter operator--() { return *this; } bool operator!() { return true; } bool operator<(GoodIter a) { return true; } bool operator<=(GoodIter a) { return true; } bool operator>=(GoodIter a) { return false; } typedef int difference_type; typedef std::random_access_iterator_tag iterator_category; }; // expected-note@+2 {{candidate function not viable: no known conversion from 'const Iter0' to 'GoodIter' for 2nd argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'GoodIter' for 1st argument}} int operator-(GoodIter a, GoodIter b) { return 0; } // expected-note@+1 3 {{candidate function not viable: requires single argument 'a', but 2 arguments were provided}} GoodIter operator-(GoodIter a) { return a; } // expected-note@+2 {{candidate function not viable: no known conversion from 'const Iter0' to 'int' for 2nd argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'GoodIter' for 1st argument}} GoodIter operator-(GoodIter a, int v) { return GoodIter(); } // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter0' to 'GoodIter' for 1st argument}} GoodIter operator+(GoodIter a, int v) { return GoodIter(); } // expected-note@+2 {{candidate function not viable: no known conversion from 'GoodIter' to 'int' for 1st argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'int' for 1st argument}} GoodIter operator-(int v, GoodIter a) { return GoodIter(); } // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter0' to 'int' for 1st argument}} GoodIter operator+(int v, GoodIter a) { return GoodIter(); } int test_with_random_access_iterator() { GoodIter begin, end; Iter0 begin0, end0; #pragma omp target teams distribute parallel for simd for (GoodIter I = begin; I < end; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter &I = begin; I < end; ++I) ++I; #pragma omp target teams distribute parallel for simd for (GoodIter I = begin; I >= end; --I) ++I; #pragma omp target teams distribute parallel for simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter I(begin); I < end; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter I(nullptr); I < end; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter I(0); I < end; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (GoodIter I(1, 2); I < end; ++I) ++I; #pragma omp target teams distribute parallel for simd for (begin = GoodIter(0); begin < end; ++begin) ++begin; #pragma omp target teams distribute parallel for simd // expected-error@+2 {{invalid operands to binary expression ('GoodIter' and 'const Iter0')}} // expected-error@+1 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} for (begin = begin0; begin < end; ++begin) ++begin; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (++begin; begin < end; ++begin) ++begin; #pragma omp target teams distribute parallel for simd for (begin = end; begin < end; ++begin) ++begin; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} for (GoodIter I = begin; I - I; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} for (GoodIter I = begin; begin < end; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} for (GoodIter I = begin; !I; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (GoodIter I = begin; I >= end; I = I + 1) ++I; #pragma omp target teams distribute parallel for simd for (GoodIter I = begin; I >= end; I = I - 1) ++I; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'I'}} for (GoodIter I = begin; I >= end; I = -I) ++I; #pragma omp target teams distribute parallel for simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (GoodIter I = begin; I >= end; I = 2 + I) ++I; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'I'}} for (GoodIter I = begin; I >= end; I = 2 - I) ++I; #pragma omp target teams distribute parallel for simd // expected-error@+1 {{invalid operands to binary expression ('Iter0' and 'int')}} for (Iter0 I = begin0; I < end0; ++I) ++I; #pragma omp target teams distribute parallel for simd // Initializer is constructor without params. // expected-error@+2 {{invalid operands to binary expression ('Iter0' and 'int')}} // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (Iter0 I; I < end0; ++I) ++I; Iter1 begin1, end1; #pragma omp target teams distribute parallel for simd // expected-error@+2 {{invalid operands to binary expression ('Iter1' and 'Iter1')}} // expected-error@+1 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} for (Iter1 I = begin1; I < end1; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (Iter1 I = begin1; I >= end1; ++I) ++I; #pragma omp target teams distribute parallel for simd // expected-error@+4 {{invalid operands to binary expression ('Iter1' and 'float')}} // expected-error@+3 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} // Initializer is constructor with all default params. // expected-warning@+1 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} for (Iter1 I; I < end1; ++I) { } return 0; } template <typename IT, int ST> class TC { public: int dotest_lt(IT begin, IT end) { #pragma omp target teams distribute parallel for simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to increase on each iteration of OpenMP for loop}} for (IT I = begin; I < end; I = I + ST) { ++I; } #pragma omp target teams distribute parallel for simd // expected-note@+2 {{loop step is expected to be positive due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to increase on each iteration of OpenMP for loop}} for (IT I = begin; I <= end; I += ST) { ++I; } #pragma omp target teams distribute parallel for simd for (IT I = begin; I < end; ++I) { ++I; } } static IT step() { return IT(ST); } }; template <typename IT, int ST = 0> int dotest_gt(IT begin, IT end) { #pragma omp target teams distribute parallel for simd // expected-note@+2 2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (IT I = begin; I >= end; I = I + ST) { ++I; } #pragma omp target teams distribute parallel for simd // expected-note@+2 2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (IT I = begin; I >= end; I += ST) { ++I; } #pragma omp target teams distribute parallel for simd // expected-note@+2 {{loop step is expected to be negative due to this condition}} // expected-error@+1 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} for (IT I = begin; I >= end; ++I) { ++I; } #pragma omp target teams distribute parallel for simd for (IT I = begin; I < end; I += TC<int, ST>::step()) { ++I; } } void test_with_template() { GoodIter begin, end; TC<GoodIter, 100> t1; TC<GoodIter, -100> t2; t1.dotest_lt(begin, end); t2.dotest_lt(begin, end); // expected-note {{in instantiation of member function 'TC<GoodIter, -100>::dotest_lt' requested here}} dotest_gt(begin, end); // expected-note {{in instantiation of function template specialization 'dotest_gt<GoodIter, 0>' requested here}} dotest_gt<unsigned, -10>(0, 100); // expected-note {{in instantiation of function template specialization 'dotest_gt<unsigned int, -10>' requested here}} } void test_loop_break() { const int N = 100; float a[N], b[N], c[N]; #pragma omp target teams distribute parallel for simd for (int i = 0; i < 10; i++) { c[i] = a[i] + b[i]; for (int j = 0; j < 10; ++j) { if (a[i] > b[j]) break; // OK in nested loop } switch (i) { case 1: b[i]++; break; default: break; } if (c[i] > 10) break; // expected-error {{'break' statement cannot be used in OpenMP for loop}} if (c[i] > 11) break; // expected-error {{'break' statement cannot be used in OpenMP for loop}} } #pragma omp target teams distribute parallel for simd for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { c[i] = a[i] + b[i]; if (c[i] > 10) { if (c[i] < 20) { break; // OK } } } } } void test_loop_eh() { const int N = 100; float a[N], b[N], c[N]; #pragma omp target teams distribute parallel for simd for (int i = 0; i < 10; i++) { c[i] = a[i] + b[i]; try { // expected-error {{'try' statement cannot be used in OpenMP simd region}} for (int j = 0; j < 10; ++j) { if (a[i] > b[j]) throw a[i]; // expected-error {{'throw' statement cannot be used in OpenMP simd region}} } throw a[i]; // expected-error {{'throw' statement cannot be used in OpenMP simd region}} } catch (float f) { if (f > 0.1) throw a[i]; // expected-error {{'throw' statement cannot be used in OpenMP simd region}} return; // expected-error {{cannot return from OpenMP region}} } switch (i) { case 1: b[i]++; break; default: break; } for (int j = 0; j < 10; j++) { if (c[i] > 10) throw c[i]; // expected-error {{'throw' statement cannot be used in OpenMP simd region}} } } if (c[9] > 10) throw c[9]; // OK #pragma omp target teams distribute parallel for simd for (int i = 0; i < 10; ++i) { struct S { void g() { throw 0; } }; } } void test_loop_firstprivate_lastprivate() { S s(4); #pragma omp target teams distribute parallel for simd lastprivate(s) firstprivate(s) for (int i = 0; i < 16; ++i) ; } void test_ordered() { #pragma omp target teams distribute parallel for simd ordered // expected-error {{unexpected OpenMP clause 'ordered' in directive '#pragma omp target teams distribute parallel for simd'}} for (int i = 0; i < 16; ++i) ; } void test_nowait() { #pragma omp target teams distribute parallel for simd nowait nowait // expected-error {{directive '#pragma omp target teams distribute parallel for simd' cannot contain more than one 'nowait' clause}} for (int i = 0; i < 16; ++i) ; }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
lib/Format/BreakableToken.cpp
520
//===--- BreakableToken.cpp - Format C++ code -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Contains implementation of BreakableToken class and classes derived /// from it. /// //===----------------------------------------------------------------------===// #include "BreakableToken.h" #include "ContinuationIndenter.h" #include "clang/Basic/CharInfo.h" #include "clang/Format/Format.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include <algorithm> #define DEBUG_TYPE "format-token-breaker" namespace clang { namespace format { static const char *const Blanks = " \t\v\f\r"; static bool IsBlank(char C) { switch (C) { case ' ': case '\t': case '\v': case '\f': case '\r': return true; default: return false; } } static StringRef getLineCommentIndentPrefix(StringRef Comment) { static const char *const KnownPrefixes[] = {"///", "//", "//!"}; StringRef LongestPrefix; for (StringRef KnownPrefix : KnownPrefixes) { if (Comment.startswith(KnownPrefix)) { size_t PrefixLength = KnownPrefix.size(); while (PrefixLength < Comment.size() && Comment[PrefixLength] == ' ') ++PrefixLength; if (PrefixLength > LongestPrefix.size()) LongestPrefix = Comment.substr(0, PrefixLength); } } return LongestPrefix; } static BreakableToken::Split getCommentSplit(StringRef Text, unsigned ContentStartColumn, unsigned ColumnLimit, unsigned TabWidth, encoding::Encoding Encoding) { if (ColumnLimit <= ContentStartColumn + 1) return BreakableToken::Split(StringRef::npos, 0); unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1; unsigned MaxSplitBytes = 0; for (unsigned NumChars = 0; NumChars < MaxSplit && MaxSplitBytes < Text.size();) { unsigned BytesInChar = encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding); NumChars += encoding::columnWidthWithTabs(Text.substr(MaxSplitBytes, BytesInChar), ContentStartColumn, TabWidth, Encoding); MaxSplitBytes += BytesInChar; } StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes); if (SpaceOffset == StringRef::npos || // Don't break at leading whitespace. Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) { // Make sure that we don't break at leading whitespace that // reaches past MaxSplit. StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks); if (FirstNonWhitespace == StringRef::npos) // If the comment is only whitespace, we cannot split. return BreakableToken::Split(StringRef::npos, 0); SpaceOffset = Text.find_first_of( Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace)); } if (SpaceOffset != StringRef::npos && SpaceOffset != 0) { StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks); StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks); return BreakableToken::Split(BeforeCut.size(), AfterCut.begin() - BeforeCut.end()); } return BreakableToken::Split(StringRef::npos, 0); } static BreakableToken::Split getStringSplit(StringRef Text, unsigned UsedColumns, unsigned ColumnLimit, unsigned TabWidth, encoding::Encoding Encoding) { // FIXME: Reduce unit test case. if (Text.empty()) return BreakableToken::Split(StringRef::npos, 0); if (ColumnLimit <= UsedColumns) return BreakableToken::Split(StringRef::npos, 0); unsigned MaxSplit = ColumnLimit - UsedColumns; StringRef::size_type SpaceOffset = 0; StringRef::size_type SlashOffset = 0; StringRef::size_type WordStartOffset = 0; StringRef::size_type SplitPoint = 0; for (unsigned Chars = 0;;) { unsigned Advance; if (Text[0] == '\\') { Advance = encoding::getEscapeSequenceLength(Text); Chars += Advance; } else { Advance = encoding::getCodePointNumBytes(Text[0], Encoding); Chars += encoding::columnWidthWithTabs( Text.substr(0, Advance), UsedColumns + Chars, TabWidth, Encoding); } if (Chars > MaxSplit || Text.size() <= Advance) break; if (IsBlank(Text[0])) SpaceOffset = SplitPoint; if (Text[0] == '/') SlashOffset = SplitPoint; if (Advance == 1 && !isAlphanumeric(Text[0])) WordStartOffset = SplitPoint; SplitPoint += Advance; Text = Text.substr(Advance); } if (SpaceOffset != 0) return BreakableToken::Split(SpaceOffset + 1, 0); if (SlashOffset != 0) return BreakableToken::Split(SlashOffset + 1, 0); if (WordStartOffset != 0) return BreakableToken::Split(WordStartOffset + 1, 0); if (SplitPoint != 0) return BreakableToken::Split(SplitPoint, 0); return BreakableToken::Split(StringRef::npos, 0); } bool switchesFormatting(const FormatToken &Token) { assert((Token.is(TT_BlockComment) || Token.is(TT_LineComment)) && "formatting regions are switched by comment tokens"); StringRef Content = Token.TokenText.substr(2).ltrim(); return Content.startswith("clang-format on") || Content.startswith("clang-format off"); } unsigned BreakableToken::getLineLengthAfterCompression(unsigned RemainingTokenColumns, Split Split) const { // Example: consider the content // lala lala // - RemainingTokenColumns is the original number of columns, 10; // - Split is (4, 2), denoting the two spaces between the two words; // // We compute the number of columns when the split is compressed into a single // space, like: // lala lala return RemainingTokenColumns + 1 - Split.second; } unsigned BreakableSingleLineToken::getLineCount() const { return 1; } unsigned BreakableSingleLineToken::getLineLengthAfterSplit( unsigned LineIndex, unsigned TailOffset, StringRef::size_type Length) const { return StartColumn + Prefix.size() + Postfix.size() + encoding::columnWidthWithTabs(Line.substr(TailOffset, Length), StartColumn + Prefix.size(), Style.TabWidth, Encoding); } BreakableSingleLineToken::BreakableSingleLineToken( const FormatToken &Tok, unsigned IndentLevel, unsigned StartColumn, StringRef Prefix, StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style) : BreakableToken(Tok, IndentLevel, InPPDirective, Encoding, Style), StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix) { assert(Tok.TokenText.endswith(Postfix)); Line = Tok.TokenText.substr( Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size()); } BreakableStringLiteral::BreakableStringLiteral( const FormatToken &Tok, unsigned IndentLevel, unsigned StartColumn, StringRef Prefix, StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style) : BreakableSingleLineToken(Tok, IndentLevel, StartColumn, Prefix, Postfix, InPPDirective, Encoding, Style) {} BreakableToken::Split BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit) const { return getStringSplit(Line.substr(TailOffset), StartColumn + Prefix.size() + Postfix.size(), ColumnLimit, Style.TabWidth, Encoding); } void BreakableStringLiteral::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { unsigned LeadingSpaces = StartColumn; // The '@' of an ObjC string literal (@"Test") does not become part of the // string token. // FIXME: It might be a cleaner solution to merge the tokens as a // precomputation step. if (Prefix.startswith("@")) --LeadingSpaces; Whitespaces.replaceWhitespaceInToken( Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix, Prefix, InPPDirective, 1, IndentLevel, LeadingSpaces); } BreakableComment::BreakableComment(const FormatToken &Token, unsigned IndentLevel, unsigned StartColumn, unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style) : BreakableToken(Token, IndentLevel, InPPDirective, Encoding, Style), StartColumn(StartColumn), OriginalStartColumn(OriginalStartColumn), FirstInLine(FirstInLine) {} unsigned BreakableComment::getLineCount() const { return Lines.size(); } BreakableToken::Split BreakableComment::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit) const { return getCommentSplit(Content[LineIndex].substr(TailOffset), getContentStartColumn(LineIndex, TailOffset), ColumnLimit, Style.TabWidth, Encoding); } void BreakableComment::compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { StringRef Text = Content[LineIndex].substr(TailOffset); // Text is relative to the content line, but Whitespaces operates relative to // the start of the corresponding token, so compute the start of the Split // that needs to be compressed into a single space relative to the start of // its token. unsigned BreakOffsetInToken = Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; unsigned CharsToRemove = Split.second; Whitespaces.replaceWhitespaceInToken( tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", "", /*InPPDirective=*/false, /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1); } BreakableToken::Split BreakableComment::getReflowSplit(StringRef Text, StringRef ReflowPrefix, unsigned PreviousEndColumn, unsigned ColumnLimit) const { unsigned ReflowStartColumn = PreviousEndColumn + ReflowPrefix.size(); StringRef TrimmedText = Text.rtrim(Blanks); // This is the width of the resulting line in case the full line of Text gets // reflown up starting at ReflowStartColumn. unsigned FullWidth = ReflowStartColumn + encoding::columnWidthWithTabs( TrimmedText, ReflowStartColumn, Style.TabWidth, Encoding); // If the full line fits up, we return a reflow split after it, // otherwise we compute the largest piece of text that fits after // ReflowStartColumn. Split ReflowSplit = FullWidth <= ColumnLimit ? Split(TrimmedText.size(), Text.size() - TrimmedText.size()) : getCommentSplit(Text, ReflowStartColumn, ColumnLimit, Style.TabWidth, Encoding); // We need to be extra careful here, because while it's OK to keep a long line // if it can't be broken into smaller pieces (like when the first word of a // long line is longer than the column limit), it's not OK to reflow that long // word up. So we recompute the size of the previous line after reflowing and // only return the reflow split if that's under the line limit. if (ReflowSplit.first != StringRef::npos && // Check if the width of the newly reflown line is under the limit. PreviousEndColumn + ReflowPrefix.size() + encoding::columnWidthWithTabs(Text.substr(0, ReflowSplit.first), PreviousEndColumn + ReflowPrefix.size(), Style.TabWidth, Encoding) <= ColumnLimit) { return ReflowSplit; } return Split(StringRef::npos, 0); } const FormatToken &BreakableComment::tokenAt(unsigned LineIndex) const { return Tokens[LineIndex] ? *Tokens[LineIndex] : Tok; } static bool mayReflowContent(StringRef Content) { Content = Content.trim(Blanks); // Simple heuristic for what to reflow: content should contain at least two // characters and either the first or second character must be // non-punctuation. return Content.size() >= 2 && !Content.endswith("\\") && // Note that this is UTF-8 safe, since if isPunctuation(Content[0]) is // true, then the first code point must be 1 byte long. (!isPunctuation(Content[0]) || !isPunctuation(Content[1])); } bool BreakableComment::mayReflow(unsigned LineIndex) const { return LineIndex > 0 && mayReflowContent(Content[LineIndex]) && !Tok.Finalized && !switchesFormatting(tokenAt(LineIndex)) && (!Tok.is(TT_LineComment) || OriginalPrefix[LineIndex] == OriginalPrefix[LineIndex - 1]); } BreakableBlockComment::BreakableBlockComment( const FormatToken &Token, unsigned IndentLevel, unsigned StartColumn, unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style) : BreakableComment(Token, IndentLevel, StartColumn, OriginalStartColumn, FirstInLine, InPPDirective, Encoding, Style) { assert(Tok.is(TT_BlockComment) && "block comment section must start with a block comment"); StringRef TokenText(Tok.TokenText); assert(TokenText.startswith("/*") && TokenText.endswith("*/")); TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n"); int IndentDelta = StartColumn - OriginalStartColumn; Content.resize(Lines.size()); Content[0] = Lines[0]; ContentColumn.resize(Lines.size()); // Account for the initial '/*'. ContentColumn[0] = StartColumn + 2; Tokens.resize(Lines.size()); for (size_t i = 1; i < Lines.size(); ++i) adjustWhitespace(i, IndentDelta); Decoration = "* "; if (Lines.size() == 1 && !FirstInLine) { // Comments for which FirstInLine is false can start on arbitrary column, // and available horizontal space can be too small to align consecutive // lines with the first one. // FIXME: We could, probably, align them to current indentation level, but // now we just wrap them without stars. Decoration = ""; } for (size_t i = 1, e = Lines.size(); i < e && !Decoration.empty(); ++i) { // If the last line is empty, the closing "*/" will have a star. if (i + 1 == e && Content[i].empty()) break; if (!Content[i].empty() && i + 1 != e && Decoration.startswith(Content[i])) continue; while (!Content[i].startswith(Decoration)) Decoration = Decoration.substr(0, Decoration.size() - 1); } LastLineNeedsDecoration = true; IndentAtLineBreak = ContentColumn[0] + 1; for (size_t i = 1, e = Lines.size(); i < e; ++i) { if (Content[i].empty()) { if (i + 1 == e) { // Empty last line means that we already have a star as a part of the // trailing */. We also need to preserve whitespace, so that */ is // correctly indented. LastLineNeedsDecoration = false; } else if (Decoration.empty()) { // For all other lines, set the start column to 0 if they're empty, so // we do not insert trailing whitespace anywhere. ContentColumn[i] = 0; } continue; } // The first line already excludes the star. // For all other lines, adjust the line to exclude the star and // (optionally) the first whitespace. unsigned DecorationSize = Decoration.startswith(Content[i]) ? Content[i].size() : Decoration.size(); ContentColumn[i] += DecorationSize; Content[i] = Content[i].substr(DecorationSize); if (!Decoration.startswith(Content[i])) IndentAtLineBreak = std::min<int>(IndentAtLineBreak, std::max(0, ContentColumn[i])); } IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size()); DEBUG({ llvm::dbgs() << "IndentAtLineBreak " << IndentAtLineBreak << "\n"; for (size_t i = 0; i < Lines.size(); ++i) { llvm::dbgs() << i << " |" << Content[i] << "| " << (Content[i].data() - Lines[i].data()) << "\n"; } }); } void BreakableBlockComment::adjustWhitespace(unsigned LineIndex, int IndentDelta) { // When in a preprocessor directive, the trailing backslash in a block comment // is not needed, but can serve a purpose of uniformity with necessary escaped // newlines outside the comment. In this case we remove it here before // trimming the trailing whitespace. The backslash will be re-added later when // inserting a line break. size_t EndOfPreviousLine = Lines[LineIndex - 1].size(); if (InPPDirective && Lines[LineIndex - 1].endswith("\\")) --EndOfPreviousLine; // Calculate the end of the non-whitespace text in the previous line. EndOfPreviousLine = Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine); if (EndOfPreviousLine == StringRef::npos) EndOfPreviousLine = 0; else ++EndOfPreviousLine; // Calculate the start of the non-whitespace text in the current line. size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks); if (StartOfLine == StringRef::npos) StartOfLine = Lines[LineIndex].rtrim("\r\n").size(); StringRef Whitespace = Lines[LineIndex].substr(0, StartOfLine); // Adjust Lines to only contain relevant text. size_t PreviousContentOffset = Content[LineIndex - 1].data() - Lines[LineIndex - 1].data(); Content[LineIndex - 1] = Lines[LineIndex - 1].substr( PreviousContentOffset, EndOfPreviousLine - PreviousContentOffset); Content[LineIndex] = Lines[LineIndex].substr(StartOfLine); // Adjust the start column uniformly across all lines. ContentColumn[LineIndex] = encoding::columnWidthWithTabs(Whitespace, 0, Style.TabWidth, Encoding) + IndentDelta; } unsigned BreakableBlockComment::getLineLengthAfterSplit( unsigned LineIndex, unsigned TailOffset, StringRef::size_type Length) const { unsigned ContentStartColumn = getContentStartColumn(LineIndex, TailOffset); unsigned LineLength = ContentStartColumn + encoding::columnWidthWithTabs( Content[LineIndex].substr(TailOffset, Length), ContentStartColumn, Style.TabWidth, Encoding); // The last line gets a "*/" postfix. if (LineIndex + 1 == Lines.size()) { LineLength += 2; // We never need a decoration when breaking just the trailing "*/" postfix. // Note that checking that Length == 0 is not enough, since Length could // also be StringRef::npos. if (Content[LineIndex].substr(TailOffset, Length).empty()) { LineLength -= Decoration.size(); } } return LineLength; } void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { StringRef Text = Content[LineIndex].substr(TailOffset); StringRef Prefix = Decoration; // We need this to account for the case when we have a decoration "* " for all // the lines except for the last one, where the star in "*/" acts as a // decoration. unsigned LocalIndentAtLineBreak = IndentAtLineBreak; if (LineIndex + 1 == Lines.size() && Text.size() == Split.first + Split.second) { // For the last line we need to break before "*/", but not to add "* ". Prefix = ""; if (LocalIndentAtLineBreak >= 2) LocalIndentAtLineBreak -= 2; } // The split offset is from the beginning of the line. Convert it to an offset // from the beginning of the token text. unsigned BreakOffsetInToken = Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; unsigned CharsToRemove = Split.second; assert(LocalIndentAtLineBreak >= Prefix.size()); Whitespaces.replaceWhitespaceInToken( tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix, InPPDirective, /*Newlines=*/1, IndentLevel, /*Spaces=*/LocalIndentAtLineBreak - Prefix.size()); } BreakableToken::Split BreakableBlockComment::getSplitBefore( unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit) const { if (!mayReflow(LineIndex)) return Split(StringRef::npos, 0); StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks); return getReflowSplit(TrimmedContent, ReflowPrefix, PreviousEndColumn, ColumnLimit); } unsigned BreakableBlockComment::getReflownColumn( StringRef Content, unsigned LineIndex, unsigned PreviousEndColumn) const { unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size(); // If this is the last line, it will carry around its '*/' postfix. unsigned PostfixLength = (LineIndex + 1 == Lines.size() ? 2 : 0); // The line is composed of previous text, reflow prefix, reflown text and // postfix. unsigned ReflownColumn = StartColumn + encoding::columnWidthWithTabs(Content, StartColumn, Style.TabWidth, Encoding) + PostfixLength; return ReflownColumn; } unsigned BreakableBlockComment::getLineLengthAfterSplitBefore( unsigned LineIndex, unsigned TailOffset, unsigned PreviousEndColumn, unsigned ColumnLimit, Split SplitBefore) const { if (SplitBefore.first == StringRef::npos || SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) { // A piece of line, not the whole, gets reflown. return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos); } else { // The whole line gets reflown, need to check if we need to insert a break // for the postfix or not. StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks); unsigned ReflownColumn = getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn); if (ReflownColumn <= ColumnLimit) { return ReflownColumn; } return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos); } } void BreakableBlockComment::replaceWhitespaceBefore( unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit, Split SplitBefore, WhitespaceManager &Whitespaces) { if (LineIndex == 0) return; StringRef TrimmedContent = Content[LineIndex].ltrim(Blanks); if (SplitBefore.first != StringRef::npos) { // Here we need to reflow. assert(Tokens[LineIndex - 1] == Tokens[LineIndex] && "Reflowing whitespace within a token"); // This is the offset of the end of the last line relative to the start of // the token text in the token. unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() + Content[LineIndex - 1].size() - tokenAt(LineIndex).TokenText.data(); unsigned WhitespaceLength = TrimmedContent.data() - tokenAt(LineIndex).TokenText.data() - WhitespaceOffsetInToken; Whitespaces.replaceWhitespaceInToken( tokenAt(LineIndex), WhitespaceOffsetInToken, /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"", /*CurrentPrefix=*/ReflowPrefix, InPPDirective, /*Newlines=*/0, IndentLevel, /*Spaces=*/0); // Check if we need to also insert a break at the whitespace range. // For this we first adapt the reflow split relative to the beginning of the // content. // Note that we don't need a penalty for this break, since it doesn't change // the total number of lines. Split BreakSplit = SplitBefore; BreakSplit.first += TrimmedContent.data() - Content[LineIndex].data(); unsigned ReflownColumn = getReflownColumn(TrimmedContent, LineIndex, PreviousEndColumn); if (ReflownColumn > ColumnLimit) { insertBreak(LineIndex, 0, BreakSplit, Whitespaces); } return; } // Here no reflow with the previous line will happen. // Fix the decoration of the line at LineIndex. StringRef Prefix = Decoration; if (Content[LineIndex].empty()) { if (LineIndex + 1 == Lines.size()) { if (!LastLineNeedsDecoration) { // If the last line was empty, we don't need a prefix, as the */ will // line up with the decoration (if it exists). Prefix = ""; } } else if (!Decoration.empty()) { // For other empty lines, if we do have a decoration, adapt it to not // contain a trailing whitespace. Prefix = Prefix.substr(0, 1); } } else { if (ContentColumn[LineIndex] == 1) { // This line starts immediately after the decorating *. Prefix = Prefix.substr(0, 1); } } // This is the offset of the end of the last line relative to the start of the // token text in the token. unsigned WhitespaceOffsetInToken = Content[LineIndex - 1].data() + Content[LineIndex - 1].size() - tokenAt(LineIndex).TokenText.data(); unsigned WhitespaceLength = Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - WhitespaceOffsetInToken; Whitespaces.replaceWhitespaceInToken( tokenAt(LineIndex), WhitespaceOffsetInToken, WhitespaceLength, "", Prefix, InPPDirective, /*Newlines=*/1, IndentLevel, ContentColumn[LineIndex] - Prefix.size()); } unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex, unsigned TailOffset) const { // If we break, we always break at the predefined indent. if (TailOffset != 0) return IndentAtLineBreak; return std::max(0, ContentColumn[LineIndex]); } BreakableLineCommentSection::BreakableLineCommentSection( const FormatToken &Token, unsigned IndentLevel, unsigned StartColumn, unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, encoding::Encoding Encoding, const FormatStyle &Style) : BreakableComment(Token, IndentLevel, StartColumn, OriginalStartColumn, FirstInLine, InPPDirective, Encoding, Style) { assert(Tok.is(TT_LineComment) && "line comment section must start with a line comment"); FormatToken *LineTok = nullptr; for (const FormatToken *CurrentTok = &Tok; CurrentTok && CurrentTok->is(TT_LineComment); CurrentTok = CurrentTok->Next) { LastLineTok = LineTok; StringRef TokenText(CurrentTok->TokenText); assert(TokenText.startswith("//")); size_t FirstLineIndex = Lines.size(); TokenText.split(Lines, "\n"); Content.resize(Lines.size()); ContentColumn.resize(Lines.size()); OriginalContentColumn.resize(Lines.size()); Tokens.resize(Lines.size()); Prefix.resize(Lines.size()); OriginalPrefix.resize(Lines.size()); for (size_t i = FirstLineIndex, e = Lines.size(); i < e; ++i) { StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i]); OriginalPrefix[i] = Prefix[i] = IndentPrefix; if (Lines[i].size() > Prefix[i].size() && isAlphanumeric(Lines[i][Prefix[i].size()])) { if (Prefix[i] == "//") Prefix[i] = "// "; else if (Prefix[i] == "///") Prefix[i] = "/// "; else if (Prefix[i] == "//!") Prefix[i] = "//! "; } Tokens[i] = LineTok; Content[i] = Lines[i].substr(IndentPrefix.size()); OriginalContentColumn[i] = StartColumn + encoding::columnWidthWithTabs(OriginalPrefix[i], StartColumn, Style.TabWidth, Encoding); ContentColumn[i] = StartColumn + encoding::columnWidthWithTabs(Prefix[i], StartColumn, Style.TabWidth, Encoding); // Calculate the end of the non-whitespace text in this line. size_t EndOfLine = Content[i].find_last_not_of(Blanks); if (EndOfLine == StringRef::npos) EndOfLine = Content[i].size(); else ++EndOfLine; Content[i] = Content[i].substr(0, EndOfLine); } LineTok = CurrentTok->Next; } } unsigned BreakableLineCommentSection::getLineLengthAfterSplit( unsigned LineIndex, unsigned TailOffset, StringRef::size_type Length) const { unsigned ContentStartColumn = (TailOffset == 0 ? ContentColumn[LineIndex] : OriginalContentColumn[LineIndex]); return ContentStartColumn + encoding::columnWidthWithTabs( Content[LineIndex].substr(TailOffset, Length), ContentStartColumn, Style.TabWidth, Encoding); } void BreakableLineCommentSection::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { StringRef Text = Content[LineIndex].substr(TailOffset); // Compute the offset of the split relative to the beginning of the token // text. unsigned BreakOffsetInToken = Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first; unsigned CharsToRemove = Split.second; // Compute the size of the new indent, including the size of the new prefix of // the newly broken line. unsigned IndentAtLineBreak = OriginalContentColumn[LineIndex] + Prefix[LineIndex].size() - OriginalPrefix[LineIndex].size(); assert(IndentAtLineBreak >= Prefix[LineIndex].size()); Whitespaces.replaceWhitespaceInToken( tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix[LineIndex], InPPDirective, /*Newlines=*/1, IndentLevel, /*Spaces=*/IndentAtLineBreak - Prefix[LineIndex].size()); } BreakableComment::Split BreakableLineCommentSection::getSplitBefore( unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit) const { if (!mayReflow(LineIndex)) return Split(StringRef::npos, 0); return getReflowSplit(Content[LineIndex], ReflowPrefix, PreviousEndColumn, ColumnLimit); } unsigned BreakableLineCommentSection::getLineLengthAfterSplitBefore( unsigned LineIndex, unsigned TailOffset, unsigned PreviousEndColumn, unsigned ColumnLimit, Split SplitBefore) const { if (SplitBefore.first == StringRef::npos || SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) { // A piece of line, not the whole line, gets reflown. return getLineLengthAfterSplit(LineIndex, TailOffset, StringRef::npos); } else { // The whole line gets reflown. unsigned StartColumn = PreviousEndColumn + ReflowPrefix.size(); return StartColumn + encoding::columnWidthWithTabs(Content[LineIndex], StartColumn, Style.TabWidth, Encoding); } } void BreakableLineCommentSection::replaceWhitespaceBefore( unsigned LineIndex, unsigned PreviousEndColumn, unsigned ColumnLimit, Split SplitBefore, WhitespaceManager &Whitespaces) { // If this is the first line of a token, we need to inform Whitespace Manager // about it: either adapt the whitespace range preceding it, or mark it as an // untouchable token. // This happens for instance here: // // line 1 \ // // line 2 if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) { if (SplitBefore.first != StringRef::npos) { // Reflow happens between tokens. Replace the whitespace between the // tokens by the empty string. Whitespaces.replaceWhitespace(*Tokens[LineIndex], /*Newlines=*/0, /*IndentLevel=*/IndentLevel, /*Spaces=*/0, /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false); // Replace the indent and prefix of the token with the reflow prefix. unsigned WhitespaceLength = Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data(); Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex], /*Offset=*/0, /*ReplaceChars=*/WhitespaceLength, /*PreviousPostfix=*/"", /*CurrentPrefix=*/ReflowPrefix, /*InPPDirective=*/false, /*Newlines=*/0, /*IndentLevel=*/IndentLevel, /*Spaces=*/0); } else { // This is the first line for the current token, but no reflow with the // previous token is necessary. However, we still may need to adjust the // start column. unsigned LineColumn = ContentColumn[LineIndex] - (Content[LineIndex].data() - Lines[LineIndex].data()); if (tokenAt(LineIndex).OriginalColumn != LineColumn) { Whitespaces.replaceWhitespace(*Tokens[LineIndex], /*Newlines=*/1, /*IndentLevel=*/IndentLevel, /*Spaces=*/LineColumn, /*StartOfTokenColumn=*/LineColumn, /*InPPDirective=*/false); } else { // The whitespace preceding the first line of this token does not need // to be touched. Whitespaces.addUntouchableToken(tokenAt(LineIndex), /*InPPDirective=*/false); } } } else if (OriginalPrefix[LineIndex] != Prefix[LineIndex]) { // This is not the first line of the token. Adjust the prefix if necessary. // Take care of the space possibly introduced after a decoration. assert(Prefix[LineIndex] == (OriginalPrefix[LineIndex] + " ").str() && "Expecting a block comment decoration to differ from original by " "at most a space"); Whitespaces.replaceWhitespaceInToken( tokenAt(LineIndex), OriginalPrefix[LineIndex].size(), 0, "", "", /*InPPDirective=*/false, /*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1); } // Add a break after a reflow split has been introduced, if necessary. // Note that this break doesn't need to be penalized, since it doesn't change // the number of lines. if (SplitBefore.first != StringRef::npos && SplitBefore.first + SplitBefore.second < Content[LineIndex].size()) { insertBreak(LineIndex, 0, SplitBefore, Whitespaces); } } void BreakableLineCommentSection::updateNextToken(LineState& State) const { if (LastLineTok) { State.NextToken = LastLineTok->Next; } } unsigned BreakableLineCommentSection::getContentStartColumn(unsigned LineIndex, unsigned TailOffset) const { if (TailOffset != 0) { return OriginalContentColumn[LineIndex]; } return ContentColumn[LineIndex]; } } // namespace format } // namespace clang
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_parallel_for_simd_schedule_messages.cpp
143
// RUN: %clang_cc1 -verify -fopenmp %s void foo() { } bool foobool(int argc) { return argc; } struct S1; // expected-note {{declared here}} template <class T, typename S, int N, int ST> // expected-note {{declared here}} T tmain(T argc, S **argv) { // expected-error@+1 {{expected '(' after 'schedule'}} #pragma omp target teams distribute parallel for simd schedule for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{expected 'static', 'dynamic', 'guided', 'auto', 'runtime', 'monotonic', 'nonmonotonic' or 'simd' in OpenMP clause 'schedule'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule ( for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{expected 'static', 'dynamic', 'guided', 'auto', 'runtime', 'monotonic', 'nonmonotonic' or 'simd' in OpenMP clause 'schedule'}} #pragma omp target teams distribute parallel for simd schedule () for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (auto for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{expected 'static', 'dynamic', 'guided', 'auto', 'runtime', 'monotonic', 'nonmonotonic' or 'simd' in OpenMP clause 'schedule'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (auto_dynamic for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (auto, for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (runtime, 3) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (guided argc for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 2 {{argument to 'schedule' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd schedule (static, ST // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd schedule (dynamic, 1)) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd schedule (guided, (ST > 0) ? 1 + ST : 2) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+2 2 {{directive '#pragma omp target teams distribute parallel for simd' cannot contain more than one 'schedule' clause}} // expected-error@+1 {{argument to 'schedule' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd schedule (static, foobool(argc)), schedule (dynamic, true), schedule (guided, -5) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{'S' does not refer to a value}} #pragma omp target teams distribute parallel for simd schedule (static, S) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+2 2 {{expression must have integral or unscoped enumeration type, not 'char *'}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (guided, argv[1]=2) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd schedule (dynamic, 1) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 {{argument to 'schedule' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd schedule (static, N) for (T i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; return argc; } int main(int argc, char **argv) { // expected-error@+1 {{expected '(' after 'schedule'}} #pragma omp target teams distribute parallel for simd schedule for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{expected 'static', 'dynamic', 'guided', 'auto', 'runtime', 'monotonic', 'nonmonotonic' or 'simd' in OpenMP clause 'schedule'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule ( for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{expected 'static', 'dynamic', 'guided', 'auto', 'runtime', 'monotonic', 'nonmonotonic' or 'simd' in OpenMP clause 'schedule'}} #pragma omp target teams distribute parallel for simd schedule () for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (auto for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{expected 'static', 'dynamic', 'guided', 'auto', 'runtime', 'monotonic', 'nonmonotonic' or 'simd' in OpenMP clause 'schedule'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (auto_dynamic for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (auto, for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (runtime, 3) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp target teams distribute parallel for simd schedule (guided, 4 for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-warning@+1 {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} #pragma omp target teams distribute parallel for simd schedule (static, 2+2)) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd schedule (dynamic, foobool(1) > 0 ? 1 : 2) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+2 2 {{directive '#pragma omp target teams distribute parallel for simd' cannot contain more than one 'schedule' clause}} // expected-error@+1 {{argument to 'schedule' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd schedule (guided, foobool(argc)), schedule (static, true), schedule (dynamic, -5) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+1 {{'S1' does not refer to a value}} #pragma omp target teams distribute parallel for simd schedule (guided, S1) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expression must have integral or unscoped enumeration type, not 'char *'}} #pragma omp target teams distribute parallel for simd schedule (static, argv[1]=2) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+3 {{statement after '#pragma omp target teams distribute parallel for simd' must be a for loop}} // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, -1, -2>' requested here}} #pragma omp target teams distribute parallel for simd schedule(dynamic, schedule(tmain<int, char, -1, -2>(argc, argv) // expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}} foo(); // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, 1, 0>' requested here}} return tmain<int, char, 1, 0>(argc, argv); }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/nvptx_parallel_codegen.cpp
317
// Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // RUN: %clang_cc1 -verify -fopenmp -fexceptions -fcxx-exceptions -x c++ -triple nvptx-unknown-unknown -fopenmp-targets=nvptx-nvidia-cuda -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // expected-no-diagnostics #ifndef HEADER #define HEADER template<typename tx> tx ftemplate(int n) { tx a = 0; short aa = 0; tx b[10]; #pragma omp target if(0) { #pragma omp parallel { int a = 41; } a += 1; } #pragma omp target { #pragma omp parallel { int a = 42; } #pragma omp parallel if(0) { int a = 43; } #pragma omp parallel if(1) { int a = 44; } a += 1; } #pragma omp target if(n>40) { #pragma omp parallel if(n>1000) { int a = 45; } a += 1; aa += 1; b[2] += 1; } return a; } int bar(int n){ int a = 0; a += ftemplate<int>(n); return a; } // CHECK-NOT: define {{.*}}void {{@__omp_offloading_.+template.+l17}}_worker() // CHECK-LABEL: define {{.*}}void {{@__omp_offloading_.+template.+l26}}_worker() // CHECK-DAG: [[OMP_EXEC_STATUS:%.+]] = alloca i8, // CHECK-DAG: [[OMP_WORK_FN:%.+]] = alloca i8*, // CHECK: store i8* null, i8** [[OMP_WORK_FN]], // CHECK: store i8 0, i8* [[OMP_EXEC_STATUS]], // CHECK: br label {{%?}}[[AWAIT_WORK:.+]] // // CHECK: [[AWAIT_WORK]] // CHECK: call void @llvm.nvvm.barrier0() // CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]]) // CHECK: [[KPRB:%.+]] = zext i1 [[KPR]] to i8 // store i8 [[KPRB]], i8* [[OMP_EXEC_STATUS]], align 1 // CHECK: [[WORK:%.+]] = load i8*, i8** [[OMP_WORK_FN]], // CHECK: [[SHOULD_EXIT:%.+]] = icmp eq i8* [[WORK]], null // CHECK: br i1 [[SHOULD_EXIT]], label {{%?}}[[EXIT:.+]], label {{%?}}[[SEL_WORKERS:.+]] // // CHECK: [[SEL_WORKERS]] // CHECK: [[ST:%.+]] = load i8, i8* [[OMP_EXEC_STATUS]] // CHECK: [[IS_ACTIVE:%.+]] = icmp ne i8 [[ST]], 0 // CHECK: br i1 [[IS_ACTIVE]], label {{%?}}[[EXEC_PARALLEL:.+]], label {{%?}}[[BAR_PARALLEL:.+]] // // CHECK: [[EXEC_PARALLEL]] // CHECK: [[WF1:%.+]] = load i8*, i8** [[OMP_WORK_FN]], // CHECK: [[WM1:%.+]] = icmp eq i8* [[WF1]], bitcast (void (i32*, i32*)* [[PARALLEL_FN1:@.+]] to i8*) // CHECK: br i1 [[WM1]], label {{%?}}[[EXEC_PFN1:.+]], label {{%?}}[[CHECK_NEXT1:.+]] // // CHECK: [[EXEC_PFN1]] // CHECK: call void [[PARALLEL_FN1]]( // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]] // // CHECK: [[CHECK_NEXT1]] // CHECK: [[WF2:%.+]] = load i8*, i8** [[OMP_WORK_FN]], // CHECK: [[WM2:%.+]] = icmp eq i8* [[WF2]], bitcast (void (i32*, i32*)* [[PARALLEL_FN2:@.+]] to i8*) // CHECK: br i1 [[WM2]], label {{%?}}[[EXEC_PFN2:.+]], label {{%?}}[[CHECK_NEXT2:.+]] // // CHECK: [[EXEC_PFN2]] // CHECK: call void [[PARALLEL_FN2]]( // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]] // // CHECK: [[CHECK_NEXT2]] // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]] // // CHECK: [[TERM_PARALLEL]] // CHECK: call void @__kmpc_kernel_end_parallel() // CHECK: br label {{%?}}[[BAR_PARALLEL]] // // CHECK: [[BAR_PARALLEL]] // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[AWAIT_WORK]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK: define {{.*}}void [[T6:@__omp_offloading_.+template.+l26]](i[[SZ:32|64]] // Create local storage for each capture. // CHECK: [[LOCAL_A:%.+]] = alloca i[[SZ]], // CHECK-DAG: store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]] // Store captures in the context. // CHECK-64-DAG:[[REF_A:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32* // // CHECK-DAG: [[TID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK-DAG: [[NTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[WS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK-DAG: [[TH_LIMIT:%.+]] = sub i32 [[NTH]], [[WS]] // CHECK: [[IS_WORKER:%.+]] = icmp ult i32 [[TID]], [[TH_LIMIT]] // CHECK: br i1 [[IS_WORKER]], label {{%?}}[[WORKER:.+]], label {{%?}}[[CHECK_MASTER:.+]] // // CHECK: [[WORKER]] // CHECK: {{call|invoke}} void [[T6]]_worker() // CHECK: br label {{%?}}[[EXIT:.+]] // // CHECK: [[CHECK_MASTER]] // CHECK-DAG: [[CMTID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK-DAG: [[CMNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[CMWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK: [[IS_MASTER:%.+]] = icmp eq i32 [[CMTID]], // CHECK: br i1 [[IS_MASTER]], label {{%?}}[[MASTER:.+]], label {{%?}}[[EXIT]] // // CHECK: [[MASTER]] // CHECK-DAG: [[MNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[MWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK: [[MTMP1:%.+]] = sub i32 [[MNTH]], [[MWS]] // CHECK: call void @__kmpc_kernel_init(i32 [[MTMP1]] // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i32*, i32*)* [[PARALLEL_FN1]] to i8*)) // CHECK: call void @llvm.nvvm.barrier0() // CHECK: call void @llvm.nvvm.barrier0() // CHECK: call void @__kmpc_serialized_parallel( // CHECK: {{call|invoke}} void [[PARALLEL_FN3:@.+]]( // CHECK: call void @__kmpc_end_serialized_parallel( // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i32*, i32*)* [[PARALLEL_FN2]] to i8*)) // CHECK: call void @llvm.nvvm.barrier0() // CHECK: call void @llvm.nvvm.barrier0() // CHECK-64-DAG: load i32, i32* [[REF_A]] // CHECK-32-DAG: load i32, i32* [[LOCAL_A]] // CHECK: br label {{%?}}[[TERMINATE:.+]] // // CHECK: [[TERMINATE]] // CHECK: call void @__kmpc_kernel_deinit() // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[EXIT]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK-DAG: define internal void [[PARALLEL_FN1]]( // CHECK: [[A:%.+]] = alloca i[[SZ:32|64]], // CHECK: store i[[SZ]] 42, i[[SZ]]* %a, // CHECK: ret void // CHECK-DAG: define internal void [[PARALLEL_FN3]]( // CHECK: [[A:%.+]] = alloca i[[SZ:32|64]], // CHECK: store i[[SZ]] 43, i[[SZ]]* %a, // CHECK: ret void // CHECK-DAG: define internal void [[PARALLEL_FN2]]( // CHECK: [[A:%.+]] = alloca i[[SZ:32|64]], // CHECK: store i[[SZ]] 44, i[[SZ]]* %a, // CHECK: ret void // CHECK-LABEL: define {{.*}}void {{@__omp_offloading_.+template.+l43}}_worker() // CHECK-DAG: [[OMP_EXEC_STATUS:%.+]] = alloca i8, // CHECK-DAG: [[OMP_WORK_FN:%.+]] = alloca i8*, // CHECK: store i8* null, i8** [[OMP_WORK_FN]], // CHECK: store i8 0, i8* [[OMP_EXEC_STATUS]], // CHECK: br label {{%?}}[[AWAIT_WORK:.+]] // // CHECK: [[AWAIT_WORK]] // CHECK: call void @llvm.nvvm.barrier0() // CHECK: [[KPR:%.+]] = call i1 @__kmpc_kernel_parallel(i8** [[OMP_WORK_FN]]) // CHECK: [[KPRB:%.+]] = zext i1 [[KPR]] to i8 // store i8 [[KPRB]], i8* [[OMP_EXEC_STATUS]], align 1 // CHECK: [[WORK:%.+]] = load i8*, i8** [[OMP_WORK_FN]], // CHECK: [[SHOULD_EXIT:%.+]] = icmp eq i8* [[WORK]], null // CHECK: br i1 [[SHOULD_EXIT]], label {{%?}}[[EXIT:.+]], label {{%?}}[[SEL_WORKERS:.+]] // // CHECK: [[SEL_WORKERS]] // CHECK: [[ST:%.+]] = load i8, i8* [[OMP_EXEC_STATUS]] // CHECK: [[IS_ACTIVE:%.+]] = icmp ne i8 [[ST]], 0 // CHECK: br i1 [[IS_ACTIVE]], label {{%?}}[[EXEC_PARALLEL:.+]], label {{%?}}[[BAR_PARALLEL:.+]] // // CHECK: [[EXEC_PARALLEL]] // CHECK: [[WF:%.+]] = load i8*, i8** [[OMP_WORK_FN]], // CHECK: [[WM:%.+]] = icmp eq i8* [[WF]], bitcast (void (i32*, i32*)* [[PARALLEL_FN4:@.+]] to i8*) // CHECK: br i1 [[WM]], label {{%?}}[[EXEC_PFN:.+]], label {{%?}}[[CHECK_NEXT:.+]] // // CHECK: [[EXEC_PFN]] // CHECK: call void [[PARALLEL_FN4]]( // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]] // // CHECK: [[CHECK_NEXT]] // CHECK: br label {{%?}}[[TERM_PARALLEL:.+]] // // CHECK: [[TERM_PARALLEL]] // CHECK: call void @__kmpc_kernel_end_parallel() // CHECK: br label {{%?}}[[BAR_PARALLEL]] // // CHECK: [[BAR_PARALLEL]] // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[AWAIT_WORK]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK: define {{.*}}void [[T6:@__omp_offloading_.+template.+l43]](i[[SZ:32|64]] // Create local storage for each capture. // CHECK: [[LOCAL_N:%.+]] = alloca i[[SZ]], // CHECK: [[LOCAL_A:%.+]] = alloca i[[SZ]], // CHECK: [[LOCAL_AA:%.+]] = alloca i[[SZ]], // CHECK: [[LOCAL_B:%.+]] = alloca [10 x i32]* // CHECK-DAG: store i[[SZ]] [[ARG_N:%.+]], i[[SZ]]* [[LOCAL_N]] // CHECK-DAG: store i[[SZ]] [[ARG_A:%.+]], i[[SZ]]* [[LOCAL_A]] // CHECK-DAG: store i[[SZ]] [[ARG_AA:%.+]], i[[SZ]]* [[LOCAL_AA]] // CHECK-DAG: store [10 x i32]* [[ARG_B:%.+]], [10 x i32]** [[LOCAL_B]] // Store captures in the context. // CHECK-64-DAG:[[REF_N:%.+]] = bitcast i[[SZ]]* [[LOCAL_N]] to i32* // CHECK-64-DAG:[[REF_A:%.+]] = bitcast i[[SZ]]* [[LOCAL_A]] to i32* // CHECK-DAG: [[REF_AA:%.+]] = bitcast i[[SZ]]* [[LOCAL_AA]] to i16* // CHECK-DAG: [[REF_B:%.+]] = load [10 x i32]*, [10 x i32]** [[LOCAL_B]], // // CHECK-DAG: [[TID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK-DAG: [[NTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[WS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK-DAG: [[TH_LIMIT:%.+]] = sub i32 [[NTH]], [[WS]] // CHECK: [[IS_WORKER:%.+]] = icmp ult i32 [[TID]], [[TH_LIMIT]] // CHECK: br i1 [[IS_WORKER]], label {{%?}}[[WORKER:.+]], label {{%?}}[[CHECK_MASTER:.+]] // // CHECK: [[WORKER]] // CHECK: {{call|invoke}} void [[T6]]_worker() // CHECK: br label {{%?}}[[EXIT:.+]] // // CHECK: [[CHECK_MASTER]] // CHECK-DAG: [[CMTID:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.tid.x() // CHECK-DAG: [[CMNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[CMWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK: [[IS_MASTER:%.+]] = icmp eq i32 [[CMTID]], // CHECK: br i1 [[IS_MASTER]], label {{%?}}[[MASTER:.+]], label {{%?}}[[EXIT]] // // CHECK: [[MASTER]] // CHECK-DAG: [[MNTH:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.ntid.x() // CHECK-DAG: [[MWS:%.+]] = call i32 @llvm.nvvm.read.ptx.sreg.warpsize() // CHECK: [[MTMP1:%.+]] = sub i32 [[MNTH]], [[MWS]] // CHECK: call void @__kmpc_kernel_init(i32 [[MTMP1]] // CHECK-64: [[N:%.+]] = load i32, i32* [[REF_N]], // CHECK-32: [[N:%.+]] = load i32, i32* [[LOCAL_N]], // CHECK: [[CMP:%.+]] = icmp sgt i32 [[N]], 1000 // CHECK: br i1 [[CMP]], label {{%?}}[[IF_THEN:.+]], label {{%?}}[[IF_ELSE:.+]] // // CHECK: [[IF_THEN]] // CHECK: call void @__kmpc_kernel_prepare_parallel(i8* bitcast (void (i32*, i32*)* [[PARALLEL_FN4]] to i8*)) // CHECK: call void @llvm.nvvm.barrier0() // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[IF_END:.+]] // // CHECK: [[IF_ELSE]] // CHECK: call void @__kmpc_serialized_parallel( // CHECK: {{call|invoke}} void [[PARALLEL_FN4]]( // CHECK: call void @__kmpc_end_serialized_parallel( // br label [[IF_END]] // // CHECK: [[IF_END]] // CHECK-64-DAG: load i32, i32* [[REF_A]] // CHECK-32-DAG: load i32, i32* [[LOCAL_A]] // CHECK-DAG: load i16, i16* [[REF_AA]] // CHECK-DAG: getelementptr inbounds [10 x i32], [10 x i32]* [[REF_B]], i[[SZ]] 0, i[[SZ]] 2 // // CHECK: br label {{%?}}[[TERMINATE:.+]] // // CHECK: [[TERMINATE]] // CHECK: call void @__kmpc_kernel_deinit() // CHECK: call void @llvm.nvvm.barrier0() // CHECK: br label {{%?}}[[EXIT]] // // CHECK: [[EXIT]] // CHECK: ret void // CHECK: define internal void [[PARALLEL_FN4]]( // CHECK: [[A:%.+]] = alloca i[[SZ:32|64]], // CHECK: store i[[SZ]] 45, i[[SZ]]* %a, // CHECK: ret void #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_parallel_for_simd_collapse_messages.cpp
149
// RUN: %clang_cc1 -verify -fopenmp %s // RUN: %clang_cc1 -verify -fopenmp %s -std=c++98 // RUN: %clang_cc1 -verify -fopenmp %s -std=c++11 void foo() { } #if __cplusplus >= 201103L // expected-note@+2 4 {{declared here}} #endif bool foobool(int argc) { return argc; } struct S1; // expected-note {{declared here}} template <class T, typename S, int N, int ST> // expected-note {{declared here}} T tmain(T argc, S **argv) { //expected-note 2 {{declared here}} #pragma omp target teams distribute parallel for simd collapse // expected-error {{expected '(' after 'collapse'}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse () // expected-error {{expected expression}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 2 {{expression is not an integral constant expression}} // expected-note@+1 2 {{read of non-const variable 'argc' is not allowed in a constant expression}} #pragma omp target teams distribute parallel for simd collapse (argc for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 2 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse (ST // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (1)) // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse ((ST > 0) ? 1 + ST : 2) // expected-note 2 {{as specified in 'collapse' clause}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error 2 {{expected 2 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} #if __cplusplus >= 201103L // expected-note@+5 2 {{non-constexpr function 'foobool' cannot be used}} #endif // expected-error@+3 2 {{directive '#pragma omp target teams distribute parallel for simd' cannot contain more than one 'collapse' clause}} // expected-error@+2 2 {{argument to 'collapse' clause must be a strictly positive integer value}} // expected-error@+1 2 {{expression is not an integral constant expression}} #pragma omp target teams distribute parallel for simd collapse (foobool(argc)), collapse (true), collapse (-5) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (S) // expected-error {{'S' does not refer to a value}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #if __cplusplus >= 201103L // expected-error@+4 2 {{integral constant expression must have integral or unscoped enumeration type}} #else // expected-error@+2 2 {{expression is not an integral constant expression}} #endif #pragma omp target teams distribute parallel for simd collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (1) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (N) // expected-error {{argument to 'collapse' clause must be a strictly positive integer value}} for (T i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (2) // expected-note {{as specified in 'collapse' clause}} foo(); // expected-error {{expected 2 for loops after '#pragma omp target teams distribute parallel for simd'}} return argc; } int main(int argc, char **argv) { #pragma omp target teams distribute parallel for simd collapse // expected-error {{expected '(' after 'collapse'}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd collapse () // expected-error {{expected expression}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd collapse (4 // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-note {{as specified in 'collapse' clause}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} #pragma omp target teams distribute parallel for simd collapse (2+2)) // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} expected-note {{as specified in 'collapse' clause}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} #if __cplusplus >= 201103L // expected-note@+2 {{non-constexpr function 'foobool' cannot be used}} #endif #pragma omp target teams distribute parallel for simd collapse (foobool(1) > 0 ? 1 : 2) // expected-error {{expression is not an integral constant expression}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #if __cplusplus >= 201103L // expected-note@+5 {{non-constexpr function 'foobool' cannot be used}} #endif // expected-error@+3 {{expression is not an integral constant expression}} // expected-error@+2 2 {{directive '#pragma omp target teams distribute parallel for simd' cannot contain more than one 'collapse' clause}} // expected-error@+1 2 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse (foobool(argc)), collapse (true), collapse (-5) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd collapse (S1) // expected-error {{'S1' does not refer to a value}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #if __cplusplus >= 201103L // expected-error@+4 {{integral constant expression must have integral or unscoped enumeration type}} #else // expected-error@+2 {{expression is not an integral constant expression}} #endif #pragma omp target teams distribute parallel for simd collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+3 {{statement after '#pragma omp target teams distribute parallel for simd' must be a for loop}} // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, -1, -2>' requested here}} #pragma omp target teams distribute parallel for simd collapse(collapse(tmain<int, char, -1, -2>(argc, argv) // expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}} foo(); #pragma omp target teams distribute parallel for simd collapse (2) // expected-note {{as specified in 'collapse' clause}} foo(); // expected-error {{expected 2 for loops after '#pragma omp target teams distribute parallel for simd'}} // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, 1, 0>' requested here}} return tmain<int, char, 1, 0>(argc, argv); }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_simd_aligned_messages.cpp
231
// RUN: %clang_cc1 -x c++ -std=c++11 -verify -fopenmp %s struct B { static int ib[20]; // expected-note 0 {{'B::ib' declared here}} static constexpr int bfoo() { return 8; } }; namespace X { B x; // expected-note {{'x' defined here}} }; constexpr int bfoo() { return 4; } int **z; const int C1 = 1; const int C2 = 2; void test_aligned_colons(int *&rp) { int *B = 0; #pragma omp target teams distribute simd aligned(B:bfoo()) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(B::ib:B:bfoo()) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(B:B::bfoo()) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(z:B:bfoo()) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'?}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(B:B::bfoo()) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(X::x : ::z) // expected-error {{integral constant expression must have integral or unscoped enumeration type, not 'int **'}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'B'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(B,rp,::z: X::x) // expected-error {{integral constant expression must have integral or unscoped enumeration type, not 'B'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(::z) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(B::bfoo()) // expected-error {{expected variable name}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute simd aligned(B::ib,B:C1+C2) // expected-warning {{aligned clause will be ignored because the requested alignment is not a power of 2}} for (int i = 0; i < 10; ++i) ; } // expected-note@+1 {{'num' defined here}} template<int L, class T, class N> T test_template(T* arr, N num) { N i; T sum = (T)0; T ind2 = - num * L; // Negative number is passed as L. #pragma omp target teams distribute simd aligned(arr:L) // expected-error {{argument to 'aligned' clause must be a strictly positive integer value}} for (i = 0; i < num; ++i) { T cur = arr[(int)ind2]; ind2 += L; sum += cur; } #pragma omp target teams distribute simd aligned(num:4) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}} for (i = 0; i < num; ++i); return T(); } template<int LEN> int test_warn() { int *ind2 = 0; #pragma omp target teams distribute simd aligned(ind2:LEN) // expected-error {{argument to 'aligned' clause must be a strictly positive integer value}} for (int i = 0; i < 100; i++) { ind2 += LEN; } return 0; } struct S1; // expected-note 2 {{declared here}} extern S1 a; // expected-note {{'a' declared here}} class S2 { mutable int a; public: S2():a(0) { } }; const S2 b; // expected-note 1 {{'b' defined here}} const S2 ba[5]; class S3 { int a; public: S3():a(0) { } }; const S3 ca[5]; class S4 { int a; S4(); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} public: S5(int v):a(v) { } }; S3 h; // expected-note 2 {{'h' defined here}} #pragma omp threadprivate(h) template<class I, class C> int foomain(I argc, C **argv) { I e(argc); I g(argc); int i; // expected-note {{declared here}} expected-note {{'i' defined here}} // expected-note@+2 {{declared here}} // expected-note@+1 {{reference to 'i' is not a constant expression}} int &j = i; #pragma omp target teams distribute simd aligned // expected-error {{expected '(' after 'aligned'}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned () // expected-error {{expected expression}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (I k = 0; k < argc; ++k) ++k; // FIXME: Should argc really be a pointer? #pragma omp target teams distribute simd aligned (*argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (argc : 5) // expected-warning {{aligned clause will be ignored because the requested alignment is not a power of 2}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (S1) // expected-error {{'S1' does not refer to a value}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (argv[1]) // expected-error {{expected variable name}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned(e, g) for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned(h) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S3'}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned(i) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}} for (I k = 0; k < argc; ++k) ++k; #pragma omp parallel { int *v = 0; I i; #pragma omp target teams distribute simd aligned(v:16) for (I k = 0; k < argc; ++k) { i = k; v += 2; } } float *f; #pragma omp target teams distribute simd aligned(f) for (I k = 0; k < argc; ++k) ++k; int v = 0; #pragma omp target teams distribute simd aligned(f:j) // expected-note {{initializer of 'j' is not a constant expression}} expected-error {{expression is not an integral constant expression}} for (I k = 0; k < argc; ++k) { ++k; v += j; } #pragma omp target teams distribute simd aligned(f) for (I k = 0; k < argc; ++k) ++k; return 0; } // expected-note@+1 2 {{'argc' defined here}} int main(int argc, char **argv) { double darr[100]; // expected-note@+1 {{in instantiation of function template specialization 'test_template<-4, double, int>' requested here}} test_template<-4>(darr, 4); test_warn<4>(); // ok // expected-note@+1 {{in instantiation of function template specialization 'test_warn<0>' requested here}} test_warn<0>(); int i; int &j = i; #pragma omp target teams distribute simd aligned // expected-error {{expected '(' after 'aligned'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned () // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (argv // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams #pragma omp distribute simd aligned (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams #pragma omp distribute simd aligned (argc) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (a, b) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S1'}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S2'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned (argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute simd aligned(h) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S3'}} for (int k = 0; k < argc; ++k) ++k; int *pargc = &argc; // expected-note@+1 {{in instantiation of function template specialization 'foomain<int *, char>' requested here}} foomain<int*,char>(pargc,argv); return 0; }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_parallel_if_codegen.cpp
413
// Test host codegen. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32 // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-DAG: %ident_t = type { i32, i32, i32, i32, i8* } // CHECK-DAG: [[STR:@.+]] = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00" // CHECK-DAG: [[DEF_LOC:@.+]] = private unnamed_addr constant %ident_t { i32 0, i32 2, i32 0, i32 0, i8* getelementptr inbounds ([23 x i8], [23 x i8]* [[STR]], i32 0, i32 0) } // CHECK-DAG: [[S1:%.+]] = type { double } // CHECK-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 } // CHECK-DAG: [[DEVTY:%.+]] = type { i8*, i8*, [[ENTTY]]*, [[ENTTY]]* } // CHECK-DAG: [[DSCTY:%.+]] = type { i32, [[DEVTY]]*, [[ENTTY]]*, [[ENTTY]]* } // TCHECK: [[ENTTY:%.+]] = type { i8*, i8*, i{{32|64}}, i32, i32 } // We have 6 target regions // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] // CHECK: [[DEVBEGIN:@.+]] = external constant i8 // CHECK: [[DEVEND:@.+]] = external constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }] // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] } // Check target registration is registered as a Ctor. // CHECK: appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* bitcast (void (i8*)* [[REGFN:@.+]] to void ()*), i8* null }] template<typename tx> tx ftemplate(int n) { tx a = 0; #pragma omp target parallel if(parallel: 0) { a += 1; } short b = 1; #pragma omp target parallel if(parallel: 1) { a += b; } return a; } static int fstatic(int n) { #pragma omp target parallel if(n>1) { } #pragma omp target parallel if(target: n-2>2) { } return n+1; } struct S1 { double a; int r1(int n){ int b = 1; #pragma omp target parallel if(parallel: n>3) { this->a = (double)b + 1.5; } #pragma omp target parallel if(target: n>4) if(parallel: n>5) { this->a = 2.5; } return (int)a; } }; // CHECK: define {{.*}}@{{.*}}bar{{.*}} int bar(int n){ int a = 0; S1 S; // CHECK: call {{.*}}i32 [[FS1:@.+]]([[S1]]* {{.*}}, i32 {{.*}}) a += S.r1(n); // CHECK: call {{.*}}i32 [[FSTATIC:@.+]](i32 {{.*}}) a += fstatic(n); // CHECK: call {{.*}}i32 [[FTEMPLATE:@.+]](i32 {{.*}}) a += ftemplate<int>(n); return a; } // // CHECK: define {{.*}}[[FS1]]([[S1]]* {{%.+}}, i32 {{[^%]*}}[[PARM:%.+]]) // // CHECK-DAG: store i32 [[PARM]], i32* [[N_ADDR:%.+]], align // CHECK: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: [[CMP:%.+]] = icmp sgt i32 [[NV]], 3 // CHECK: [[FB:%.+]] = zext i1 [[CMP]] to i8 // CHECK: store i8 [[FB]], i8* [[CAPE_ADDR:%.+]], align // CHECK: [[CAPE:%.+]] = load i8, i8* [[CAPE_ADDR]], align // CHECK: [[TB:%.+]] = trunc i8 [[CAPE]] to i1 // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPEC_ADDR:%.+]] to i8* // CHECK: [[FB:%.+]] = zext i1 [[TB]] to i8 // CHECK: store i8 [[FB]], i8* [[CONV]], align // CHECK: [[ARG:%.+]] = load i[[SZ]], i[[SZ]]* [[CAPEC_ADDR]], align // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 3, {{.*}}, i32 1, i32 0) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT1:@.+]]([[S1]]* {{%.+}}, i[[SZ]] {{%.+}}, i[[SZ]] [[ARG]]) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // // // CHECK: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: [[CMP:%.+]] = icmp sgt i32 [[NV]], 5 // CHECK: [[FB:%.+]] = zext i1 [[CMP]] to i8 // CHECK: store i8 [[FB]], i8* [[CAPE_ADDR:%.+]], align // CHECK: [[CAPE:%.+]] = load i8, i8* [[CAPE_ADDR]], align // CHECK: [[TB:%.+]] = trunc i8 [[CAPE]] to i1 // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPEC_ADDR:%.+]] to i8* // CHECK: [[FB:%.+]] = zext i1 [[TB]] to i8 // CHECK: store i8 [[FB]], i8* [[CONV]], align // CHECK: [[ARG:%.+]] = load i[[SZ]], i[[SZ]]* [[CAPEC_ADDR]], align // CHECK: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: [[CMP:%.+]] = icmp sgt i32 [[NV]], 4 // CHECK: br i1 [[CMP]], label {{%?}}[[IF_THEN:.+]], label {{%?}}[[IF_ELSE:.+]] // // CHECK: [[IF_THEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 2, {{.*}}, i32 1, i32 0) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: br label {{%?}}[[END:.+]] // // CHECK: [[IF_ELSE]] // CHECK: store i32 -1, i32* [[RHV]], align // CHECK: br label {{%?}}[[END]] // // CHECK: [[END]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT2:@.+]]([[S1]]* {{%.+}}, i[[SZ]] [[ARG]]) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // CHECK: define {{.*}}[[FSTATIC]](i32 {{[^%]*}}[[PARM:%.+]]) // // CHECK-DAG: store i32 [[PARM]], i32* [[N_ADDR:%.+]], align // CHECK: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: [[CMP:%.+]] = icmp sgt i32 [[NV]], 1 // CHECK: [[FB:%.+]] = zext i1 [[CMP]] to i8 // CHECK: store i8 [[FB]], i8* [[CAPE_ADDR:%.+]], align // CHECK: [[CAPE:%.+]] = load i8, i8* [[CAPE_ADDR]], align // CHECK: [[TB:%.+]] = trunc i8 [[CAPE]] to i1 // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPEC_ADDR:%.+]] to i8* // CHECK: [[FB:%.+]] = zext i1 [[TB]] to i8 // CHECK: store i8 [[FB]], i8* [[CONV]], align // CHECK: [[ARG:%.+]] = load i[[SZ]], i[[SZ]]* [[CAPEC_ADDR]], align // CHECK: [[CAPE2:%.+]] = load i8, i8* [[CAPE_ADDR]], align // CHECK: [[TB:%.+]] = trunc i8 [[CAPE2]] to i1 // CHECK: br i1 [[TB]], label {{%?}}[[IF_THEN:.+]], label {{%?}}[[IF_ELSE:.+]] // // CHECK: [[IF_THEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 1, {{.*}}, i32 1, i32 0) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: br label {{%?}}[[END:.+]] // // CHECK: [[IF_ELSE]] // CHECK: store i32 -1, i32* [[RHV]], align // CHECK: br label {{%?}}[[END]] // // CHECK: [[END]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT3:@.+]](i[[SZ]] [[ARG]]) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // // // CHECK-DAG: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: [[SUB:%.+]] = sub nsw i32 [[NV]], 2 // CHECK: [[CMP:%.+]] = icmp sgt i32 [[SUB]], 2 // CHECK: br i1 [[CMP]], label {{%?}}[[IF_THEN:.+]], label {{%?}}[[IF_ELSE:.+]] // // CHECK: [[IF_THEN]] // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 0, {{.*}}, i32 1, i32 0) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: br label {{%?}}[[END:.+]] // // CHECK: [[IF_ELSE]] // CHECK: store i32 -1, i32* [[RHV]], align // CHECK: br label {{%?}}[[END]] // // CHECK: [[END]] // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT4:@.+]]() // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // CHECK: define {{.*}}[[FTEMPLATE]] // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 1, {{.*}}, i32 1, i32 0) // CHECK-NEXT: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK-NEXT: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT5:@.+]]({{[^,]+}}) // CHECK: br label {{%?}}[[END]] // // CHECK: [[END]] // // // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 2, {{.*}}, i32 1, i32 0) // CHECK-NEXT: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK-NEXT: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT6:@.+]]({{[^,]+}}, {{[^,]+}}) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // Check that the offloading functions are emitted and that the parallel function // is appropriately guarded. // CHECK: define internal void [[HVT1]]([[S1]]* {{%.+}}, i[[SZ]] [[PARM1:%.+]], i[[SZ]] [[PARM2:%.+]]) // CHECK-DAG: store i[[SZ]] [[PARM1]], i[[SZ]]* [[B_ADDR:%.+]], align // CHECK-DAG: store i[[SZ]] [[PARM2]], i[[SZ]]* [[CAPE_ADDR:%.+]], align // CHECK-64: [[CONVB:%.+]] = bitcast i[[SZ]]* [[B_ADDR]] to i32* // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPE_ADDR]] to i8* // CHECK-64: [[BV:%.+]] = load i32, i32* [[CONVB]], align // CHECK-32: [[BV:%.+]] = load i32, i32* [[B_ADDR]], align // CHECK-64: [[BC:%.+]] = bitcast i64* [[ARGA:%.+]] to i32* // CHECK-64: store i32 [[BV]], i32* [[BC]], align // CHECK-64: [[ARG:%.+]] = load i[[SZ]], i[[SZ]]* [[ARGA]], align // CHECK-32: store i32 [[BV]], i32* [[ARGA:%.+]], align // CHECK-32: [[ARG:%.+]] = load i[[SZ]], i[[SZ]]* [[ARGA]], align // CHECK: [[IFC:%.+]] = load i8, i8* [[CONV]], align // CHECK: [[TB:%.+]] = trunc i8 [[IFC]] to i1 // CHECK: br i1 [[TB]], label {{%?}}[[IF_THEN:.+]], label {{%?}}[[IF_ELSE:.+]] // // CHECK: [[IF_THEN]] // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 2, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, [[S1]]*, i[[SZ]])* [[OMP_OUTLINED3:@.+]] to void (i32*, i32*, ...)*), [[S1]]* {{.+}}, i[[SZ]] [[ARG]]) // CHECK: br label {{%?}}[[END:.+]] // // CHECK: [[IF_ELSE]] // CHECK: call void @__kmpc_serialized_parallel( // CHECK: call void [[OMP_OUTLINED3]](i32* {{%.+}}, i32* {{%.+}}, [[S1]]* {{.+}}, i[[SZ]] [[ARG]]) // CHECK: call void @__kmpc_end_serialized_parallel( // CHECK: br label {{%?}}[[END]] // // CHECK: [[END]] // // // CHECK: define internal void [[HVT2]]([[S1]]* {{%.+}}, i[[SZ]] [[PARM:%.+]]) // CHECK-DAG: store i[[SZ]] [[PARM]], i[[SZ]]* [[CAPE_ADDR:%.+]], align // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPE_ADDR]] to i8* // CHECK: [[IFC:%.+]] = load i8, i8* [[CONV]], align // CHECK: [[TB:%.+]] = trunc i8 [[IFC]] to i1 // CHECK: br i1 [[TB]], label {{%?}}[[IF_THEN:.+]], label {{%?}}[[IF_ELSE:.+]] // // CHECK: [[IF_THEN]] // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 1, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, [[S1]]*)* [[OMP_OUTLINED4:@.+]] to void (i32*, i32*, ...)*), [[S1]]* {{.+}}) // CHECK: br label {{%?}}[[END:.+]] // // CHECK: [[IF_ELSE]] // CHECK: call void @__kmpc_serialized_parallel( // CHECK: call void [[OMP_OUTLINED4]](i32* {{%.+}}, i32* {{%.+}}, [[S1]]* {{.+}}) // CHECK: call void @__kmpc_end_serialized_parallel( // CHECK: br label {{%?}}[[END]] // // CHECK: [[END]] // // // CHECK: define internal void [[HVT3]](i[[SZ]] [[PARM:%.+]]) // CHECK-DAG: store i[[SZ]] [[PARM]], i[[SZ]]* [[CAPE_ADDR:%.+]], align // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPE_ADDR]] to i8* // CHECK: [[IFC:%.+]] = load i8, i8* [[CONV]], align // CHECK: [[TB:%.+]] = trunc i8 [[IFC]] to i1 // CHECK: br i1 [[TB]], label {{%?}}[[IF_THEN:.+]], label {{%?}}[[IF_ELSE:.+]] // // CHECK: [[IF_THEN]] // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* [[OMP_OUTLINED1:@.+]] to void (i32*, i32*, ...)*)) // CHECK: br label {{%?}}[[END:.+]] // // CHECK: [[IF_ELSE]] // CHECK: call void @__kmpc_serialized_parallel( // CHECK: call void [[OMP_OUTLINED1]](i32* {{%.+}}, i32* {{%.+}}) // CHECK: call void @__kmpc_end_serialized_parallel( // CHECK: br label {{%?}}[[END]] // // CHECK: [[END]] // // // CHECK: define internal void [[HVT4]]() // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 0, void (i32*, i32*, ...)* bitcast (void (i32*, i32*)* [[OMP_OUTLINED2:@.+]] to void (i32*, i32*, ...)*)) // CHECK-NEXT: ret // // // CHECK: define internal void [[HVT5]]( // CHECK-NOT: @__kmpc_fork_call // CHECK: call void @__kmpc_serialized_parallel( // CHECK: call void [[OMP_OUTLINED5:@.+]](i32* {{%.+}}, i32* {{%.+}}, i[[SZ]] {{.+}}) // CHECK: call void @__kmpc_end_serialized_parallel( // CHECK: ret // // // CHECK: define internal void [[HVT6]]( // CHECK-NOT: call void @__kmpc_serialized_parallel( // CHECK-NOT: call void [[OMP_OUTLINED5:@.+]](i32* {{%.+}}, i32* {{%.+}}, i[[SZ]] {{.+}}) // CHECK-NOT: call void @__kmpc_end_serialized_parallel( // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_call(%ident_t* [[DEF_LOC]], i32 2, void (i32*, i32*, ...)* bitcast (void (i32*, i32*, i[[SZ]], i[[SZ]])* [[OMP_OUTLINED5:@.+]] to void (i32*, i32*, ...)*), // CHECK: ret // // #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_distribute_parallel_for_simd_aligned_messages.cpp
231
// RUN: %clang_cc1 -x c++ -std=c++11 -verify -fopenmp %s struct B { static int ib[20]; // expected-note 0 {{'B::ib' declared here}} static constexpr int bfoo() { return 8; } }; namespace X { B x; // expected-note {{'x' defined here}} }; constexpr int bfoo() { return 4; } int **z; const int C1 = 1; const int C2 = 2; void test_aligned_colons(int *&rp) { int *B = 0; #pragma omp target teams distribute parallel for simd aligned(B:bfoo()) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(B::ib:B:bfoo()) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(B:B::bfoo()) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(z:B:bfoo()) // expected-error {{unexpected ':' in nested name specifier; did you mean '::'?}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(B:B::bfoo()) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(X::x : ::z) // expected-error {{integral constant expression must have integral or unscoped enumeration type, not 'int **'}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'B'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(B,rp,::z: X::x) // expected-error {{integral constant expression must have integral or unscoped enumeration type, not 'B'}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(::z) for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(B::bfoo()) // expected-error {{expected variable name}} for (int i = 0; i < 10; ++i) ; #pragma omp target teams distribute parallel for simd aligned(B::ib,B:C1+C2) // expected-warning {{aligned clause will be ignored because the requested alignment is not a power of 2}} for (int i = 0; i < 10; ++i) ; } // expected-note@+1 {{'num' defined here}} template<int L, class T, class N> T test_template(T* arr, N num) { N i; T sum = (T)0; T ind2 = - num * L; // Negative number is passed as L. #pragma omp target teams distribute parallel for simd aligned(arr:L) // expected-error {{argument to 'aligned' clause must be a strictly positive integer value}} for (i = 0; i < num; ++i) { T cur = arr[(int)ind2]; ind2 += L; sum += cur; } #pragma omp target teams distribute parallel for simd aligned(num:4) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}} for (i = 0; i < num; ++i); return T(); } template<int LEN> int test_warn() { int *ind2 = 0; #pragma omp target teams distribute parallel for simd aligned(ind2:LEN) // expected-error {{argument to 'aligned' clause must be a strictly positive integer value}} for (int i = 0; i < 100; i++) { ind2 += LEN; } return 0; } struct S1; // expected-note 2 {{declared here}} extern S1 a; // expected-note {{'a' declared here}} class S2 { mutable int a; public: S2():a(0) { } }; const S2 b; // expected-note 1 {{'b' defined here}} const S2 ba[5]; class S3 { int a; public: S3():a(0) { } }; const S3 ca[5]; class S4 { int a; S4(); public: S4(int v):a(v) { } }; class S5 { int a; S5():a(0) {} public: S5(int v):a(v) { } }; S3 h; // expected-note 2 {{'h' defined here}} #pragma omp threadprivate(h) template<class I, class C> int foomain(I argc, C **argv) { I e(argc); I g(argc); int i; // expected-note {{declared here}} expected-note {{'i' defined here}} // expected-note@+2 {{declared here}} // expected-note@+1 {{reference to 'i' is not a constant expression}} int &j = i; #pragma omp target teams distribute parallel for simd aligned // expected-error {{expected '(' after 'aligned'}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned () // expected-error {{expected expression}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (I k = 0; k < argc; ++k) ++k; // FIXME: Should argc really be a pointer? #pragma omp target teams distribute parallel for simd aligned (*argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (argc : 5) // expected-warning {{aligned clause will be ignored because the requested alignment is not a power of 2}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (S1) // expected-error {{'S1' does not refer to a value}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (argv[1]) // expected-error {{expected variable name}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned(e, g) for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned(h) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S3'}} for (I k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned(i) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}} for (I k = 0; k < argc; ++k) ++k; #pragma omp parallel { int *v = 0; I i; #pragma omp target teams distribute parallel for simd aligned(v:16) for (I k = 0; k < argc; ++k) { i = k; v += 2; } } float *f; #pragma omp target teams distribute parallel for simd aligned(f) for (I k = 0; k < argc; ++k) ++k; int v = 0; #pragma omp target teams distribute parallel for simd aligned(f:j) // expected-note {{initializer of 'j' is not a constant expression}} expected-error {{expression is not an integral constant expression}} for (I k = 0; k < argc; ++k) { ++k; v += j; } #pragma omp target teams distribute parallel for simd aligned(f) for (I k = 0; k < argc; ++k) ++k; return 0; } // expected-note@+1 2 {{'argc' defined here}} int main(int argc, char **argv) { double darr[100]; // expected-note@+1 {{in instantiation of function template specialization 'test_template<-4, double, int>' requested here}} test_template<-4>(darr, 4); test_warn<4>(); // ok // expected-note@+1 {{in instantiation of function template specialization 'test_warn<0>' requested here}} test_warn<0>(); int i; int &j = i; #pragma omp target teams distribute parallel for simd aligned // expected-error {{expected '(' after 'aligned'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned () // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (argv // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams #pragma omp distribute simd aligned (argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams #pragma omp distribute simd aligned (argc) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'int'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (a, b) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S1'}} expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S2'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned (argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp target teams distribute parallel for simd aligned(h) // expected-error {{argument of aligned clause should be array, pointer, reference to array or reference to pointer, not 'S3'}} for (int k = 0; k < argc; ++k) ++k; int *pargc = &argc; // expected-note@+1 {{in instantiation of function template specialization 'foomain<int *, char>' requested here}} foomain<int*,char>(pargc,argv); return 0; }
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_thread_limit_codegen.cpp
357
// Test host codegen. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix CHECK --check-prefix CHECK-32 // Test target codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-64 // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32 // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s --check-prefix TCHECK --check-prefix TCHECK-32 // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-DAG: %ident_t = type { i32, i32, i32, i32, i8* } // CHECK-DAG: [[STR:@.+]] = private unnamed_addr constant [23 x i8] c";unknown;unknown;0;0;;\00" // CHECK-DAG: [[DEF_LOC:@.+]] = private unnamed_addr constant %ident_t { i32 0, i32 2, i32 0, i32 0, i8* getelementptr inbounds ([23 x i8], [23 x i8]* [[STR]], i32 0, i32 0) } // CHECK-DAG: [[S1:%.+]] = type { double } // CHECK-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 } // CHECK-DAG: [[DEVTY:%.+]] = type { i8*, i8*, [[ENTTY]]*, [[ENTTY]]* } // CHECK-DAG: [[DSCTY:%.+]] = type { i32, [[DEVTY]]*, [[ENTTY]]*, [[ENTTY]]* } // TCHECK: [[ENTTY:%.+]] = type { i8*, i8*, i{{32|64}}, i32, i32 } // We have 6 target regions // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // CHECK-DAG: @{{.*}} = private constant i8 0 // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // TCHECK: @{{.+}} = constant [[ENTTY]] // Check if offloading descriptor is created. // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] // CHECK: [[DEVBEGIN:@.+]] = external constant i8 // CHECK: [[DEVEND:@.+]] = external constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }] // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] } // Check target registration is registered as a Ctor. // CHECK: appending global [1 x { i32, void ()*, i8* }] [{ i32, void ()*, i8* } { i32 0, void ()* bitcast (void (i8*)* [[REGFN:@.+]] to void ()*), i8* null }] template<typename tx> tx ftemplate(int n) { tx a = 0; #pragma omp target teams thread_limit(tx(20)) { } short b = 1; #pragma omp target teams num_teams(b) thread_limit(1024) { a += b; } return a; } static int fstatic(int n) { #pragma omp target teams num_teams(n) thread_limit(n*32) { } #pragma omp target teams thread_limit(32+n) { } return n+1; } struct S1 { double a; int r1(int n){ int b = 1; #pragma omp target teams thread_limit(n-b) { this->a = (double)b + 1.5; } #pragma omp target teams thread_limit(1024) { this->a = 2.5; } return (int)a; } }; // CHECK: define {{.*}}@{{.*}}bar{{.*}} int bar(int n){ int a = 0; S1 S; // CHECK: call {{.*}}i32 [[FS1:@.+]]([[S1]]* {{.*}}, i32 {{.*}}) a += S.r1(n); // CHECK: call {{.*}}i32 [[FSTATIC:@.+]](i32 {{.*}}) a += fstatic(n); // CHECK: call {{.*}}i32 [[FTEMPLATE:@.+]](i32 {{.*}}) a += ftemplate<int>(n); return a; } // // CHECK: define {{.*}}[[FS1]]([[S1]]* {{%.+}}, i32 {{[^%]*}}[[PARM:%.+]]) // // CHECK-DAG: store i32 [[PARM]], i32* [[N_ADDR:%.+]], align // CHECK: store i32 1, i32* [[B:%.+]], align // CHECK: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: [[BV:%.+]] = load i32, i32* [[B]], align // CHECK: [[SUB:%.+]] = sub nsw i32 [[NV]], [[BV]] // CHECK: store i32 [[SUB]], i32* [[CAPE_ADDR:%.+]], align // CHECK: [[CEV:%.+]] = load i32, i32* [[CAPE_ADDR]], align // CHECK-64: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPEC_ADDR:%.+]] to i32* // CHECK-64: store i32 [[CEV]], i32* [[CONV]], align // CHECK-32: store i32 [[CEV]], i32* [[CAPEC_ADDR:%.+]], align // CHECK: [[ARG:%.+]] = load i[[SZ]], i[[SZ]]* [[CAPEC_ADDR]], align // CHECK: [[TL:%.+]] = load i32, i32* [[CAPE_ADDR]], align // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 3, {{.*}}, i32 0, i32 [[TL]]) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT1:@.+]]([[S1]]* {{%.+}}, i[[SZ]] {{%.+}}, i[[SZ]] [[ARG]]) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 1, {{.+}}, i32 0, i32 1024) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT2:@.+]]([[S1]]* {{[^,]+}}) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // // CHECK: define {{.*}}[[FSTATIC]](i32 {{[^%]*}}[[PARM:%.+]]) // // CHECK-DAG: store i32 [[PARM]], i32* [[N_ADDR:%.+]], align // CHECK: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: store i32 [[NV]], i32* [[CAPE_ADDR1:%.+]], align // CHECK: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: [[MUL:%.+]] = mul nsw i32 [[NV]], 32 // CHECK: store i32 [[MUL]], i32* [[CAPE_ADDR2:%.+]], align // CHECK: [[CEV:%.+]] = load i32, i32* [[CAPE_ADDR1]], align // CHECK-64: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPEC_ADDR1:%.+]] to i32* // CHECK-64: store i32 [[CEV]], i32* [[CONV]], align // CHECK-32: store i32 [[CEV]], i32* [[CAPEC_ADDR1:%.+]], align // CHECK: [[ARG1:%.+]] = load i[[SZ]], i[[SZ]]* [[CAPEC_ADDR1]], align // CHECK: [[CEV:%.+]] = load i32, i32* [[CAPE_ADDR2]], align // CHECK-64: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPEC_ADDR2:%.+]] to i32* // CHECK-64: store i32 [[CEV]], i32* [[CONV]], align // CHECK-32: store i32 [[CEV]], i32* [[CAPEC_ADDR2:%.+]], align // CHECK: [[ARG2:%.+]] = load i[[SZ]], i[[SZ]]* [[CAPEC_ADDR2]], align // CHECK: [[TEAMS:%.+]] = load i32, i32* [[CAPE_ADDR1]], align // CHECK: [[TL:%.+]] = load i32, i32* [[CAPE_ADDR2]], align // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 2, {{.*}}, i32 [[TEAMS]], i32 [[TL]]) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT3:@.+]](i[[SZ]] [[ARG1]], i[[SZ]] [[ARG2]]) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // // // CHECK: [[NV:%.+]] = load i32, i32* [[N_ADDR]], align // CHECK: [[ADD:%.+]] = add nsw i32 32, [[NV]] // CHECK: store i32 [[ADD]], i32* [[CAPE_ADDR:%.+]], align // CHECK: [[CEV:%.+]] = load i32, i32* [[CAPE_ADDR]], align // CHECK-64: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPEC_ADDR:%.+]] to i32* // CHECK-64: store i32 [[CEV]], i32* [[CONV]], align // CHECK-32: store i32 [[CEV]], i32* [[CAPEC_ADDR:%.+]], align // CHECK: [[ARG:%.+]] = load i[[SZ]], i[[SZ]]* [[CAPEC_ADDR]], align // CHECK: [[TL:%.+]] = load i32, i32* [[CAPE_ADDR]], align // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 1, {{.*}}, i32 0, i32 [[TL]]) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT4:@.+]](i[[SZ]] [[ARG]]) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // // CHECK: define {{.*}}[[FTEMPLATE]] // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 0, {{.*}}, i32 0, i32 20) // CHECK-NEXT: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK-NEXT: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK-NEXT: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK-NEXT: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT5:@.+]]() // CHECK: br label {{%?}}[[END]] // // CHECK: [[END]] // // // // CHECK: store i16 1, i16* [[B:%.+]], align // CHECK: [[BV:%.+]] = load i16, i16* [[B]], align // CHECK: store i16 [[BV]], i16* [[CAPE_ADDR:%.+]], align // CHECK: [[CEV:%.+]] = load i16, i16* [[CAPE_ADDR]], align // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPEC_ADDR:%.+]] to i16* // CHECK: store i16 [[CEV]], i16* [[CONV]], align // CHECK: [[ARG:%.+]] = load i[[SZ]], i[[SZ]]* [[CAPEC_ADDR]], align // CHECK: [[T:%.+]] = load i16, i16* [[CAPE_ADDR]], align // CHECK: [[TEAMS:%.+]] = sext i16 [[T]] to i32 // // CHECK-DAG: [[RET:%.+]] = call i32 @__tgt_target_teams(i32 -1, i8* @{{[^,]+}}, i32 3, {{.*}}, i32 [[TEAMS]], i32 1024) // CHECK: store i32 [[RET]], i32* [[RHV:%.+]], align // CHECK: [[RET2:%.+]] = load i32, i32* [[RHV]], align // CHECK: [[ERROR:%.+]] = icmp ne i32 [[RET2]], 0 // CHECK: br i1 [[ERROR]], label %[[FAIL:.+]], label %[[END:[^,]+]] // // CHECK: [[FAIL]] // CHECK: call void [[HVT6:@.+]](i[[SZ]] {{%.+}}, i[[SZ]] {{%.+}}, i[[SZ]] [[ARG]]) // CHECK: br label {{%?}}[[END]] // CHECK: [[END]] // // Check that the offloading functions are emitted and that the parallel function // is appropriately guarded. // CHECK: define internal void [[HVT1]]([[S1]]* {{%.+}}, i[[SZ]] [[PARM1:%.+]], i[[SZ]] [[PARM2:%.+]]) // CHECK-DAG: store i[[SZ]] [[PARM2]], i[[SZ]]* [[CAPE_ADDR:%.+]], align // CHECK-64: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPE_ADDR]] to i32* // CHECK-64: [[TL:%.+]] = load i32, i32* [[CONV]], align // CHECK-32: [[TL:%.+]] = load i32, i32* [[CAPE_ADDR]], align // CHECK: call i32 @__kmpc_push_num_teams(%ident_t* {{[^,]+}}, i32 {{[^,]+}}, i32 0, i32 [[TL]]) // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 2, // // // CHECK: define internal void [[HVT2]]([[S1]]* {{%.+}}) // CHECK: call i32 @__kmpc_push_num_teams(%ident_t* {{[^,]+}}, i32 {{[^,]+}}, i32 0, i32 1024) // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 1, // // // CHECK: define internal void [[HVT3]](i[[SZ]] [[PARM1:%.+]], i[[SZ]] [[PARM2:%.+]]) // CHECK-DAG: store i[[SZ]] [[PARM1]], i[[SZ]]* [[CAPE_ADDR1:%.+]], align // CHECK-DAG: store i[[SZ]] [[PARM2]], i[[SZ]]* [[CAPE_ADDR2:%.+]], align // CHECK-64: [[CONV1:%.+]] = bitcast i[[SZ]]* [[CAPE_ADDR1]] to i32* // CHECK-64: [[CONV2:%.+]] = bitcast i[[SZ]]* [[CAPE_ADDR2]] to i32* // CHECK-64: [[NT:%.+]] = load i32, i32* [[CONV1]], align // CHECK-64: [[TL:%.+]] = load i32, i32* [[CONV2]], align // CHECK-32: [[NT:%.+]] = load i32, i32* [[CAPE_ADDR1]], align // CHECK-32: [[TL:%.+]] = load i32, i32* [[CAPE_ADDR2]], align // CHECK: call i32 @__kmpc_push_num_teams(%ident_t* {{[^,]+}}, i32 {{[^,]+}}, i32 [[NT]], i32 [[TL]]) // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 0, // // // CHECK: define internal void [[HVT4]](i[[SZ]] [[PARM:%.+]]) // CHECK-DAG: store i[[SZ]] [[PARM]], i[[SZ]]* [[CAPE_ADDR:%.+]], align // CHECK-64: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPE_ADDR]] to i32* // CHECK-64: [[TL:%.+]] = load i32, i32* [[CONV]], align // CHECK-32: [[TL:%.+]] = load i32, i32* [[CAPE_ADDR]], align // CHECK: call i32 @__kmpc_push_num_teams(%ident_t* {{[^,]+}}, i32 {{[^,]+}}, i32 0, i32 [[TL]]) // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 0, // // // CHECK: define internal void [[HVT5]]( // CHECK: call i32 @__kmpc_push_num_teams(%ident_t* {{[^,]+}}, i32 {{[^,]+}}, i32 0, i32 20) // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 0, // // // CHECK: define internal void [[HVT6]](i[[SZ]] [[PARM1:%.+]], i[[SZ]] [[PARM2:%.+]], i[[SZ]] [[PARM3:%.+]]) // CHECK-DAG: store i[[SZ]] [[PARM3]], i[[SZ]]* [[CAPE_ADDR:%.+]], align // CHECK: [[CONV:%.+]] = bitcast i[[SZ]]* [[CAPE_ADDR]] to i16* // CHECK: [[T:%.+]] = load i16, i16* [[CONV]], align // CHECK: [[NT:%.+]] = sext i16 [[T]] to i32 // CHECK: call i32 @__kmpc_push_num_teams(%ident_t* {{[^,]+}}, i32 {{[^,]+}}, i32 [[NT]], i32 1024) // CHECK: call {{.*}}void (%ident_t*, i32, void (i32*, i32*, ...)*, ...) @__kmpc_fork_teams(%ident_t* [[DEF_LOC]], i32 2, // // #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1
test/OpenMP/target_teams_codegen_registration.cpp
437
// Test host codegen. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s // Test target teams codegen - host bc file has to be created first. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm-bc %s -o %t-ppc-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - | FileCheck %s -check-prefix=TCHECK // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s -check-prefix=TCHECK // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm-bc %s -o %t-x86-host.bc // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o - | FileCheck %s -check-prefix=TCHECK // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -o %t %s // RUN: %clang_cc1 -fopenmp -fopenmp-version=45 -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -fopenmp-is-device -fopenmp-host-ir-file-path %t-x86-host.bc -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s -check-prefix=TCHECK // Check that no target code is emmitted if no omptests flag was provided. // RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=45 -x c++ -triple powerpc64le-unknown-unknown -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK-NTARGET // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-DAG: [[SA:%.+]] = type { [4 x i32] } // CHECK-DAG: [[SB:%.+]] = type { [8 x i32] } // CHECK-DAG: [[SC:%.+]] = type { [16 x i32] } // CHECK-DAG: [[SD:%.+]] = type { [32 x i32] } // CHECK-DAG: [[SE:%.+]] = type { [64 x i32] } // CHECK-DAG: [[ST1:%.+]] = type { [228 x i32] } // CHECK-DAG: [[ST2:%.+]] = type { [1128 x i32] } // CHECK-DAG: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 } // CHECK-DAG: [[DEVTY:%.+]] = type { i8*, i8*, [[ENTTY]]*, [[ENTTY]]* } // CHECK-DAG: [[DSCTY:%.+]] = type { i32, [[DEVTY]]*, [[ENTTY]]*, [[ENTTY]]* } // TCHECK: [[ENTTY:%.+]] = type { i8*, i8*, i[[SZ:32|64]], i32, i32 } // CHECK-DAG: [[A1:@.+]] = internal global [[SA]] // CHECK-DAG: [[A2:@.+]] = global [[SA]] // CHECK-DAG: [[B1:@.+]] = global [[SB]] // CHECK-DAG: [[B2:@.+]] = global [[SB]] // CHECK-DAG: [[C1:@.+]] = internal global [[SC]] // CHECK-DAG: [[D1:@.+]] = global [[SD]] // CHECK-DAG: [[E1:@.+]] = global [[SE]] // CHECK-DAG: [[T1:@.+]] = global [[ST1]] // CHECK-DAG: [[T2:@.+]] = global [[ST2]] // CHECK-NTARGET-DAG: [[SA:%.+]] = type { [4 x i32] } // CHECK-NTARGET-DAG: [[SB:%.+]] = type { [8 x i32] } // CHECK-NTARGET-DAG: [[SC:%.+]] = type { [16 x i32] } // CHECK-NTARGET-DAG: [[SD:%.+]] = type { [32 x i32] } // CHECK-NTARGET-DAG: [[SE:%.+]] = type { [64 x i32] } // CHECK-NTARGET-DAG: [[ST1:%.+]] = type { [228 x i32] } // CHECK-NTARGET-DAG: [[ST2:%.+]] = type { [1128 x i32] } // CHECK-NTARGET-NOT: type { i8*, i8*, % // CHECK-NTARGET-NOT: type { i32, % // We have 7 target regions // CHECK-DAG: {{@.+}} = private constant i8 0 // TCHECK-NOT: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-DAG: {{@.+}} = private constant i8 0 // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i[[SZ]]] [i[[SZ]] 4] // CHECK-DAG: {{@.+}} = private unnamed_addr constant [1 x i32] [i32 288] // CHECK-NTARGET-NOT: private constant i8 0 // CHECK-NTARGET-NOT: private unnamed_addr constant [1 x i // CHECK-DAG: [[NAMEPTR1:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME1:__omp_offloading_[0-9a-f]+_[0-9a-f]+__Z.+_l[0-9]+]]\00" // CHECK-DAG: [[ENTRY1:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR1]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR2:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME2:.+]]\00" // CHECK-DAG: [[ENTRY2:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR2]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR3:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME3:.+]]\00" // CHECK-DAG: [[ENTRY3:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR3]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR4:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME4:.+]]\00" // CHECK-DAG: [[ENTRY4:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR4]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR5:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME5:.+]]\00" // CHECK-DAG: [[ENTRY5:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR5]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR6:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME6:.+]]\00" // CHECK-DAG: [[ENTRY6:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR6]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR7:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME7:.+]]\00" // CHECK-DAG: [[ENTRY7:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR7]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR8:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME8:.+]]\00" // CHECK-DAG: [[ENTRY8:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR8]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR9:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME9:.+]]\00" // CHECK-DAG: [[ENTRY9:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR9]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR10:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME10:.+]]\00" // CHECK-DAG: [[ENTRY10:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR10]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR11:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME11:.+]]\00" // CHECK-DAG: [[ENTRY11:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR11]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK-DAG: [[NAMEPTR12:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME12:.+]]\00" // CHECK-DAG: [[ENTRY12:@.+]] = constant [[ENTTY]] { i8* @{{.*}}, i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR12]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR1:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME1:__omp_offloading_[0-9a-f]+_[0-9a-f]+__Z.+_l[0-9]+]]\00" // TCHECK-DAG: [[ENTRY1:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR1]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR2:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME2:.+]]\00" // TCHECK-DAG: [[ENTRY2:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR2]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR3:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME3:.+]]\00" // TCHECK-DAG: [[ENTRY3:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR3]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR4:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME4:.+]]\00" // TCHECK-DAG: [[ENTRY4:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR4]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR5:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME5:.+]]\00" // TCHECK-DAG: [[ENTRY5:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR5]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR6:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME6:.+]]\00" // TCHECK-DAG: [[ENTRY6:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR6]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR7:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME7:.+]]\00" // TCHECK-DAG: [[ENTRY7:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR7]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR8:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME8:.+]]\00" // TCHECK-DAG: [[ENTRY8:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR8]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR9:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME9:.+]]\00" // TCHECK-DAG: [[ENTRY9:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR9]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR10:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME10:.+]]\00" // TCHECK-DAG: [[ENTRY10:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR10]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR11:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME11:.+]]\00" // TCHECK-DAG: [[ENTRY11:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR11]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // TCHECK-DAG: [[NAMEPTR12:@.+]] = internal unnamed_addr constant [{{.*}} x i8] c"[[NAME12:.+]]\00" // TCHECK-DAG: [[ENTRY12:@.+]] = constant [[ENTTY]] { i8* bitcast (void (i[[SZ]])* @{{.*}} to i8*), i8* getelementptr inbounds ([{{.*}} x i8], [{{.*}} x i8]* [[NAMEPTR12]], i32 0, i32 0), i[[SZ]] 0, i32 0, i32 0 }, section ".omp_offloading.entries", align 1 // CHECK: [[ENTBEGIN:@.+]] = external constant [[ENTTY]] // CHECK: [[ENTEND:@.+]] = external constant [[ENTTY]] // CHECK: [[DEVBEGIN:@.+]] = external constant i8 // CHECK: [[DEVEND:@.+]] = external constant i8 // CHECK: [[IMAGES:@.+]] = internal unnamed_addr constant [1 x [[DEVTY]]] [{{.+}} { i8* [[DEVBEGIN]], i8* [[DEVEND]], [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] }] // CHECK: [[DESC:@.+]] = internal constant [[DSCTY]] { i32 1, [[DEVTY]]* getelementptr inbounds ([1 x [[DEVTY]]], [1 x [[DEVTY]]]* [[IMAGES]], i32 0, i32 0), [[ENTTY]]* [[ENTBEGIN]], [[ENTTY]]* [[ENTEND]] } // We have 4 initializers, one for the 500 priority, another one for 501, or more for the default priority, and the last one for the offloading registration function. // CHECK: @llvm.global_ctors = appending global [4 x { i32, void ()*, i8* }] [ // CHECK-SAME: { i32, void ()*, i8* } { i32 500, void ()* [[P500:@[^,]+]], i8* null }, // CHECK-SAME: { i32, void ()*, i8* } { i32 501, void ()* [[P501:@[^,]+]], i8* null }, // CHECK-SAME: { i32, void ()*, i8* } { i32 65535, void ()* [[PMAX:@[^,]+]], i8* null }, // CHECK-SAME: { i32, void ()*, i8* } { i32 0, void ()* bitcast (void (i8*)* [[REGFN:@.+]] to void ()*), i8* null }] // CHECK-NTARGET: @llvm.global_ctors = appending global [3 x { i32, void ()*, i8* }] [ extern int *R; struct SA { int arr[4]; void foo() { int a = *R; a += 1; *R = a; } SA() { int a = *R; a += 2; *R = a; } ~SA() { int a = *R; a += 3; *R = a; } }; struct SB { int arr[8]; void foo() { int a = *R; #pragma omp target teams a += 4; *R = a; } SB() { int a = *R; a += 5; *R = a; } ~SB() { int a = *R; a += 6; *R = a; } }; struct SC { int arr[16]; void foo() { int a = *R; a += 7; *R = a; } SC() { int a = *R; #pragma omp target teams a += 8; *R = a; } ~SC() { int a = *R; a += 9; *R = a; } }; struct SD { int arr[32]; void foo() { int a = *R; a += 10; *R = a; } SD() { int a = *R; a += 11; *R = a; } ~SD() { int a = *R; #pragma omp target teams a += 12; *R = a; } }; struct SE { int arr[64]; void foo() { int a = *R; #pragma omp target teams if(target: 0) a += 13; *R = a; } SE() { int a = *R; #pragma omp target teams a += 14; *R = a; } ~SE() { int a = *R; #pragma omp target teams a += 15; *R = a; } }; template <int x> struct ST { int arr[128 + x]; void foo() { int a = *R; #pragma omp target teams a += 16 + x; *R = a; } ST() { int a = *R; #pragma omp target teams a += 17 + x; *R = a; } ~ST() { int a = *R; #pragma omp target teams a += 18 + x; *R = a; } }; // We have to make sure we us all the target regions: //CHECK-DAG: define internal void @[[NAME1]]( //CHECK-DAG: call void @[[NAME1]]( //CHECK-DAG: define internal void @[[NAME2]]( //CHECK-DAG: call void @[[NAME2]]( //CHECK-DAG: define internal void @[[NAME3]]( //CHECK-DAG: call void @[[NAME3]]( //CHECK-DAG: define internal void @[[NAME4]]( //CHECK-DAG: call void @[[NAME4]]( //CHECK-DAG: define internal void @[[NAME5]]( //CHECK-DAG: call void @[[NAME5]]( //CHECK-DAG: define internal void @[[NAME6]]( //CHECK-DAG: call void @[[NAME6]]( //CHECK-DAG: define internal void @[[NAME7]]( //CHECK-DAG: call void @[[NAME7]]( //CHECK-DAG: define internal void @[[NAME8]]( //CHECK-DAG: call void @[[NAME8]]( //CHECK-DAG: define internal void @[[NAME9]]( //CHECK-DAG: call void @[[NAME9]]( //CHECK-DAG: define internal void @[[NAME10]]( //CHECK-DAG: call void @[[NAME10]]( //CHECK-DAG: define internal void @[[NAME11]]( //CHECK-DAG: call void @[[NAME11]]( //CHECK-DAG: define internal void @[[NAME12]]( //CHECK-DAG: call void @[[NAME12]]( //TCHECK-DAG: define void @[[NAME1]]( //TCHECK-DAG: define void @[[NAME2]]( //TCHECK-DAG: define void @[[NAME3]]( //TCHECK-DAG: define void @[[NAME4]]( //TCHECK-DAG: define void @[[NAME5]]( //TCHECK-DAG: define void @[[NAME6]]( //TCHECK-DAG: define void @[[NAME7]]( //TCHECK-DAG: define void @[[NAME8]]( //TCHECK-DAG: define void @[[NAME9]]( //TCHECK-DAG: define void @[[NAME10]]( //TCHECK-DAG: define void @[[NAME11]]( //TCHECK-DAG: define void @[[NAME12]]( // CHECK-NTARGET-NOT: __tgt_target // CHECK-NTARGET-NOT: __tgt_register_lib // CHECK-NTARGET-NOT: __tgt_unregister_lib // TCHECK-NOT: __tgt_target // TCHECK-NOT: __tgt_register_lib // TCHECK-NOT: __tgt_unregister_lib // We have 2 initializers with priority 500 //CHECK: define internal void [[P500]]( //CHECK: call void @{{.+}}() //CHECK: call void @{{.+}}() //CHECK-NOT: call void @{{.+}}() //CHECK: ret void // We have 1 initializers with priority 501 //CHECK: define internal void [[P501]]( //CHECK: call void @{{.+}}() //CHECK-NOT: call void @{{.+}}() //CHECK: ret void // We have 6 initializers with default priority //CHECK: define internal void [[PMAX]]( //CHECK: call void @{{.+}}() //CHECK: call void @{{.+}}() //CHECK: call void @{{.+}}() //CHECK: call void @{{.+}}() //CHECK: call void @{{.+}}() //CHECK: call void @{{.+}}() //CHECK-NOT: call void @{{.+}}() //CHECK: ret void // Check registration and unregistration //CHECK: define internal void [[UNREGFN:@.+]](i8*) //CHECK: call i32 @__tgt_unregister_lib([[DSCTY]]* [[DESC]]) //CHECK: ret void //CHECK: declare i32 @__tgt_unregister_lib([[DSCTY]]*) //CHECK: define internal void [[REGFN]](i8*) //CHECK: call i32 @__tgt_register_lib([[DSCTY]]* [[DESC]]) //CHECK: call i32 @__cxa_atexit(void (i8*)* [[UNREGFN]], i8* bitcast ([[DSCTY]]* [[DESC]] to i8*), //CHECK: ret void //CHECK: declare i32 @__tgt_register_lib([[DSCTY]]*) static __attribute__((init_priority(500))) SA a1; SA a2; SB __attribute__((init_priority(500))) b1; SB __attribute__((init_priority(501))) b2; static SC c1; SD d1; SE e1; ST<100> t1; ST<1000> t2; int bar(int a){ int r = a; a1.foo(); a2.foo(); b1.foo(); b2.foo(); c1.foo(); d1.foo(); e1.foo(); t1.foo(); t2.foo(); #pragma omp target teams ++r; return r + *R; } // Check metadata is properly generated: // CHECK: !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 193, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 243, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 259, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 265, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 276, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 282, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 402, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 288, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 282, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 288, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 276, i32 {{[0-9]+}}} // CHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SCC1Ev", i32 218, i32 {{[0-9]+}}} // TCHECK: !omp_offload.info = !{!{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}, !{{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID:-?[0-9]+]], i32 [[FILEID:-?[0-9]+]], !"_ZN2SB3fooEv", i32 193, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SDD1Ev", i32 243, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SEC1Ev", i32 259, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SED1Ev", i32 265, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EE3fooEv", i32 276, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EEC1Ev", i32 282, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_Z3bari", i32 402, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EED1Ev", i32 288, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EEC1Ev", i32 282, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi1000EED1Ev", i32 288, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2STILi100EE3fooEv", i32 276, i32 {{[0-9]+}}} // TCHECK-DAG: = !{i32 0, i32 [[DEVID]], i32 [[FILEID]], !"_ZN2SCC1Ev", i32 218, i32 {{[0-9]+}}} #endif
llvm-mirror_clang
2017-01-28
4c2a74ccfd6996fa95da8489e5fcb63aca18a4e1