summaryrefslogtreecommitdiffstats
path: root/qemu/slirp/udp.c
blob: 247024fd86a7558055e8d782aeb2ec79f2b1bee1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
 * Copyright (c) 1982, 1986, 1988, 1990, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)udp_usrreq.c	8.4 (Berkeley) 1/21/94
 * udp_usrreq.c,v 1.4 1994/10/02 17:48:45 phk Exp
 */

/*
 * Changes and additions relating to SLiRP
 * Copyright (c) 1995 Danny Gasparovski.
 *
 * Please read the file COPYRIGHT for the
 * terms and conditions of the copyright.
 */

#include "qemu/osdep.h"
#include <slirp.h>
#include "ip_icmp.h"

static uint8_t udp_tos(struct socket *so);

void
udp_init(Slirp *slirp)
{
    slirp->udb.so_next = slirp->udb.so_prev = &slirp->udb;
    slirp->udp_last_so = &slirp->udb;
}

void udp_cleanup(Slirp *slirp)
{
    while (slirp->udb.so_next != &slirp->udb) {
        udp_detach(slirp->udb.so_next);
    }
}

/* m->m_data  points at ip packet header
 * m->m_len   length ip packet
 * ip->ip_len length data (IPDU)
 */
void
udp_input(register struct mbuf *m, int iphlen)
{
	Slirp *slirp = m->slirp;
	register struct ip *ip;
	register struct udphdr *uh;
	int len;
	struct ip save_ip;
	struct socket *so;
	struct sockaddr_storage lhost;
	struct sockaddr_in *lhost4;

	DEBUG_CALL("udp_input");
	DEBUG_ARG("m = %p", m);
	DEBUG_ARG("iphlen = %d", iphlen);

	/*
	 * Strip IP options, if any; should skip this,
	 * make available to user, and use on returned packets,
	 * but we don't yet have a way to check the checksum
	 * with options still present.
	 */
	if(iphlen > sizeof(struct ip)) {
		ip_stripoptions(m, (struct mbuf *)0);
		iphlen = sizeof(struct ip);
	}

	/*
	 * Get IP and UDP header together in first mbuf.
	 */
	ip = mtod(m, struct ip *);
	uh = (struct udphdr *)((caddr_t)ip + iphlen);

	/*
	 * Make mbuf data length reflect UDP length.
	 * If not enough data to reflect UDP length, drop.
	 */
	len = ntohs((uint16_t)uh->uh_ulen);

	if (ip->ip_len != len) {
		if (len > ip->ip_len) {
			goto bad;
		}
		m_adj(m, len - ip->ip_len);
		ip->ip_len = len;
	}

	/*
	 * Save a copy of the IP header in case we want restore it
	 * for sending an ICMP error message in response.
	 */
	save_ip = *ip;
	save_ip.ip_len+= iphlen;         /* tcp_input subtracts this */

	/*
	 * Checksum extended UDP header and data.
	 */
	if (uh->uh_sum) {
      memset(&((struct ipovly *)ip)->ih_mbuf, 0, sizeof(struct mbuf_ptr));
	  ((struct ipovly *)ip)->ih_x1 = 0;
	  ((struct ipovly *)ip)->ih_len = uh->uh_ulen;
	  if(cksum(m, len + sizeof(struct ip))) {
	    goto bad;
	  }
	}

	lhost.ss_family = AF_INET;
	lhost4 = (struct sockaddr_in *) &lhost;
	lhost4->sin_addr = ip->ip_src;
	lhost4->sin_port = uh->uh_sport;

        /*
         *  handle DHCP/BOOTP
         */
        if (ntohs(uh->uh_dport) == BOOTP_SERVER &&
            (ip->ip_dst.s_addr == slirp->vhost_addr.s_addr ||
             ip->ip_dst.s_addr == 0xffffffff)) {
                bootp_input(m);
                goto bad;
            }

        /*
         *  handle TFTP
         */
        if (ntohs(uh->uh_dport) == TFTP_SERVER &&
            ip->ip_dst.s_addr == slirp->vhost_addr.s_addr) {
            m->m_data += iphlen;
            m->m_len -= iphlen;
            tftp_input(&lhost, m);
            m->m_data -= iphlen;
            m->m_len += iphlen;
            goto bad;
        }

        if (slirp->restricted) {
            goto bad;
        }

	/*
	 * Locate pcb for datagram.
	 */
	so = solookup(&slirp->udp_last_so, &slirp->udb, &lhost, NULL);

	if (so == NULL) {
	  /*
	   * If there's no socket for this packet,
	   * create one
	   */
	  so = socreate(slirp);
	  if (!so) {
	      goto bad;
	  }
	  if (udp_attach(so, AF_INET) == -1) {
	    DEBUG_MISC((dfd," udp_attach errno = %d-%s\n",
			errno,strerror(errno)));
	    sofree(so);
	    goto bad;
	  }

	  /*
	   * Setup fields
	   */
	  so->so_lfamily = AF_INET;
	  so->so_laddr = ip->ip_src;
	  so->so_lport = uh->uh_sport;

	  if ((so->so_iptos = udp_tos(so)) == 0)
	    so->so_iptos = ip->ip_tos;

	  /*
	   * XXXXX Here, check if it's in udpexec_list,
	   * and if it is, do the fork_exec() etc.
	   */
	}

        so->so_ffamily = AF_INET;
        so->so_faddr = ip->ip_dst; /* XXX */
        so->so_fport = uh->uh_dport; /* XXX */

	iphlen += sizeof(struct udphdr);
	m->m_len -= iphlen;
	m->m_data += iphlen;

	/*
	 * Now we sendto() the packet.
	 */
	if(sosendto(so,m) == -1) {
	  m->m_len += iphlen;
	  m->m_data -= iphlen;
	  *ip=save_ip;
	  DEBUG_MISC((dfd,"udp tx errno = %d-%s\n",errno,strerror(errno)));
	  icmp_send_error(m, ICMP_UNREACH, ICMP_UNREACH_NET, 0,
	                  strerror(errno));
	  goto bad;
	}

	m_free(so->so_m);   /* used for ICMP if error on sorecvfrom */

	/* restore the orig mbuf packet */
	m->m_len += iphlen;
	m->m_data -= iphlen;
	*ip=save_ip;
	so->so_m=m;         /* ICMP backup */

	return;
bad:
	m_free(m);
}

int udp_output(struct socket *so, struct mbuf *m,
                struct sockaddr_in *saddr, struct sockaddr_in *daddr,
                int iptos)
{
	register struct udpiphdr *ui;
	int error = 0;

	DEBUG_CALL("udp_output");
	DEBUG_ARG("so = %p", so);
	DEBUG_ARG("m = %p", m);
	DEBUG_ARG("saddr = %lx", (long)saddr->sin_addr.s_addr);
	DEBUG_ARG("daddr = %lx", (long)daddr->sin_addr.s_addr);

	/*
	 * Adjust for header
	 */
	m->m_data -= sizeof(struct udpiphdr);
	m->m_len += sizeof(struct udpiphdr);

	/*
	 * Fill in mbuf with extended UDP header
	 * and addresses and length put into network format.
	 */
	ui = mtod(m, struct udpiphdr *);
    memset(&ui->ui_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));
	ui->ui_x1 = 0;
	ui->ui_pr = IPPROTO_UDP;
	ui->ui_len = htons(m->m_len - sizeof(struct ip));
	/* XXXXX Check for from-one-location sockets, or from-any-location sockets */
        ui->ui_src = saddr->sin_addr;
	ui->ui_dst = daddr->sin_addr;
	ui->ui_sport = saddr->sin_port;
	ui->ui_dport = daddr->sin_port;
	ui->ui_ulen = ui->ui_len;

	/*
	 * Stuff checksum and output datagram.
	 */
	ui->ui_sum = 0;
	if ((ui->ui_sum = cksum(m, m->m_len)) == 0)
		ui->ui_sum = 0xffff;
	((struct ip *)ui)->ip_len = m->m_len;

	((struct ip *)ui)->ip_ttl = IPDEFTTL;
	((struct ip *)ui)->ip_tos = iptos;

	error = ip_output(so, m);

	return (error);
}

int
udp_attach(struct socket *so, unsigned short af)
{
  so->s = qemu_socket(af, SOCK_DGRAM, 0);
  if (so->s != -1) {
    so->so_expire = curtime + SO_EXPIRE;
    insque(so, &so->slirp->udb);
  }
  return(so->s);
}

void
udp_detach(struct socket *so)
{
	closesocket(so->s);
	sofree(so);
}

static const struct tos_t udptos[] = {
	{0, 53, IPTOS_LOWDELAY, 0},			/* DNS */
	{0, 0, 0, 0}
};

static uint8_t
udp_tos(struct socket *so)
{
	int i = 0;

	while(udptos[i].tos) {
		if ((udptos[i].fport && ntohs(so->so_fport) == udptos[i].fport) ||
		    (udptos[i].lport && ntohs(so->so_lport) == udptos[i].lport)) {
		    	so->so_emu = udptos[i].emu;
			return udptos[i].tos;
		}
		i++;
	}

	return 0;
}

struct socket *
udp_listen(Slirp *slirp, uint32_t haddr, u_int hport, uint32_t laddr,
           u_int lport, int flags)
{
	struct sockaddr_in addr;
	struct socket *so;
	socklen_t addrlen = sizeof(struct sockaddr_in);

	so = socreate(slirp);
	if (!so) {
	    return NULL;
	}
	so->s = qemu_socket(AF_INET,SOCK_DGRAM,0);
	so->so_expire = curtime + SO_EXPIRE;
	insque(so, &slirp->udb);

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = haddr;
	addr.sin_port = hport;

	if (bind(so->s,(struct sockaddr *)&addr, addrlen) < 0) {
		udp_detach(so);
		return NULL;
	}
	socket_set_fast_reuse(so->s);

	getsockname(so->s,(struct sockaddr *)&addr,&addrlen);
	so->fhost.sin = addr;
	sotranslate_accept(so);
	so->so_lfamily = AF_INET;
	so->so_lport = lport;
	so->so_laddr.s_addr = laddr;
	if (flags != SS_FACCEPTONCE)
	   so->so_expire = 0;

	so->so_state &= SS_PERSISTENT_MASK;
	so->so_state |= SS_ISFCONNECTED | flags;

	return so;
}
an>); } self.renderer.context = null; self.renderer.domElement = null; self.renderer = null; self.camera = null; self.controls = null; self.scene = null; self.labelGroup = null; cancelAnimationFrame(self.requestId); } } D3THREE.prototype.stop = function() { this.running = false; } D3THREE.prototype.render = function(element, data) { element.render(data); } D3THREE.createAxis = function(dt) { return new D3THREE.Axis(dt); } // d3three axis D3THREE.Axis = function(dt) { this._scale = d3.scale.linear(); this._orient = "x"; this._tickFormat = function(d) { return d }; this._dt = dt; } D3THREE.Axis.prototype.orient = function(o) { if (o) { this._dt.axisObjects[o] = this; this._orient = o; } return this; } D3THREE.Axis.prototype.scale = function(s) { if (s) { this._scale = s; } return this; } D3THREE.Axis.prototype.tickFormat = function(f) { if (f) { this._tickFormat = f; } return this; } D3THREE.Axis.prototype.interval = function() { var interval; if (typeof(this._scale.rangeBand) === 'function') { // ordinal scale interval = this._scale.range()[1]; } else { interval = this._scale.range()[1] / (this._scale.ticks().length - 1); } return interval; } D3THREE.Axis.prototype.ticks = function() { var ticks; if (typeof(this._scale.rangeBand) === 'function') { // ordinal scale ticks = this._scale.domain(); } else { ticks = this._scale.ticks(); } return ticks; } D3THREE.Axis.prototype.getRotationShift = function() { return this.interval() * (this.ticks().length - 1) / 2; } D3THREE.Axis.prototype.render = function() { var material = new THREE.LineBasicMaterial({ color: 0xbbbbbb, linewidth: 2 }); var tickMaterial = new THREE.LineBasicMaterial({ color: 0xbbbbbb, linewidth: 1 }); var geometry = new THREE.Geometry(); interval = this.interval(); var interval = this.interval(), ticks = this.ticks(); // x,y axis shift, so rotation is from center of screen var xAxisShift = this._dt.axisObjects.x.getRotationShift(), yAxisShift = this._dt.axisObjects.y.getRotationShift(); for (var i = 0; i < ticks.length; i++) { var tickMarGeometry = new THREE.Geometry(); var shape = new THREE.TextGeometry(this._tickFormat(ticks[i]), { size: 5, height: 1, curveSegments: 20 }); var wrapper = new THREE.MeshBasicMaterial({color: 0xbbbbbb}); var words = new THREE.Mesh(shape, wrapper); if (this._orient === "y") { // tick geometry.vertices.push(new THREE.Vector3(i * interval - yAxisShift, chartOffset, 0 - xAxisShift)); tickMarGeometry.vertices.push(new THREE.Vector3(i * interval - yAxisShift, chartOffset, 0 - xAxisShift)); tickMarGeometry.vertices.push(new THREE.Vector3(i * interval - yAxisShift, -10 + chartOffset, 0 - xAxisShift)); var tickLine = new THREE.Line(tickMarGeometry, tickMaterial); this._dt.scene.add(tickLine); if (i * interval > this._dt.maxY) { this._dt.maxY = i * interval; } words.position.set(i * interval - yAxisShift, -20 + chartOffset, 0 - xAxisShift); } else if (this._orient === "z") { // tick geometry.vertices.push(new THREE.Vector3(0 + this._dt.maxY - yAxisShift, i * interval + chartOffset, 0 - xAxisShift)); tickMarGeometry.vertices.push(new THREE.Vector3(0 + this._dt.maxY - yAxisShift, i * interval + chartOffset, 0 - xAxisShift)); tickMarGeometry.vertices.push(new THREE.Vector3(10 + this._dt.maxY - yAxisShift, i * interval + chartOffset, 0 - xAxisShift)); var tickLine = new THREE.Line(tickMarGeometry, tickMaterial); this._dt.scene.add(tickLine); words.position.set(20 + this._dt.maxY - yAxisShift, i * interval + chartOffset, 0 - xAxisShift); } else if (this._orient === "x") { // tick geometry.vertices.push(new THREE.Vector3(0 - yAxisShift, chartOffset, i * interval - xAxisShift)); tickMarGeometry.vertices.push(new THREE.Vector3(0 - yAxisShift, 0 + chartOffset, i * interval - xAxisShift)); tickMarGeometry.vertices.push(new THREE.Vector3(0 - yAxisShift, -10 + chartOffset, i * interval - xAxisShift)); var tickLine = new THREE.Line(tickMarGeometry, tickMaterial); this._dt.scene.add(tickLine); words.position.set(0 - yAxisShift, -20 + chartOffset, i * interval - xAxisShift); } this._dt.labelGroup.add(words); } var line = new THREE.Line(geometry, material); this._dt.scene.add(line); } // Chart object D3THREE.Chart = function() { } D3THREE.Chart.prototype.config = function(c) { this._config = $.extend(this._config, c); } D3THREE.Chart.prototype.init = function(dt) { this._dt = dt; // mouse move var self = this; this._dt.renderer.domElement.addEventListener( 'mousemove', function(e) { self.onDocumentMouseMove(e); }, false ); } var cumulativeOffset = function(element) { var top = 0, left = 0; do { top += element.offsetTop || 0; left += element.offsetLeft || 0; element = element.offsetParent; } while(element); return { top: top, left: left }; }; D3THREE.Chart.prototype.detectNodeHover = function(e) { var boundingRect = this._dt.renderer.domElement.getBoundingClientRect(); var vector = new THREE.Vector3(); vector.x = ( (e.clientX - boundingRect.left) / this._dt.renderer.domElement.width ) * 2 - 1; vector.y = 1 - ( (e.clientY - boundingRect.top) / this._dt.renderer.domElement.height ) * 2; vector.z = 1; // create a check ray vector.unproject( this._dt.camera ); var ray = new THREE.Raycaster( this._dt.camera.position, vector.sub( this._dt.camera.position ).normalize() ); var intersects = ray.intersectObjects( this._nodeGroup.children ); for (var i = 0; i < this._nodeGroup.children.length; i++) { this._nodeGroup.children[i].material.opacity = 1; } if (intersects.length > 0) { var obj = intersects[0].object; obj.material.opacity = 0.5; var html = ""; html += "<div class=\"tooltip_kv\">"; html += "<span>"; html += "x: " + this._dt.axisObjects.x._tickFormat(obj.userData.x); html += "</span><br>"; html += "<span>"; html += "y: " + this._dt.axisObjects.y._tickFormat(obj.userData.y); html += "</span><br>"; html += "<span>"; html += "z: " + this._dt.axisObjects.z._tickFormat(obj.userData.z); html += "</span><br>"; html += "</div>"; document.getElementById("tooltip-container").innerHTML = html; document.getElementById("tooltip-container").style.display = "block"; document.getElementById("tooltip-container").style.top = (e.pageY + 10) + "px"; document.getElementById("tooltip-container").style.left = (e.pageX + 10) + "px"; } else { document.getElementById("tooltip-container").style.display = "none"; } } // Scatter plot D3THREE.Scatter = function(dt) { this.init(dt); this._nodeGroup = new THREE.Object3D(); this._config = {color: 0x4682B4, pointRadius: 5}; } D3THREE.Scatter.prototype = new D3THREE.Chart(); D3THREE.Scatter.prototype.onDocumentMouseMove = function(e) { // detect intersected spheres this.detectNodeHover(e); } D3THREE.Scatter.prototype.render = function(data) { var geometry = new THREE.SphereGeometry( this._config.pointRadius, 32, 32 ); this._dt.scene.add(this._nodeGroup); // x,y axis shift, so rotation is from center of screen var xAxisShift = this._dt.axisObjects.x.getRotationShift(), yAxisShift = this._dt.axisObjects.y.getRotationShift(); var self = this; d3.select(this._nodeGroup) .selectAll() .data(data) .enter().append( function(d) { var material = new THREE.MeshBasicMaterial( { color: self._config.color } ); var mesh = new THREE.Mesh( geometry, material ); mesh.userData = {x: d.x, y: d.y, z: d.z}; return mesh; } ) .attr("position.z", function(d) { return self._dt.axisObjects.x._scale(d.x) - xAxisShift; }) .attr("position.x", function(d) { return self._dt.axisObjects.y._scale(d.y) - yAxisShift; }) .attr("position.y", function(d) { return self._dt.axisObjects.z._scale(d.z) + chartOffset; }); } // Surface plot D3THREE.Surface = function(dt) { this.init(dt); this._nodeGroup = new THREE.Object3D(); this._config = {color: 0x4682B4, pointColor: 0xff7f0e, pointRadius: 2}; } D3THREE.Surface.prototype = new D3THREE.Chart(); D3THREE.Surface.prototype.onDocumentMouseMove = function(e) { // detect intersected spheres var boundingRect = this._dt.renderer.domElement.getBoundingClientRect(); var vector = new THREE.Vector3(); vector.x = ( (e.clientX - boundingRect.left) / this._dt.renderer.domElement.width ) * 2 - 1; vector.y = 1 - ( (e.clientY - boundingRect.top) / this._dt.renderer.domElement.height ) * 2; vector.z = 1; // create a check ray vector.unproject( this._dt.camera ); var ray = new THREE.Raycaster( this._dt.camera.position, vector.sub( this._dt.camera.position ).normalize() ); var meshIntersects = ray.intersectObjects( [this._meshSurface] ); if (meshIntersects.length > 0) { for (var i = 0; i < this._nodeGroup.children.length; i++) { this._nodeGroup.children[i].visible = true; this._nodeGroup.children[i].material.opacity = 1; } this.detectNodeHover(e); } else { // hide nodes for (var i = 0; i < this._nodeGroup.children.length; i++) { this._nodeGroup.children[i].visible = false; } } } D3THREE.Surface.prototype.render = function(threeData) { /* render data points */ var geometry = new THREE.SphereGeometry( this._config.pointRadius, 32, 32 ); this._dt.scene.add(this._nodeGroup); // x,y axis shift, so rotation is from center of screen var xAxisShift = this._dt.axisObjects.x.getRotationShift(), yAxisShift = this._dt.axisObjects.y.getRotationShift(); var self = this; d3.select(this._nodeGroup) .selectAll() .data(threeData) .enter().append( function(d) { var material = new THREE.MeshBasicMaterial( { color: self._config.pointColor } ); var mesh = new THREE.Mesh( geometry, material ); mesh.userData = {x: d.x, y: d.y, z: d.z}; mesh.visible = false; return mesh; } ) .attr("position.z", function(d) { return self._dt.axisObjects.x._scale(d.x) - xAxisShift; }) .attr("position.x", function(d) { return self._dt.axisObjects.y._scale(d.y) - yAxisShift; }) .attr("position.y", function(d) { return self._dt.axisObjects.z._scale(d.z) + chartOffset; }); /* custom surface */ function distance (v1, v2) { var dx = v1.x - v2.x; var dy = v1.y - v2.y; var dz = v1.z - v2.z; return Math.sqrt(dx*dx+dz*dz); } var vertices = []; var holes = []; var triangles, mesh; var geometry = new THREE.Geometry(); var material = new THREE.MeshBasicMaterial({color: this._config.color}); for (var i = 0; i < threeData.length; i++) { vertices.push(new THREE.Vector3( self._dt.axisObjects.y._scale(threeData[i].y) - yAxisShift, self._dt.axisObjects.z._scale(threeData[i].z) + chartOffset, self._dt.axisObjects.x._scale(threeData[i].x) - xAxisShift)); } geometry.vertices = vertices; for (var i = 0; i < vertices.length; i++) { // find three closest vertices to generate surface var v1, v2, v3; var distances = []; // find vertices in same y or y + 1 row var minY = Number.MAX_VALUE; for (var j = i + 1; j < vertices.length; j++) { if (i !== j && vertices[j].x > vertices[i].x) { if (vertices[j].x < minY) { minY = vertices[j].x; } } } var rowVertices = [], row2Vertices = []; for (var j = i + 1; j < vertices.length; j++) { if (i !== j && (vertices[j].x === vertices[i].x)) { rowVertices.push({index: j, v: vertices[j]}); } if (i !== j && (vertices[j].x === minY)) { row2Vertices.push({index: j, v: vertices[j]}); } } if (rowVertices.length >= 1 && row2Vertices.length >= 2) { // find smallest x rowVertices.sort(function(a, b) { if (a.v.z < b.v.z) { return -1; } else if (a.v.z === b.v.z) { return 0; } else { return 1; } }); v1 = rowVertices[0].index; row2Vertices.sort(function(a, b) { if (a.v.z < b.v.z) { return -1; } else if (a.v.z === b.v.z) { return 0; } else { return 1; } }); v2 = row2Vertices[0].index; v3 = row2Vertices[1].index; var fv = [i, v1, v2, v3]; fv = fv.sort(function(a, b) { if (a < b) return -1; else if (a === b) return 0; else return 1; }); geometry.faces.push( new THREE.Face3(fv[1], fv[0], fv[3])); geometry.faces.push( new THREE.Face3(fv[0], fv[2], fv[3])); } } this._meshSurface = new THREE.Mesh( geometry, material ); this._dt.scene.add(this._meshSurface); } // Bar plot D3THREE.Bar = function(dt) { this.init(dt); this._nodeGroup = new THREE.Object3D(); this._config = {color: 0x4682B4, barSize: 5}; } D3THREE.Bar.prototype = new D3THREE.Chart(); D3THREE.Bar.prototype.onDocumentMouseMove = function(e) { this.detectNodeHover(e); } D3THREE.Bar.prototype.render = function(threeData) { /* render data points */ this._dt.scene.add(this._nodeGroup); // x,y axis shift, so rotation is from center of screen var xAxisShift = this._dt.axisObjects.x.getRotationShift(), yAxisShift = this._dt.axisObjects.y.getRotationShift(); var self = this; d3.select(this._nodeGroup) .selectAll() .data(threeData) .enter().append( function(d) { var height = self._dt.axisObjects.z._scale(d.z) + chartOffset; var geometry = new THREE.BoxGeometry( self._config.barSize, height, self._config.barSize ); var material = new THREE.MeshBasicMaterial( { color: self._config.color } ); var mesh = new THREE.Mesh( geometry, material ); mesh.userData = {x: d.x, y: d.y, z: d.z}; return mesh; } ) .attr("position.z", function(d) { return self._dt.axisObjects.x._scale(d.x) - xAxisShift; }) .attr("position.x", function(d) { return self._dt.axisObjects.y._scale(d.y) - yAxisShift; }) .attr("position.y", function(d) { var height = self._dt.axisObjects.z._scale(d.z) + chartOffset; return height / 2; }); } // Force layout plot D3THREE.Force = function(dt) { this.init(dt); this._nodeGroup = new THREE.Object3D(); this._config = {color: 0x4682B4, linkColor: 0xcccccc, linkWidth: 1}; } D3THREE.Force.prototype = new D3THREE.Chart(); D3THREE.Force.prototype.onDocumentMouseMove = function(e) { } D3THREE.Force.prototype.render = function(threeData) { var spheres = [], three_links = []; // Define the 3d force var force = d3.layout.force3d() .nodes(sort_data=[]) .links(links=[]) .size([50, 50]) .gravity(0.3) .charge(-400) var DISTANCE = 1; for (var i = 0; i < threeData.nodes.length; i++) { sort_data.push({x:threeData.nodes.x + DISTANCE,y:threeData.nodes.y + DISTANCE,z:0}) // set up the sphere vars var radius = 5, segments = 16, rings = 16; // create the sphere's material var sphereMaterial = new THREE.MeshLambertMaterial({ color: this._config.color }); var sphere = new THREE.Mesh( new THREE.SphereGeometry( radius, segments, rings), sphereMaterial); spheres.push(sphere); // add the sphere to the scene this._dt.scene.add(sphere); } for (var i = 0; i < threeData.links.length; i++) { links.push({target:sort_data[threeData.links[i].target],source:sort_data[threeData.links[i].source]}); var material = new THREE.LineBasicMaterial({ color: this._config.linkColor, linewidth: this._config.linkWidth}); var geometry = new THREE.Geometry(); geometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) ); geometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) ); var line = new THREE.Line( geometry, material ); line.userData = { source: threeData.links[i].source, target: threeData.links[i].target }; three_links.push(line); this._dt.scene.add(line); force.start(); } // set up the axes var x = d3.scale.linear().domain([0, 350]).range([0, 10]), y = d3.scale.linear().domain([0, 350]).range([0, 10]), z = d3.scale.linear().domain([0, 350]).range([0, 10]); var self = this; force.on("tick", function(e) { for (var i = 0; i < sort_data.length; i++) { spheres[i].position.set(x(sort_data[i].x) * 40 - 40, y(sort_data[i].y) * 40 - 40,z(sort_data[i].z) * 40 - 40); for (var j = 0; j < three_links.length; j++) { var line = three_links[j]; var vi = -1; if (line.userData.source === i) { vi = 0; } if (line.userData.target === i) { vi = 1; } if (vi >= 0) { line.geometry.vertices[vi].x = x(sort_data[i].x) * 40 - 40; line.geometry.vertices[vi].y = y(sort_data[i].y) * 40 - 40; line.geometry.vertices[vi].z = y(sort_data[i].z) * 40 - 40; line.geometry.verticesNeedUpdate = true; } } } }); }