connection_db.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /**
  2. * @license
  3. * Visual Blocks Editor
  4. *
  5. * Copyright 2011 Google Inc.
  6. * https://developers.google.com/blockly/
  7. *
  8. * Licensed under the Apache License, Version 2.0 (the "License");
  9. * you may not use this file except in compliance with the License.
  10. * You may obtain a copy of the License at
  11. *
  12. * http://www.apache.org/licenses/LICENSE-2.0
  13. *
  14. * Unless required by applicable law or agreed to in writing, software
  15. * distributed under the License is distributed on an "AS IS" BASIS,
  16. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  17. * See the License for the specific language governing permissions and
  18. * limitations under the License.
  19. */
  20. /**
  21. * @fileoverview Components for managing connections between blocks.
  22. * @author fraser@google.com (Neil Fraser)
  23. */
  24. 'use strict';
  25. goog.provide('Blockly.ConnectionDB');
  26. goog.require('Blockly.Connection');
  27. /**
  28. * Database of connections.
  29. * Connections are stored in order of their vertical component. This way
  30. * connections in an area may be looked up quickly using a binary search.
  31. * @constructor
  32. */
  33. Blockly.ConnectionDB = function() {
  34. };
  35. Blockly.ConnectionDB.prototype = new Array();
  36. /**
  37. * Don't inherit the constructor from Array.
  38. * @type {!Function}
  39. */
  40. Blockly.ConnectionDB.constructor = Blockly.ConnectionDB;
  41. /**
  42. * Add a connection to the database. Must not already exist in DB.
  43. * @param {!Blockly.Connection} connection The connection to be added.
  44. */
  45. Blockly.ConnectionDB.prototype.addConnection = function(connection) {
  46. if (connection.inDB_) {
  47. throw 'Connection already in database.';
  48. }
  49. if (connection.getSourceBlock().isInFlyout) {
  50. // Don't bother maintaining a database of connections in a flyout.
  51. return;
  52. }
  53. var position = this.findPositionForConnection_(connection);
  54. this.splice(position, 0, connection);
  55. connection.inDB_ = true;
  56. };
  57. /**
  58. * Find the given connection.
  59. * Starts by doing a binary search to find the approximate location, then
  60. * linearly searches nearby for the exact connection.
  61. * @param {!Blockly.Connection} conn The connection to find.
  62. * @return {number} The index of the connection, or -1 if the connection was
  63. * not found.
  64. */
  65. Blockly.ConnectionDB.prototype.findConnection = function(conn) {
  66. if (!this.length) {
  67. return -1;
  68. }
  69. var bestGuess = this.findPositionForConnection_(conn);
  70. if (bestGuess >= this.length) {
  71. // Not in list
  72. return -1;
  73. }
  74. var yPos = conn.y_;
  75. // Walk forward and back on the y axis looking for the connection.
  76. var pointerMin = bestGuess;
  77. var pointerMax = bestGuess;
  78. while (pointerMin >= 0 && this[pointerMin].y_ == yPos) {
  79. if (this[pointerMin] == conn) {
  80. return pointerMin;
  81. }
  82. pointerMin--;
  83. }
  84. while (pointerMax < this.length && this[pointerMax].y_ == yPos) {
  85. if (this[pointerMax] == conn) {
  86. return pointerMax;
  87. }
  88. pointerMax++;
  89. }
  90. return -1;
  91. };
  92. /**
  93. * Finds a candidate position for inserting this connection into the list.
  94. * This will be in the correct y order but makes no guarantees about ordering in
  95. * the x axis.
  96. * @param {!Blockly.Connection} connection The connection to insert.
  97. * @return {number} The candidate index.
  98. * @private
  99. */
  100. Blockly.ConnectionDB.prototype.findPositionForConnection_ =
  101. function(connection) {
  102. /* eslint-disable indent */
  103. if (!this.length) {
  104. return 0;
  105. }
  106. var pointerMin = 0;
  107. var pointerMax = this.length;
  108. while (pointerMin < pointerMax) {
  109. var pointerMid = Math.floor((pointerMin + pointerMax) / 2);
  110. if (this[pointerMid].y_ < connection.y_) {
  111. pointerMin = pointerMid + 1;
  112. } else if (this[pointerMid].y_ > connection.y_) {
  113. pointerMax = pointerMid;
  114. } else {
  115. pointerMin = pointerMid;
  116. break;
  117. }
  118. }
  119. return pointerMin;
  120. }; /* eslint-enable indent */
  121. /**
  122. * Remove a connection from the database. Must already exist in DB.
  123. * @param {!Blockly.Connection} connection The connection to be removed.
  124. * @private
  125. */
  126. Blockly.ConnectionDB.prototype.removeConnection_ = function(connection) {
  127. if (!connection.inDB_) {
  128. throw 'Connection not in database.';
  129. }
  130. var removalIndex = this.findConnection(connection);
  131. if (removalIndex == -1) {
  132. throw 'Unable to find connection in connectionDB.';
  133. }
  134. connection.inDB_ = false;
  135. this.splice(removalIndex, 1);
  136. };
  137. /**
  138. * Find all nearby connections to the given connection.
  139. * Type checking does not apply, since this function is used for bumping.
  140. * @param {!Blockly.Connection} connection The connection whose neighbours
  141. * should be returned.
  142. * @param {number} maxRadius The maximum radius to another connection.
  143. * @return {!Array.<Blockly.Connection>} List of connections.
  144. */
  145. Blockly.ConnectionDB.prototype.getNeighbours = function(connection, maxRadius) {
  146. var db = this;
  147. var currentX = connection.x_;
  148. var currentY = connection.y_;
  149. // Binary search to find the closest y location.
  150. var pointerMin = 0;
  151. var pointerMax = db.length - 2;
  152. var pointerMid = pointerMax;
  153. while (pointerMin < pointerMid) {
  154. if (db[pointerMid].y_ < currentY) {
  155. pointerMin = pointerMid;
  156. } else {
  157. pointerMax = pointerMid;
  158. }
  159. pointerMid = Math.floor((pointerMin + pointerMax) / 2);
  160. }
  161. var neighbours = [];
  162. /**
  163. * Computes if the current connection is within the allowed radius of another
  164. * connection.
  165. * This function is a closure and has access to outside variables.
  166. * @param {number} yIndex The other connection's index in the database.
  167. * @return {boolean} True if the current connection's vertical distance from
  168. * the other connection is less than the allowed radius.
  169. */
  170. function checkConnection_(yIndex) {
  171. var dx = currentX - db[yIndex].x_;
  172. var dy = currentY - db[yIndex].y_;
  173. var r = Math.sqrt(dx * dx + dy * dy);
  174. if (r <= maxRadius) {
  175. neighbours.push(db[yIndex]);
  176. }
  177. return dy < maxRadius;
  178. }
  179. // Walk forward and back on the y axis looking for the closest x,y point.
  180. pointerMin = pointerMid;
  181. pointerMax = pointerMid;
  182. if (db.length) {
  183. while (pointerMin >= 0 && checkConnection_(pointerMin)) {
  184. pointerMin--;
  185. }
  186. do {
  187. pointerMax++;
  188. } while (pointerMax < db.length && checkConnection_(pointerMax));
  189. }
  190. return neighbours;
  191. };
  192. /**
  193. * Is the candidate connection close to the reference connection.
  194. * Extremely fast; only looks at Y distance.
  195. * @param {number} index Index in database of candidate connection.
  196. * @param {number} baseY Reference connection's Y value.
  197. * @param {number} maxRadius The maximum radius to another connection.
  198. * @return {boolean} True if connection is in range.
  199. * @private
  200. */
  201. Blockly.ConnectionDB.prototype.isInYRange_ = function(index, baseY, maxRadius) {
  202. return (Math.abs(this[index].y_ - baseY) <= maxRadius);
  203. };
  204. /**
  205. * Find the closest compatible connection to this connection.
  206. * @param {!Blockly.Connection} conn The connection searching for a compatible
  207. * mate.
  208. * @param {number} maxRadius The maximum radius to another connection.
  209. * @param {!goog.math.Coordinate} dxy Offset between this connection's location
  210. * in the database and the current location (as a result of dragging).
  211. * @return {!{connection: ?Blockly.Connection, radius: number}} Contains two
  212. * properties:' connection' which is either another connection or null,
  213. * and 'radius' which is the distance.
  214. */
  215. Blockly.ConnectionDB.prototype.searchForClosest = function(conn, maxRadius,
  216. dxy) {
  217. // Don't bother.
  218. if (!this.length) {
  219. return {connection: null, radius: maxRadius};
  220. }
  221. // Stash the values of x and y from before the drag.
  222. var baseY = conn.y_;
  223. var baseX = conn.x_;
  224. conn.x_ = baseX + dxy.x;
  225. conn.y_ = baseY + dxy.y;
  226. // findPositionForConnection finds an index for insertion, which is always
  227. // after any block with the same y index. We want to search both forward
  228. // and back, so search on both sides of the index.
  229. var closestIndex = this.findPositionForConnection_(conn);
  230. var bestConnection = null;
  231. var bestRadius = maxRadius;
  232. var temp;
  233. // Walk forward and back on the y axis looking for the closest x,y point.
  234. var pointerMin = closestIndex - 1;
  235. while (pointerMin >= 0 && this.isInYRange_(pointerMin, conn.y_, maxRadius)) {
  236. temp = this[pointerMin];
  237. if (conn.isConnectionAllowed(temp, bestRadius)) {
  238. bestConnection = temp;
  239. bestRadius = temp.distanceFrom(conn);
  240. }
  241. pointerMin--;
  242. }
  243. var pointerMax = closestIndex;
  244. while (pointerMax < this.length && this.isInYRange_(pointerMax, conn.y_,
  245. maxRadius)) {
  246. temp = this[pointerMax];
  247. if (conn.isConnectionAllowed(temp, bestRadius)) {
  248. bestConnection = temp;
  249. bestRadius = temp.distanceFrom(conn);
  250. }
  251. pointerMax++;
  252. }
  253. // Reset the values of x and y.
  254. conn.x_ = baseX;
  255. conn.y_ = baseY;
  256. // If there were no valid connections, bestConnection will be null.
  257. return {connection: bestConnection, radius: bestRadius};
  258. };
  259. /**
  260. * Initialize a set of connection DBs for a specified workspace.
  261. * @param {!Blockly.Workspace} workspace The workspace this DB is for.
  262. */
  263. Blockly.ConnectionDB.init = function(workspace) {
  264. // Create four databases, one for each connection type.
  265. var dbList = [];
  266. dbList[Blockly.INPUT_VALUE] = new Blockly.ConnectionDB();
  267. dbList[Blockly.OUTPUT_VALUE] = new Blockly.ConnectionDB();
  268. dbList[Blockly.NEXT_STATEMENT] = new Blockly.ConnectionDB();
  269. dbList[Blockly.PREVIOUS_STATEMENT] = new Blockly.ConnectionDB();
  270. workspace.connectionDBList = dbList;
  271. };