diff --git a/cocos2d/core/graphics/earcut.js b/cocos2d/core/graphics/earcut.js new file mode 100644 index 0000000000..cf8daf2ebd --- /dev/null +++ b/cocos2d/core/graphics/earcut.js @@ -0,0 +1,644 @@ +'use strict'; + +module.exports = earcut; + +function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode) return triangles; + + var minX, minY, maxX, maxY, x, y, size; + + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY) maxY = y; + } + + // minX, minY and size are later used to transform coords into integers for z-order calculation + size = Math.max(maxX - minX, maxY - minY); + } + + earcutLinked(outerNode, triangles, dim, minX, minY, size); + + return triangles; +} + +// create a circular doubly linked list from polygon points in the specified winding order +function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; +} + +// eliminate colinear or duplicate points +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) return null; + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; +} + +// main ear slicing loop which triangulates a polygon (given as a linked list) +function earcutLinked(ear, triangles, dim, minX, minY, size, pass) { + if (!ear) return; + + // interlink polygon nodes in z-order + if (!pass && size) indexCurve(ear, minX, minY, size); + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim); + triangles.push(ear.i / dim); + triangles.push(next.i / dim); + + removeNode(ear); + + // skipping the next vertice leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(ear, triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, size, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, size); + } + + break; + } + } +} + +// check whether a polygon node forms a valid ear with adjacent nodes +function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var p = ear.next.next; + + while (p !== ear.prev) { + if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + + return true; +} + +function isEarHashed(ear, minX, minY, size) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) return false; // reflex, can't be an ear + + // triangle bbox; min & max are calculated like this for speed + var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), + minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), + maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), + maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); + + // z-order range for the current triangle bbox; + var minZ = zOrder(minTX, minTY, minX, minY, size), + maxZ = zOrder(maxTX, maxTY, minX, minY, size); + + // first look for points inside the triangle in increasing z-order + var p = ear.nextZ; + + while (p && p.z <= maxZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.nextZ; + } + + // then look for points in decreasing z-order + p = ear.prevZ; + + while (p && p.z >= minZ) { + if (p !== ear.prev && p !== ear.next && + pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && + area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + + return true; +} + +// go through all polygon nodes and cure small local self-intersections +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim); + triangles.push(p.i / dim); + triangles.push(b.i / dim); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return p; +} + +// try splitting polygon into two and triangulate them independently +function splitEarcut(start, triangles, dim, minX, minY, size) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, size); + earcutLinked(c, triangles, dim, minX, minY, size); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} + +// link every hole into the outer loop, producing a single-ring polygon without holes +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + eliminateHole(queue[i], outerNode); + outerNode = filterPoints(outerNode, outerNode.next); + } + + return outerNode; +} + +function compareX(a, b) { + return a.x - b.x; +} + +// find a bridge between vertices that connects hole with an outer ring and and link it +function eliminateHole(hole, outerNode) { + outerNode = findHoleBridge(hole, outerNode); + if (outerNode) { + var b = splitPolygon(outerNode, hole); + filterPoints(b, b.next); + } +} + +// David Eberly's algorithm for finding a bridge between hole and outer polygon +function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + if (x === hx) { + if (hy === p.y) return p; + if (hy === p.next.y) return p.next; + } + m = p.x < p.next.x ? p : p.next; + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) return null; + + if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m.next; + + while (p !== stop) { + if (hx >= p.x && p.x >= mx && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } + + return m; +} + +// interlink polygon nodes in z-order +function indexCurve(start, minX, minY, size) { + var p = start; + do { + if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); +} + +// Simon Tatham's linked list merge sort algorithm +// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize === 0) { + e = q; + q = q.nextZ; + qSize--; + } else if (qSize === 0 || !q) { + e = p; + p = p.nextZ; + pSize--; + } else if (p.z <= q.z) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) tail.nextZ = e; + else list = e; + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; +} + +// z-order of a point given coords and size of the data bounding box +function zOrder(x, y, minX, minY, size) { + // coords are transformed into non-negative 15-bit integer range + x = 32767 * (x - minX) / size; + y = 32767 * (y - minY) / size; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); +} + +// find the leftmost node of a polygon ring +function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x) leftmost = p; + p = p.next; + } while (p !== start); + + return leftmost; +} + +// check if a point lies within a convex triangle +function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && + (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && + (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; +} + +// check if a diagonal between two polygon nodes is valid (lies in polygon interior) +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && + locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b); +} + +// signed area of a triangle +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} + +// check if two points are equal +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} + +// check if two segments intersect +function intersects(p1, q1, p2, q2) { + if ((equals(p1, q1) && equals(p2, q2)) || + (equals(p1, q2) && equals(p2, q1))) return true; + return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && + area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0; +} + +// check if a polygon diagonal intersects any polygon segments +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + + return false; +} + +// check if a polygon diagonal is locally inside the polygon +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} + +// check if the middle point of a polygon diagonal is inside the polygon +function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + inside = !inside; + p = p.next; + } while (p !== a); + + return inside; +} + +// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; +// if one belongs to the outer ring and another to a hole, it merges it into a single ring +function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; +} + +// create a node and optionally link it with previous one (in a circular doubly linked list) +function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} + +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} + +function Node(i, x, y) { + // vertice index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertice nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = null; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; +} + +// return a percentage difference between the polygon area and its triangulation area; +// used to verify correctness of triangulation +earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); +}; + +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} + +// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts +earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; \ No newline at end of file diff --git a/cocos2d/core/graphics/graphics-canvas-cmd.js b/cocos2d/core/graphics/graphics-canvas-cmd.js new file mode 100644 index 0000000000..d55d57bb7b --- /dev/null +++ b/cocos2d/core/graphics/graphics-canvas-cmd.js @@ -0,0 +1,271 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + 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. + ****************************************************************************/ + +var Js = cc.js; + +var LineCap = require('./types').LineCap; +var LineJoin = require('./types').LineJoin; + +var PI = 3.14159265358979323846264338327; + +var min = Math.min; +var max = Math.max; +var cos = Math.cos; +var sin = Math.sin; +var abs = Math.abs; +var sign = Math.sign; + +var KAPPA90 = 0.5522847493; + +var CanvasRenderCmd = function (renderable) { + _ccsg.Node.CanvasRenderCmd.call(this, renderable); + this._needDraw = true; + this.cmds = []; +}; + +var _p = CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); +_p.constructor = CanvasRenderCmd; + +_p.rendering = function (ctx, scaleX, scaleY) { + var wrapper = ctx || cc._renderContext, context = wrapper.getContext(); + wrapper.setTransform(this._worldTransform, scaleX, scaleY); + + context.save(); + context.scale(scaleX, -scaleY); + + var endPath = true; + var cmds = this.cmds; + for (var i = 0, l = cmds.length; i < l; i++) { + var cmd = cmds[i]; + var ctxCmd = cmd[0], args = cmd[1]; + + if (ctxCmd === 'clear') { + cmds.splice(0, i+1); + i = 0; + return; + } + else if (ctxCmd === 'moveTo' && endPath) { + context.beginPath(); + endPath = false; + } + else if (ctxCmd === 'fill' || ctxCmd === 'stroke' || ctxCmd === 'fillRect') { + endPath = true; + } + + if (typeof context[ctxCmd] === 'function') { + context[ctxCmd].apply(context, args); + } + else { + context[ctxCmd] = args; + } + } + + context.restore(); +}; + +// draw api +Js.mixin(_p, { + setStrokeColor: function (v) { + var fillStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")"; + this.cmds.push(['strokeStyle', fillStyle]); + }, + + setFillColor: function (v) { + var fillStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")"; + this.cmds.push(['fillStyle', fillStyle]); + }, + + setLineWidth: function (v) { + this.cmds.push(['lineWidth', v]); + }, + + setLineCap: function (v) { + if (v === LineCap.BUTT) { + this.cmds.push(['lineCap', 'butt']); + } + else if (v === LineCap.ROUND) { + this.cmds.push(['lineCap', 'round']); + } + else if (v === LineCap.SQUARE) { + this.cmds.push(['lineCap', 'square']); + } + }, + + setLineJoin: function (v) { + if (v === LineJoin.BEVEL) { + this.cmds.push(['lineJoin', 'bevel']); + } + else if (v === LineJoin.ROUND) { + this.cmds.push(['lineJoin', 'round']); + } + else if (v === LineJoin.MITER) { + this.cmds.push(['lineJoin', 'miter']); + } + }, + + setMiterLimit: function (v) { + this.cmds.push(['miterLimit', v]); + }, + + // draw functions + + beginPath: function () { + }, + + moveTo: function (x, y) { + this.cmds.push(['moveTo', arguments]); + }, + + lineTo: function () { + this.cmds.push(['lineTo', arguments]); + }, + + bezierCurveTo: function () { + this.cmds.push(['bezierCurveTo', arguments]); + }, + + quadraticCurveTo: function () { + this.cmds.push(['quadraticCurveTo', arguments]); + }, + + // + arc: function (cx, cy, r, a0, a1, counterclockwise) { + // this.cmds.push(['arc', arguments]); + var a = 0, da = 0, hda = 0, kappa = 0; + var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; + var px = 0, py = 0, ptanx = 0, ptany = 0; + var i, ndivs; + + // Clamp angles + da = a1 - a0; + if (!counterclockwise) { + if (abs(da) >= PI * 2) { + da = PI * 2; + } else { + while (da < 0) da += PI * 2; + } + } else { + if (abs(da) >= PI * 2) { + da = -PI * 2; + } else { + while (da > 0) da -= PI * 2; + } + } + + // Split arc into max 90 degree segments. + ndivs = max(1, min(abs(da) / (PI * 0.5) + 0.5, 5)) | 0; + hda = da / ndivs / 2.0; + kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda)); + + if (counterclockwise) kappa = -kappa; + + for (i = 0; i <= ndivs; i++) { + a = a0 + da * (i / ndivs); + dx = cos(a); + dy = sin(a); + x = cx + dx * r; + y = cy + dy * r; + tanx = -dy * r * kappa; + tany = dx * r * kappa; + + if (i === 0) { + this.moveTo(x, y); + } else { + this.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y); + } + px = x; + py = y; + ptanx = tanx; + ptany = tany; + } + }, + + ellipse: function (cx, cy, rx, ry) { + this.moveTo(cx - rx, cy); + this.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry); + this.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy); + this.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry); + this.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy); + this.close(); + }, + + circle: function (cx, cy, r) { + this.ellipse(cx, cy, r, r); + this.close(); + }, + + rect: function (x, y, w, h) { + this.moveTo(x, y); + this.lineTo(x+w, y); + this.lineTo(x+w, y+h); + this.lineTo(x, y+h); + this.close(); + }, + + roundRect: function (x, y, w, h, r) { + if (r < 0.1) { + this.rect(x, y, w, h); + return; + } else { + var rx = min(r, abs(w) * 0.5) * sign(w), + ry = min(r, abs(h) * 0.5) * sign(h); + + this.moveTo(x, y + ry); + this.lineTo(x, y + h - ry); + this.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h); + this.lineTo(x + w - rx, y + h); + this.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry); + this.lineTo(x + w, y + ry); + this.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y); + this.lineTo(x + rx, y); + this.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry); + this.close(); + } + }, + + fillRect: function (x, y, w, h) { + this.cmds.push(['fillRect', arguments]); + }, + + close: function () { + this.cmds.push(['closePath', arguments]); + }, + + stroke: function () { + this.cmds.push(['stroke', arguments]); + }, + + fill: function () { + this.cmds.push(['fill', arguments]); + }, + + clear: function () { + this.cmds.push(['clear']); + } +}); + +var misc = require('../utils/misc'); +misc.propertyDefine(CanvasRenderCmd, ['lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'strokeColor', 'fillColor'], {}); + +module.exports = CanvasRenderCmd; diff --git a/cocos2d/core/graphics/graphics-node.js b/cocos2d/core/graphics/graphics-node.js new file mode 100644 index 0000000000..bfaacecddc --- /dev/null +++ b/cocos2d/core/graphics/graphics-node.js @@ -0,0 +1,171 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +var CanvasRenderCmd = require('./graphics-canvas-cmd'); +var WebGLRenderCmd = require('./graphics-webgl-cmd'); + +var LineCap = require('./types').LineCap; +var LineJoin = require('./types').LineJoin; + +var Js = cc.js; + +// GraphicsNode +var GraphicsNode = _ccsg.Node.extend({ + // constructor + ctor: function () { + this._super(); + + this.strokeColor = cc.Color.BLACK; + this.fillColor = cc.Color.WHITE; + }, + + // clear + clear: function (clean) { + this._renderCmd.clear(clean); + }, + + // extends functions + _createRenderCmd: function () { + if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) + return new CanvasRenderCmd(this); + else + return new WebGLRenderCmd(this); + } +}); + +var _p = GraphicsNode.prototype; + +// draw api +Js.mixin(_p, { + // properties + _strokeColor: null, + _fillColor: null, + + _lineWidth: 1, + + _lineCap: LineCap.BUTT, + _lineJoin: LineJoin.MITER, + + setStrokeColor: function (v) { + this._strokeColor = v; + this._renderCmd.strokeColor = v; + }, + getStrokeColor: function () { + return this._strokeColor; + }, + + setFillColor: function (v) { + this._fillColor = v; + this._renderCmd.fillColor = v; + }, + getFillColor: function () { + return this._fillColor; + }, + + setLineWidth: function (v) { + this._lineWidth = v; + this._renderCmd.lineWidth = v; + }, + getLineWidth: function () { + return this._lineWidth; + }, + + setLineCap: function (v) { + this._lineCap = v; + this._renderCmd.lineCap = v; + }, + getLineCap: function () { + return this._lineCap; + }, + + setLineJoin: function (v) { + this._lineJoin = v; + this._renderCmd.lineJoin = v; + }, + getLineJoin: function () { + return this._lineJoin; + }, + + // draw functions + + beginPath: function () { + this._renderCmd.beginPath(); + }, + + moveTo: function (x, y) { + this._renderCmd.moveTo(x, y); + }, + + lineTo: function (x, y) { + this._renderCmd.lineTo(x, y); + }, + + bezierCurveTo: function (c1x, c1y, c2x, c2y, x, y) { + this._renderCmd.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); + }, + + quadraticCurveTo: function (cx, cy, x, y) { + this._renderCmd.quadraticCurveTo(cx, cy, x, y); + }, + + // + arc: function (cx, cy, r, a0, a1, counterclockwise) { + this._renderCmd.arc(cx, cy, r, a0, a1, counterclockwise); + }, + + ellipse: function (cx, cy, rx, ry) { + this._renderCmd.ellipse(cx, cy, rx, ry); + }, + + circle: function (cx, cy, r) { + this._renderCmd.circle(cx, cy, r); + }, + + rect: function (x, y, w, h) { + this._renderCmd.rect(x, y, w, h); + }, + + roundRect: function (x, y, w, h, r) { + this._renderCmd.roundRect(x, y, w, h, r); + }, + + fillRect: function (x, y, w, h) { + this._renderCmd.fillRect(x, y, w, h); + }, + + close: function () { + this._renderCmd.close(); + }, + + stroke: function () { + this._renderCmd.stroke(); + }, + + fill: function () { + this._renderCmd.fill(); + } +}); + +module.exports = GraphicsNode; diff --git a/cocos2d/core/graphics/graphics-webgl-cmd.js b/cocos2d/core/graphics/graphics-webgl-cmd.js new file mode 100644 index 0000000000..3f5f4e3c69 --- /dev/null +++ b/cocos2d/core/graphics/graphics-webgl-cmd.js @@ -0,0 +1,1119 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +var Shader = require('./shader'); + +var LineCap = require('./types').LineCap; +var LineJoin = require('./types').LineJoin; + +var Earcut = require('./earcut'); + +var Vec2 = cc.Vec2; +var Js = cc.js; + +// Math +var PI = 3.14159265358979323846264338327; +var PI_2 = PI*2; +var INIT_VERTS_SIZE = 32; +var KAPPA90 = 0.5522847493; + +var VERTS_FLOAT_LENGTH = 2; +var VERTS_BYTE_LENGTH = 8; + +var min = Math.min; +var max = Math.max; +var ceil = Math.ceil; +var acos = Math.acos; +var cos = Math.cos; +var sin = Math.sin; +var atan2 = Math.atan2; +var abs = Math.abs; +var sign = Math.sign; + +function clamp (v, min, max) { + if (v < min) { + return min; + } + else if (v > max) { + return max; + } + return v; +} + +// PointFlags +var PointFlags = cc.Enum({ + PT_CORNER: 0x01, + PT_LEFT: 0x02, + PT_BEVEL: 0x04, + PT_INNERBEVEL: 0x08, +}); + +// Point +function Point (x, y) { + Vec2.call(this, x, y); + this.reset(); +} +Js.extend(Point, Vec2); + +Js.mixin(Point.prototype, { + reset: function () { + this.dx = 0; + this.dy = 0; + this.dmx = 0; + this.dmy = 0; + this.flags = 0; + this.len = 0; + } +}); + +// Path +function Path () { + this.reset(); +} +Path.prototype.reset = function () { + this.closed = false; + this.nbevel = 0; + this.complex = true; + + if (this.points) { + this.points.length = 0; + } + else { + this.points = []; + } +}; + +// webgl render command +function WebGLRenderCmd (renderable) { + _ccsg.Node.WebGLRenderCmd.call(this, renderable); + this._needDraw = true; + + var gl = cc._renderContext; + + this._vertsOffset = 0; + this._vertsVBO = gl.createBuffer(); + this._vertsBuffer = null; + this._vertsDirty = false; + + this._indicesOffset = 0; + this._indicesVBO = gl.createBuffer(); + this._indicesBuffer = null; + this._indicesDirty = false; + + this._paths = []; + this._points = []; + + this._cmds = []; + + this._blendFunc = new cc.BlendFunc(cc.macro.BLEND_SRC, cc.macro.BLEND_DST); + + // init shader + this._shader = new cc.GLProgram(); + this._shader.initWithVertexShaderByteArray(Shader.vert, Shader.frag); + this._shader.retain(); + this._shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); + this._shader.link(); + this._shader.updateUniforms(); + + this._allocVerts(INIT_VERTS_SIZE); +} + +WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); +WebGLRenderCmd.prototype.constructor = WebGLRenderCmd; + +var _p = WebGLRenderCmd.prototype; + +// draw api +Js.mixin(_p, { + _tessTol: 0.25, // Tessellation Tolerance + _distTol: 0.01, + + lineWidth: 1, + + lineCap: LineCap.BUTT, + lineJoin: LineJoin.MITER, + + miterLimit: 10, + + beginPath: function () { + this._pathOffset = this._pathLength; + }, + + moveTo: function (x, y) { + if (this._updatePathOffset) { + this._pathOffset = this._pathLength; + this._updatePathOffset = false; + } + + this._addPath(); + this._addPoint(x, y, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; + }, + + lineTo: function (x, y) { + this._addPoint(x, y, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; + }, + + bezierCurveTo: function (c1x, c1y, c2x, c2y, x, y) { + var path = this._curPath; + var last = path.points[path.points.length - 1]; + + if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) { + this.lineTo(x, y); + return; + } + + this._tesselateBezier(last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; + }, + + quadraticCurveTo: function (cx, cy, x, y) { + var x0 = this._commandx; + var y0 = this._commandy; + this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y); + }, + + // + arc: function (cx, cy, r, a0, a1, counterclockwise) { + var a = 0, da = 0, hda = 0, kappa = 0; + var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0; + var px = 0, py = 0, ptanx = 0, ptany = 0; + var i, ndivs; + + // Clamp angles + da = a1 - a0; + if (!counterclockwise) { + if (abs(da) >= PI * 2) { + da = PI * 2; + } else { + while (da < 0) da += PI * 2; + } + } else { + if (abs(da) >= PI * 2) { + da = -PI * 2; + } else { + while (da > 0) da -= PI * 2; + } + } + + // Split arc into max 90 degree segments. + ndivs = max(1, min(abs(da) / (PI * 0.5) + 0.5, 5)) | 0; + hda = da / ndivs / 2.0; + kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda)); + + if (counterclockwise) kappa = -kappa; + + for (i = 0; i <= ndivs; i++) { + a = a0 + da * (i / ndivs); + dx = cos(a); + dy = sin(a); + x = cx + dx * r; + y = cy + dy * r; + tanx = -dy * r * kappa; + tany = dx * r * kappa; + + if (i === 0) { + this.moveTo(x, y); + } else { + this.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y); + } + px = x; + py = y; + ptanx = tanx; + ptany = tany; + } + + // this.close(); + // this._curPath.complex = false; + }, + + ellipse: function (cx, cy, rx, ry) { + this.moveTo(cx - rx, cy); + this.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry); + this.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy); + this.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry); + this.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy); + + this.close(); + this._curPath.complex = false; + }, + + circle: function (cx, cy, r) { + // this.ellipse(cx, cy, r, r); + var divs = this._curveDivs(r, PI_2, this._tessTol); + var step = PI_2 / divs; + + this.moveTo(cx, cy + r); + + for (var i = 1; i < divs; i++) { + var angle = step * i; + var x = r * sin(angle); + var y = r * cos(angle); + + this.lineTo(cx + x, cy + y); + } + + this.close(); + this._curPath.complex = false; + }, + + rect: function (x, y, w, h) { + this.moveTo(x, y); + this.lineTo(x, y + h); + this.lineTo(x + w, y + h); + this.lineTo(x + w, y); + this.close(); + this._curPath.complex = false; + }, + + roundRect: function (x, y, w, h, r) { + if (r < 0.1) { + this.rect(x, y, w, h); + return; + } else { + var rx = min(r, abs(w) * 0.5) * sign(w), + ry = min(r, abs(h) * 0.5) * sign(h); + + this.moveTo(x, y + ry); + this.lineTo(x, y + h - ry); + this.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h); + this.lineTo(x + w - rx, y + h); + this.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry); + this.lineTo(x + w, y + ry); + this.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y); + this.lineTo(x + rx, y); + this.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry); + this.close(); + this._curPath.complex = false; + } + }, + + fillRect: function (x, y, w, h) { + this.rect(x, y, w, h); + + this.fill(); + }, + + close: function () { + this._curPath.closed = true; + }, + + stroke: function () { + this._flattenPaths(); + + this._expandStroke(); + + this._vertsDirty = true; + this._updatePathOffset = true; + }, + + fill: function () { + // this._flattenPaths(); + + this._expandFill(); + + this._vertsDirty = true; + this._updatePathOffset = true; + this._filling = false; + } +}); + + +// inner properties +Js.mixin(_p, { + _strokeColor: null, + _fillColor: null, + + setStrokeColor: function (c) { + this._strokeColor = c; + }, + + getStrokeColor: function () { + return this._strokeColor; + }, + + setFillColor: function (c) { + this._fillColor = c; + }, + + getFillColor: function () { + return this._fillColor; + } +}); + +cc.defineGetterSetter(_p, 'strokeColor', _p.getStrokeColor, _p.setStrokeColor); +cc.defineGetterSetter(_p, 'fillColor', _p.getFillColor, _p.setFillColor); + +Js.mixin(_p, { + _render: function () { + var vertsBuffer = this._vertsBuffer; + if (!vertsBuffer || vertsBuffer.length === 0 || this._cmds.length === 0) return; + + var gl = cc._renderContext; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertsVBO); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesVBO); + + if (this._vertsDirty) { + gl.bufferData(gl.ARRAY_BUFFER, vertsBuffer, gl.STREAM_DRAW); + this._vertsDirty = false; + } + + if (this._indicesDirty && this._indicesBuffer) { + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer, gl.STREAM_DRAW); + this._indicesDirty = false; + } + + cc.gl.enableVertexAttribs(cc.macro.VERTEX_ATTRIB_FLAG_POSITION); + + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, VERTS_BYTE_LENGTH, 0); + + var shader = this._shader; + var colorLocation = shader.getUniformLocationForName('color'); + + // draw paths + var cmds = this._cmds; + for (var i = 0, l = cmds.length; i < l; i++) { + var cmd = cmds[i]; + + if (cmd.nIndices) { + var color = cmd.color; + gl.uniform4f(colorLocation, color.r / 255, color.g / 255, color.b / 255, color.a / 255); + gl.drawElements(gl.TRIANGLES, cmd.nIndices, gl.UNSIGNED_SHORT, cmd.indicesOffset * 2); + + cc.incrementGLDraws(cmd.nverts); + } + } + + cc.checkGLErrorDebug(); + }, + + rendering: function () { + var node = this._node; + cc.gl.blendFunc(this._blendFunc.src, this._blendFunc.dst); + + var shader = this._shader; + shader.use(); + shader._setUniformForMVPMatrixWithMat4(this._stackMatrix); + + this._render(); + }, + + // clear + clear: function (clean) { + this._vertsOffset = 0; + this._indicesOffset = 0; + + this._pathLength = 0; + this._pathOffset = 0; + this._pointsOffset = 0; + + this._curPath = null; + + this._cmds.length = 0; + + if (clean) { + this._paths.length = 0; + this._points.length = 0; + + this._vertsBuffer = null; + this._indicesBuffer = null; + } + }, +}); + +// inner function +Js.mixin(_p, { + _updatePathOffset: false, + + _paths: null, + _pathLength: 0, + _pathOffset: 0, + + _points: null, + _pointsOffset: 0, + + _commandx: 0, + _commandy: 0, + + _addPath: function () { + var offset = this._pathLength; + var path = this._paths[offset]; + + if (!path) { + path = new Path(); + + this._paths.push(path); + } else { + path.reset(); + } + + this._pathLength++; + this._curPath = path; + + return path; + }, + + _addPoint: function (x, y, flags) { + var path = this._curPath; + if (!path) return; + + var pt; + var points = this._points; + var pathPoints = path.points; + + var offset = this._pointsOffset++; + pt = points[offset]; + + if (!pt) { + pt = new Point(x, y); + points.push(pt); + } else { + pt.x = x; + pt.y = y; + } + + pt.flags = flags; + pathPoints.push(pt); + }, + + _flattenPaths: function () { + var paths = this._paths; + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pts = path.points; + + var p0 = pts[pts.length - 1]; + var p1 = pts[0]; + + if (p0.equals(p1)) { + path.closed = true; + pts.pop(); + p0 = pts[pts.length - 1]; + } + + for (var j = 0, size = pts.length; j < size; j++) { + // Calculate segment direction and length + var dPos = p1.sub(p0); + p0.len = dPos.mag(); + dPos.normalizeSelf(); + p0.dx = dPos.x; + p0.dy = dPos.y; + // Advance + p0 = p1; + p1 = pts[j + 1]; + } + } + }, + + _allocVerts: function (cverts) { + var dnverts = this._vertsOffset + cverts; + var buffer = this._vertsBuffer; + var nverts = buffer ? buffer.length / VERTS_FLOAT_LENGTH : 0; + + if (dnverts > nverts) { + if (nverts === 0) { + nverts = INIT_VERTS_SIZE; + } + + while (dnverts > nverts) { + nverts *= 2; + } + + var newBuffer = new Float32Array(nverts * VERTS_FLOAT_LENGTH); + + if (buffer) { + for (var i = 0, l = buffer.length; i < l; i++) { + newBuffer[i] = buffer[i]; + } + } + + this._vertsBuffer = newBuffer; + } + }, + + _allocIndices: function (cindices) { + var indices = this._indicesBuffer; + var dnindices = this._indicesOffset + cindices; + var nindices = indices ? indices.length : 0; + + if (dnindices > nindices) { + if (nindices === 0) { + nindices = INIT_VERTS_SIZE * 3; + } + + while (dnindices > nindices) { + nindices *= 2; + } + + var newIndices = new Uint16Array(nindices); + + if (indices) { + for (var i = 0, l = indices.length; i < l; i++) { + newIndices[i] = indices[i]; + } + } + this._indicesBuffer = newIndices; + } + }, + + _pushCmd: function (cmd) { + var cmds = this._cmds; + var lastCmd = cmds[cmds.length - 1]; + + if (lastCmd) { + var lastColor = lastCmd.color; + var color = cmd.color; + + if (lastColor.r === color.r && + lastColor.g === color.g && + lastColor.b === color.b && + lastColor.a === color.a && + (lastCmd.indicesOffset + lastCmd.nIndices === cmd.indicesOffset)) { + lastCmd.nIndices += cmd.nIndices; + lastCmd.nverts += cmd.nverts; + } + else { + cmds.push(cmd); + } + } + else { + cmds.push(cmd); + } + }, + + _expandStroke: function () { + var w = this.lineWidth * 0.5, + lineCap = this.lineCap, + lineJoin = this.lineJoin, + miterLimit = this.miterLimit; + + var ncap = this._curveDivs(w, PI, this._tessTol); + var paths = this._paths; + + this._calculateJoins(w, lineJoin, miterLimit); + + // Calculate max vertex usage. + var cverts = 0; + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pointsLength = path.points.length; + + if (lineJoin === LineJoin.ROUND) cverts += (pointsLength + path.nbevel * (ncap + 2) + 1) * 2; // plus one for loop + else cverts += (pointsLength + path.nbevel * 5 + 1) * 2; // plus one for loop + + if (!path.closed) { + // space for caps + if (lineCap === LineCap.ROUND) { + cverts += (ncap * 2 + 2) * 2; + } else { + cverts += (3 + 3) * 2; + } + } + } + + this._allocVerts(cverts); + this._allocIndices((cverts - 2*(this._pathLength-this._pathOffset)) * 3); + + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pts = path.points; + var pointsLength = path.points.length; + + var p0, p1; + var s, e, loop; + + loop = path.closed; + var offset = this._vertsOffset; + + if (loop) { + // Looping + p0 = pts[pointsLength - 1]; + p1 = pts[0]; + s = 0; + e = pointsLength; + } else { + // Add cap + p0 = pts[0]; + p1 = pts[1]; + s = 1; + e = pointsLength - 1; + } + + if (!loop) { + // Add cap + var dPos = p1.sub(p0); + dPos.normalizeSelf(); + + var dx = dPos.x; + var dy = dPos.y; + + if (lineCap === LineCap.BUTT) + this._buttCap(p0, dx, dy, w, 0); + else if (lineCap === LineCap.SQUARE) + this._buttCap(p0, dx, dy, w, w); + else if (lineCap === LineCap.ROUND) + this._roundCapStart(p0, dx, dy, w, ncap); + } + + for (var j = s; j < e; ++j) { + if (lineJoin === LineJoin.ROUND) { + this._roundJoin(p0, p1, w, w, ncap); + } + else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) { + this._bevelJoin(p0, p1, w, w); + } + else { + this._vset(p1.x + p1.dmx * w, p1.y + p1.dmy * w); + this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w); + } + + p0 = p1; + p1 = pts[j + 1]; + } + + if (loop) { + var v0 = this._vget(offset); + var v1 = this._vget(offset + 1); + // Loop it + this._vset(v0.x, v0.y); + this._vset(v1.x, v1.y); + } else { + // Add cap + var dPos = p1.sub(p0); + dPos.normalizeSelf(); + + var dx = dPos.x; + var dy = dPos.y; + + if (lineCap === LineCap.BUTT) + this._buttCap(p1, dx, dy, w, 0); + else if (lineCap === LineCap.BUTT || lineCap === LineCap.SQUARE) + this._buttCap(p1, dx, dy, w, w); + else if (lineCap === LineCap.ROUND) + this._roundCapEnd(p1, dx, dy, w, ncap); + } + + // stroke indices + var indicesOffset = this._indicesOffset; + var indicesBuffer = this._indicesBuffer; + + for (var start = offset+2, end = this._vertsOffset; start < end; start++) { + indicesBuffer[indicesOffset++] = start - 2; + indicesBuffer[indicesOffset++] = start - 1; + indicesBuffer[indicesOffset++] = start; + } + + this._pushCmd({ + color: this._strokeColor, + indicesOffset: this._indicesOffset, + nIndices: indicesOffset - this._indicesOffset, + vertsOffset: offset, + nverts: this._vertsOffset - offset + }); + + this._indicesOffset = indicesOffset; + this._indicesDirty = true; + } + }, + + _expandFill: function () { + // this._calculateJoins(0, LineJoin.MITER, 2.4); + + var paths = this._paths; + + // Calculate max vertex usage. + var cverts = 0; + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pointsLength = path.points.length; + + cverts += pointsLength; + } + + this._allocVerts(cverts); + this._allocIndices((cverts - 2*(this._pathLength-this._pathOffset)) * 3); + + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pts = path.points; + var pointsLength = pts.length; + + if (pointsLength === 0) { + continue; + } + + // Calculate shape vertices. + var offset = this._vertsOffset; + + for (var j = 0; j < pointsLength; ++j) { + this._vset(pts[j].x, pts[j].y, 0.5, 1); + } + + var indicesOffset = path.indicesOffset = this._indicesOffset; + var indicesBuffer = this._indicesBuffer; + var nIndices = 0; + + if (path.complex) { + var data = this._vertsBuffer.slice(offset * 2, this._vertsOffset * 2); + var newIndices = Earcut(data, null, 2); + + if (!newIndices || newIndices.length === 0) { + continue; + } + + nIndices = newIndices.length; + + for (var j = 0, l3 = nIndices; j < l3; j++) { + indicesBuffer[indicesOffset + j] = newIndices[j] + offset; + } + } + else { + var first = offset; + for (var start = offset+2, end = this._vertsOffset; start < end; start++) { + indicesBuffer[indicesOffset++] = first; + indicesBuffer[indicesOffset++] = start - 1; + indicesBuffer[indicesOffset++] = start; + } + + nIndices = indicesOffset - this._indicesOffset; + } + + this._pushCmd({ + color: this._fillColor, + indicesOffset: this._indicesOffset, + nIndices: nIndices, + vertsOffset: offset, + nverts: this._vertsOffset - offset + }); + + this._indicesOffset += nIndices; + this._indicesDirty = true; + } + }, + + _curveDivs: function (r, arc, tol) { + var da = acos(r / (r + tol)) * 2.0; + return max(2, ceil(arc / da)); + }, + + _calculateJoins: function (w, lineJoin, miterLimit) { + var iw = 0.0; + + if (w > 0.0) { + iw = 1 / w; + } + + // Calculate which joins needs extra vertices to append, and gather vertex count. + var paths = this._paths; + + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + + var pts = path.points; + var ptsLength = pts.length; + var p0 = pts[ptsLength - 1]; + var p1 = pts[0]; + var nleft = 0; + + path.nbevel = 0; + + for (var j = 0; j < ptsLength; j++) { + var dmr2, cross, limit; + + // perp normals + var dlx0 = p0.dy; + var dly0 = -p0.dx; + var dlx1 = p1.dy; + var dly1 = -p1.dx; + + // Calculate extrusions + p1.dmx = (dlx0 + dlx1) * 0.5; + p1.dmy = (dly0 + dly1) * 0.5; + dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy; + if (dmr2 > 0.000001) { + var scale = 1 / dmr2; + if (scale > 600) { + scale = 600; + } + p1.dmx *= scale; + p1.dmy *= scale; + } + + // Keep track of left turns. + cross = p1.dx * p0.dy - p0.dx * p1.dy; + if (cross > 0) { + nleft++; + p1.flags |= PointFlags.PT_LEFT; + } + + // Calculate if we should use bevel or miter for inner join. + limit = max(11, min(p0.len, p1.len) * iw); + if (dmr2 * limit * limit < 1) { + p1.flags |= PointFlags.PT_INNERBEVEL; + } + + // Check to see if the corner needs to be beveled. + if (p1.flags & PointFlags.PT_CORNER) { + if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) { + p1.flags |= PointFlags.PT_BEVEL; + } + } + + if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) { + path.nbevel++; + } + + p0 = p1; + p1 = pts[j + 1]; + } + } + }, + + _vset: function (x, y) { + var offset = this._vertsOffset * VERTS_FLOAT_LENGTH; + var buffer = this._vertsBuffer; + + buffer[offset] = x; + buffer[offset + 1] = y; + + this._vertsOffset++; + }, + + _vget: function (index) { + var buffer = this._vertsBuffer; + var offset = index * VERTS_FLOAT_LENGTH; + return { + x: buffer[offset], + y: buffer[offset + 1] + }; + }, + + // + _chooseBevel: function (bevel, p0, p1, w) { + var x = p1.x; + var y = p1.y; + var x0, y0, x1, y1; + + if (bevel !== 0) { + x0 = x + p0.dy * w; + y0 = y - p0.dx * w; + x1 = x + p1.dy * w; + y1 = y - p1.dx * w; + } else { + x0 = x1 = x + p1.dmx * w; + y0 = y1 = y + p1.dmy * w; + } + + return [x0, y0, x1, y1]; + }, + + _buttCap: function (p, dx, dy, w, d) { + var px = p.x - dx * d; + var py = p.y - dy * d; + var dlx = dy; + var dly = -dx; + + this._vset(px + dlx * w, py + dly * w); + this._vset(px - dlx * w, py - dly * w); + }, + + _roundCapStart: function (p, dx, dy, w, ncap) { + var px = p.x; + var py = p.y; + var dlx = dy; + var dly = -dx; + + for (var i = 0; i < ncap; i++) { + var a = i / (ncap - 1) * PI; + var ax = cos(a) * w, + ay = sin(a) * w; + this._vset(px - dlx * ax - dx * ay, py - dly * ax - dy * ay); + this._vset(px, py); + } + this._vset(px + dlx * w, py + dly * w); + this._vset(px - dlx * w, py - dly * w); + }, + + _roundCapEnd: function (p, dx, dy, w, ncap) { + var px = p.x; + var py = p.y; + var dlx = dy; + var dly = -dx; + + this._vset(px + dlx * w, py + dly * w); + this._vset(px - dlx * w, py - dly * w); + for (var i = 0; i < ncap; i++) { + var a = i / (ncap - 1) * PI; + var ax = cos(a) * w, + ay = sin(a) * w; + this._vset(px, py); + this._vset(px - dlx * ax + dx * ay, py - dly * ax + dy * ay); + } + }, + + _roundJoin: function (p0, p1, lw, rw, ncap) { + var dlx0 = p0.dy; + var dly0 = -p0.dx; + var dlx1 = p1.dy; + var dly1 = -p1.dx; + + var p1x = p1.x; + var p1y = p1.y; + + if ((p1.flags & PointFlags.PT_LEFT) !== 0) { + var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw); + var lx0 = out[0]; + var ly0 = out[1]; + var lx1 = out[2]; + var ly1 = out[3]; + + var a0 = atan2(-dly0, -dlx0); + var a1 = atan2(-dly1, -dlx1); + if (a1 > a0) a1 -= PI * 2; + + this._vset(lx0, ly0); + this._vset(p1x - dlx0 * rw, p1.y - dly0 * rw); + + var n = clamp(ceil((a0 - a1) / PI) * ncap, 2, ncap); + for (var i = 0; i < n; i++) { + var u = i / (n - 1); + var a = a0 + u * (a1 - a0); + var rx = p1x + cos(a) * rw; + var ry = p1y + sin(a) * rw; + this._vset(p1x, p1y); + this._vset(rx, ry); + } + + this._vset(lx1, ly1); + this._vset(p1x - dlx1 * rw, p1y - dly1 * rw); + } else { + var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw); + var rx0 = out[0]; + var ry0 = out[1]; + var rx1 = out[2]; + var ry1 = out[3]; + + var a0 = atan2(dly0, dlx0); + var a1 = atan2(dly1, dlx1); + if (a1 < a0) a1 += PI * 2; + + this._vset(p1x + dlx0 * rw, p1y + dly0 * rw); + this._vset(rx0, ry0); + + var n = clamp(ceil((a1 - a0) / PI) * ncap, 2, ncap); + for (var i = 0; i < n; i++) { + var u = i / (n - 1); + var a = a0 + u * (a1 - a0); + var lx = p1x + cos(a) * lw; + var ly = p1y + sin(a) * lw; + this._vset(lx, ly); + this._vset(p1x, p1y); + } + + this._vset(p1x + dlx1 * rw, p1y + dly1 * rw); + this._vset(rx1, ry1); + } + }, + + _bevelJoin: function (p0, p1, lw, rw) { + var rx0, ry0, rx1, ry1; + var lx0, ly0, lx1, ly1; + var dlx0 = p0.dy; + var dly0 = -p0.dx; + var dlx1 = p1.dy; + var dly1 = -p1.dx; + + if (p1.flags & PointFlags.PT_LEFT) { + var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw); + lx0 = out[0]; + ly0 = out[1]; + lx1 = out[2]; + ly1 = out[3]; + + this._vset(lx0, ly0); + this._vset(p1.x - dlx0 * rw, p1.y - dly0 * rw); + + this._vset(lx1, ly1); + this._vset(p1.x - dlx1 * rw, p1.y - dly1 * rw); + } else { + var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw); + rx0 = out[0]; + ry0 = out[1]; + rx1 = out[2]; + ry1 = out[3]; + + this._vset(p1.x + dlx0 * lw, p1.y + dly0 * lw); + this._vset(rx0, ry0); + + this._vset(p1.x + dlx1 * lw, p1.y + dly1 * lw); + this._vset(rx1, ry1); + } + }, + + _tesselateBezier: function (x1, y1, x2, y2, x3, y3, x4, y4, level, type) { + var x12, y12, x23, y23, x34, y34, x123, y123, x234, y234, x1234, y1234; + var dx, dy, d2, d3; + + if (level > 10) return; + + x12 = (x1 + x2) * 0.5; + y12 = (y1 + y2) * 0.5; + x23 = (x2 + x3) * 0.5; + y23 = (y2 + y3) * 0.5; + x34 = (x3 + x4) * 0.5; + y34 = (y3 + y4) * 0.5; + x123 = (x12 + x23) * 0.5; + y123 = (y12 + y23) * 0.5; + + dx = x4 - x1; + dy = y4 - y1; + d2 = abs((x2 - x4) * dy - (y2 - y4) * dx); + d3 = abs((x3 - x4) * dy - (y3 - y4) * dx); + + if ((d2 + d3) * (d2 + d3) < this._tessTol * (dx * dx + dy * dy)) { + this._addPoint(x4, y4, type === 0 ? type | PointFlags.PT_BEVEL : type); + return; + } + + x234 = (x23 + x34) * 0.5; + y234 = (y23 + y34) * 0.5; + x1234 = (x123 + x234) * 0.5; + y1234 = (y123 + y234) * 0.5; + + this._tesselateBezier(x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0); + this._tesselateBezier(x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type); + } +}); + + +module.exports = WebGLRenderCmd; diff --git a/cocos2d/core/graphics/graphics.js b/cocos2d/core/graphics/graphics.js new file mode 100644 index 0000000000..d9af550be5 --- /dev/null +++ b/cocos2d/core/graphics/graphics.js @@ -0,0 +1,341 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +var LineCap = require('./types').LineCap; +var LineJoin = require('./types').LineJoin; + +/** + * @class Graphics + * @extends _RendererUnderSG + */ +var Graphics = cc.Class({ + name: 'cc.Graphics', + extends: cc._RendererUnderSG, + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.renderers/Graphics', + }, + + properties: { + _lineWidth: 1, + _strokeColor: cc.Color.BLACK, + _lineJoin: LineJoin.MITER, + _lineCap: LineCap.BUTT, + _fillColor: cc.Color.WHITE, + _miterLimit: 10, + + /** + * !#en + * Current line width. + * !#zh + * 当前线条宽度 + * @property {Number} lineWidth + * @default 1 + */ + lineWidth: { + get: function () { + return this._lineWidth; + }, + set: function (value) { + this._sgNode.lineWidth = this._lineWidth = value; + } + }, + + /** + * !#en + * lineJoin determines how two connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together. + * !#zh + * lineJoin 用来设置2个长度不为0的相连部分(线段,圆弧,曲线)如何连接在一起的属性。 + * @property {Graphics.LineJoin} lineJoin + * @default LineJoin.MITER + */ + lineJoin: { + get: function () { + return this._lineJoin; + }, + set: function (value) { + this._sgNode.lineJoin = this._lineJoin = value; + }, + type: LineJoin + }, + + /** + * !#en + * lineCap determines how the end points of every line are drawn. + * !#zh + * lineCap 指定如何绘制每一条线段末端。 + * @property {Graphics.LineCap} lineCap + * @default LineCap.BUTT + */ + lineCap: { + get: function () { + return this._lineCap; + }, + set: function (value) { + this._sgNode.lineCap = this._lineCap = value; + }, + type: LineCap + }, + + /** + * !#en + * stroke color + * !#zh + * 线段颜色 + * @property {Color} strokeColor + * @default Color.BLACK + */ + strokeColor: { + get: function () { + return this._strokeColor; + }, + set: function (value) { + this._sgNode.strokeColor = this._strokeColor = value; + } + }, + + /** + * !#en + * fill color + * !#zh + * 填充颜色 + * @property {Color} fillColor + * @default Color.WHITE + */ + fillColor: { + get: function () { + return this._fillColor; + }, + set: function (value) { + this._sgNode.fillColor = this._fillColor = value; + } + }, + + /** + * !#en + * Sets the miter limit ratio + * !#zh + * 设置斜接面限制比例 + * @property {Number} miterLimit + * @default 10 + */ + miterLimit: { + get: function () { + return this._miterLimit; + }, + set: function (value) { + this._sgNode.miterLimit = this._miterLimit = value; + } + } + }, + + statics: { + LineJoin: LineJoin, + LineCap: LineCap + }, + + _createSgNode: function () { + return new _ccsg.GraphicsNode(); + }, + + _initSgNode: function () { + var sgNode = this._sgNode; + sgNode.lineWidth = this._lineWidth; + sgNode.lineJoin = this._lineJoin; + sgNode.lineCap = this._lineCap; + sgNode.strokeColor = this._strokeColor; + sgNode.fillColor = this._fillColor; + sgNode.miterLimit = this._miterLimit; + }, + + /** + * !#en Move path start point to (x,y). + * !#zh 移动路径起点到坐标(x, y) + * @method moveTo + * @param {Number} [x] The x axis of the coordinate for the end point. + * @param {Number} [y] The y axis of the coordinate for the end point. + */ + moveTo: function (x, y) { + this._sgNode.moveTo(x, y); + }, + + /** + * !#en Adds a straight line to the path + * !#zh 绘制直线路径 + * @method lineTo + * @param {Number} [x] The x axis of the coordinate for the end point. + * @param {Number} [y] The y axis of the coordinate for the end point. + */ + lineTo: function (x, y) { + this._sgNode.lineTo(x, y); + }, + + /** + * !#en Adds a cubic Bézier curve to the path + * !#zh 绘制三次贝赛尔曲线路径 + * @method bezierCurveTo + * @param {Number} [c1x] The x axis of the coordinate for the first control point. + * @param {Number} [c1y] The y axis of the coordinate for first control point. + * @param {Number} [c2x] The x axis of the coordinate for the second control point. + * @param {Number} [c2y] The y axis of the coordinate for the second control point. + * @param {Number} [x] The x axis of the coordinate for the end point. + * @param {Number} [y] The y axis of the coordinate for the end point. + */ + bezierCurveTo: function (c1x, c1y, c2x, c2y, x, y) { + this._sgNode.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); + }, + + /** + * !#en Adds a quadratic Bézier curve to the path + * !#zh 绘制二次贝赛尔曲线路径 + * @method quadraticCurveTo + * @param {Number} [cx] The x axis of the coordinate for the control point. + * @param {Number} [cy] The y axis of the coordinate for the control point. + * @param {Number} [x] The x axis of the coordinate for the end point. + * @param {Number} [y] The y axis of the coordinate for the end point. + */ + quadraticCurveTo: function (cx, cy, x, y) { + this._sgNode.quadraticCurveTo(cx, cy, x, y); + }, + + /** + * !#en Adds an arc to the path which is centered at (cx, cy) position with radius r starting at startAngle and ending at endAngle going in the given direction by counterclockwise (defaulting to false). + * !#zh 绘制圆弧路径。圆弧路径的圆心在 (cx, cy) 位置,半径为 r ,根据 counterclockwise (默认为false)指定的方向从 startAngle 开始绘制,到 endAngle 结束。 + * @method arc + * @param {Number} [cx] The x axis of the coordinate for the center point. + * @param {Number} [cy] The y axis of the coordinate for the center point. + * @param {Number} [r] The arc's radius. + * @param {Number} [startAngle] The angle at which the arc starts, measured clockwise from the positive x axis and expressed in radians. + * @param {Number} [endAngle] The angle at which the arc ends, measured clockwise from the positive x axis and expressed in radians. + * @param {Number} [counterclockwise] An optional Boolean which, if true, causes the arc to be drawn counter-clockwise between the two angles. By default it is drawn clockwise. + */ + arc: function (cx, cy, r, startAngle, endAngle, counterclockwise) { + counterclockwise = counterclockwise || false; + this._sgNode.arc(cx, cy, r, startAngle, endAngle, counterclockwise); + }, + + /** + * !#en Adds an ellipse to the path. + * !#zh 绘制椭圆路径。 + * @method ellipse + * @param {Number} [cx] The x axis of the coordinate for the center point. + * @param {Number} [cy] The y axis of the coordinate for the center point. + * @param {Number} [rx] The ellipse's x-axis radius. + * @param {Number} [ry] The ellipse's y-axis radius. + */ + ellipse: function (cx, cy, rx, ry) { + this._sgNode.ellipse(cx, cy, rx, ry); + }, + + /** + * !#en Adds an circle to the path. + * !#zh 绘制圆形路径。 + * @method circle + * @param {Number} [cx] The x axis of the coordinate for the center point. + * @param {Number} [cy] The y axis of the coordinate for the center point. + * @param {Number} [r] The circle's radius. + */ + circle: function (cx, cy, r) { + this._sgNode.circle(cx, cy, r); + }, + + /** + * !#en Adds an rectangle to the path. + * !#zh 绘制矩形路径。 + * @method rect + * @param {Number} [x] The x axis of the coordinate for the rectangle starting point. + * @param {Number} [y] The y axis of the coordinate for the rectangle starting point. + * @param {Number} [w] The rectangle's width. + * @param {Number} [h] The rectangle's height. + */ + rect: function (x, y, w, h) { + this._sgNode.rect(x, y, w, h); + }, + + /** + * !#en Adds an round corner rectangle to the path. + * !#zh 绘制圆角矩形路径。 + * @method roundRect + * @param {Number} [x] The x axis of the coordinate for the rectangle starting point. + * @param {Number} [y] The y axis of the coordinate for the rectangle starting point. + * @param {Number} [w] The rectangles width. + * @param {Number} [h] The rectangle's height. + * @param {Number} [r] The radius of the rectangle. + */ + roundRect: function (x, y, w, h, r) { + this._sgNode.roundRect(x, y, w, h, r); + }, + + /** + * !#en Draws a filled rectangle. + * !#zh 绘制填充矩形。 + * @method fillRect + * @param {Number} [x] The x axis of the coordinate for the rectangle starting point. + * @param {Number} [y] The y axis of the coordinate for the rectangle starting point. + * @param {Number} [w] The rectangle's width. + * @param {Number} [h] The rectangle's height. + */ + fillRect: function (x, y, w, h) { + this._sgNode.fillRect(x, y, w, h); + }, + + /** + * !#en Erasing any previously drawn content. + * !#zh 擦除之前绘制的所有内容的方法。 + * @method clear + */ + clear: function () { + this._sgNode.clear(); + }, + + /** + * !#en Causes the point of the pen to move back to the start of the current path. It tries to add a straight line from the current point to the start. + * !#zh 将笔点返回到当前路径起始点的。它尝试从当前点到起始点绘制一条直线。 + * @method close + */ + close: function () { + this._sgNode.close(); + }, + + /** + * !#en Strokes the current or given path with the current stroke style. + * !#zh 根据当前的画线样式,绘制当前或已经存在的路径。 + * @method stroke + */ + stroke: function () { + this._sgNode.stroke(); + }, + + /** + * !#en Fills the current or given path with the current fill style. + * !#zh 根据当前的画线样式,填充当前或已经存在的路径。 + * @method stroke + */ + fill: function () { + this._sgNode.fill(); + } +}); + +cc.Graphics = module.exports = Graphics; diff --git a/cocos2d/core/graphics/index.js b/cocos2d/core/graphics/index.js new file mode 100644 index 0000000000..fbe7f1d045 --- /dev/null +++ b/cocos2d/core/graphics/index.js @@ -0,0 +1,39 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +'use strict'; + +var GraphicsNode; +if (!cc.sys.isNative) { + GraphicsNode = _ccsg.GraphicsNode = require('./graphics-node'); +} +else { + GraphicsNode = _ccsg.GraphicsNode = cc.GraphicsNode; +} + +var misc = require('../utils/misc'); +misc.propertyDefine(GraphicsNode, ['lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'deviceRatio', 'strokeColor', 'fillColor'], {}); + +require('./graphics'); diff --git a/cocos2d/core/graphics/shader.js b/cocos2d/core/graphics/shader.js new file mode 100644 index 0000000000..fb785f4d8f --- /dev/null +++ b/cocos2d/core/graphics/shader.js @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +var vert = [ + 'attribute vec4 a_position;', + '', + 'void main()', + '{', + // ' gl_Position = CC_MVPMatrix * a_position;', + ' gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;', + '}' +]; + +var frag = [ + '#ifdef GL_ES', + 'precision mediump float;', + '#endif', + '', + 'uniform vec4 color;', + '', + 'void main(void) {', + ' gl_FragColor = color;', + '}' +]; + +module.exports = { + vert: vert.join(' \n'), + frag: frag.join(' \n') +}; diff --git a/cocos2d/core/graphics/types.js b/cocos2d/core/graphics/types.js new file mode 100644 index 0000000000..1067feaa83 --- /dev/null +++ b/cocos2d/core/graphics/types.js @@ -0,0 +1,87 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +'use strict'; + +/** + * !#en Enum for LineCap. + * !#zh 线段末端属性 + * @enum Graphics.LineCap + */ +var LineCap = cc.Enum({ + /** + * !#en The ends of lines are squared off at the endpoints. + * !#zh 线段末端以方形结束。 + * @property {Number} BUTT + */ + BUTT: 0, + + /** + * !#en The ends of lines are rounded. + * !#zh 线段末端以圆形结束。 + * @property {Number} ROUND + */ + ROUND: 1, + + /** + * !#en The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness. + * !#zh 线段末端以方形结束,但是增加了一个宽度和线段相同,高度是线段厚度一半的矩形区域。 + * @property {Number} SQUARE + */ + SQUARE: 2, +}); + +/** + * !#en Enum for LineJoin. + * !#zh 线段拐角属性 + * @enum Graphics.LineJoin + */ +var LineJoin = cc.Enum({ + /** + * !#en Fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment. + * !#zh 在相连部分的末端填充一个额外的以三角形为底的区域, 每个部分都有各自独立的矩形拐角。 + * @property {Number} BEVEL + */ + BEVEL: 0, + + /** + * !#en Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is equal to the line width. + * !#zh 通过填充一个额外的,圆心在相连部分末端的扇形,绘制拐角的形状。 圆角的半径是线段的宽度。 + * @property {Number} ROUND + */ + ROUND: 1, + + /** + * !#en Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. + * !#zh 通过延伸相连部分的外边缘,使其相交于一点,形成一个额外的菱形区域。 + * @property {Number} MITER + */ + MITER: 2 +}); + +module.exports = { + LineCap: LineCap, + LineJoin: LineJoin +}; diff --git a/cocos2d/core/index.js b/cocos2d/core/index.js index 2d947a6604..084e855a61 100644 --- a/cocos2d/core/index.js +++ b/cocos2d/core/index.js @@ -35,6 +35,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) { require('./CCScene'); require('./components'); + require('./graphics'); require('./collider'); } diff --git a/modules.json b/modules.json index e824878108..24fec2d2d5 100644 --- a/modules.json +++ b/modules.json @@ -146,5 +146,11 @@ "entries": [ "./cocos2d/audio/CCAudio.js" ] + }, + { + "name": "Graphics", + "entries": [ + "./cocos2d/core/graphics/index.js" + ] } ] \ No newline at end of file