aboutsummaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: 17eb0e5d849543cf200915d23feecd869b42ef12 (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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
#include <cmath>
#include <csignal>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <sys/stat.h>
#include <sys/types.h>

#include <readline/readline.h>
#include <readline/history.h>

#include "gnuplot_i.hpp"

#include <fml/fml.h>

// under $HOME
#define HISTORY_FILE ".fieldviz_history"

using namespace fml;
using namespace std;

/* A current or charge distribution */
struct Entity {
    /* can bitwise-OR together */
    enum { CHARGE = 1 << 0, CURRENT = 1 << 1 } type;
    union {
        scalar Q_density; /* linear charge density */
        scalar I; /* current */
    };

    Manifold *path;
};

vec3 point;

/* dl x r / (|r| ^ 2) */
vec3 dB(vec3 s, vec3 ds)
{
    vec3 r = point - s;

    scalar r2 = r.magnitudeSquared();

    vec3 rnorm = r / std::sqrt(r2);

    return ds.cross(rnorm) / r2;
}

/* dl * r / (|r| ^ 2) */
vec3 dE(vec3 s, vec3 ds)
{
    vec3 r = point - s;

    scalar r2 = r.magnitudeSquared();

    vec3 rnorm = r / std::sqrt(r2);

    return rnorm * ds.magnitude() / r2;
}

int ent_counter = 0;
map<int, Entity> entities;

int add_entity(Entity e)
{
    entities[ent_counter] = e;
    return ent_counter++;
}

int add_current(scalar I, Manifold *path)
{
    return add_entity((Entity){ Entity::CURRENT, I, path });
}

int add_charge(scalar Q_density, Manifold *path)
{
    return add_entity((Entity){ Entity::CHARGE, Q_density, path });
}

const scalar U0 = 4e-7 * M_PI;
const scalar C = 299792458;
const scalar E0 = 1 / ( U0 * C * C );
const scalar K_E = 1 / (4 * M_PI * E0);
const scalar DEFAULT_D = 1e-1;
scalar D = DEFAULT_D;

vec3 calc_Bfield(vec3 x)
{
    point = x;

    vec3 B = 0;

    for(map<int, Entity>::iterator i = entities.begin(); i != entities.end(); i++)
    {
        Entity &e = i->second;
        if(e.type == Entity::CURRENT)
            B += e.path->integrate(dB, D) * U0 * e.I;
    }

    return B;
}

vec3 calc_Efield(vec3 x)
{
    point = x;

    vec3 E = 0;

    for(map<int, Entity>::iterator i = entities.begin(); i != entities.end(); i++)
    {
        Entity &e = i->second;
        if(e.type == Entity::CHARGE)
            E += e.path->integrate(dE, D) * K_E * e.Q_density;
    }

    return E;
}

ostream *dump_ofs = NULL;

vec3 dump(vec3 s, vec3 ds)
{
    *dump_ofs << s << " " << ds << endl;

    return 0;
}

void dump_points(ostream &out, Manifold *c)
{
    dump_ofs = &out;
    c->integrate(dump, D);
}

int dump_entities(ostream &out, int which, map<int, Entity> &en)
{
    int count = 0;
    for(map<int, Entity>::iterator i = en.begin(); i != en.end(); i++)
    {
        Entity &e = i->second;
        if(which & e.type)
        {
            dump_points(out, e.path);

            /* two blank lines mark an index in gnuplot */
            out << endl << endl;

            count++;
        }
    }

    return count;
}

/* dump the field vectors with a spacing of `delta' */
/* requires x0 < x1, y0 < y1, z0 < z1 */

enum FieldType { E, B };

/* dump field in a region of space to vectors */
void dump_field(ostream &out,
                enum FieldType type,
                vec3 lower_corner, vec3 upper_corner,
                scalar delta)
{
    for(scalar z = lower_corner[2]; z <= upper_corner[2]; z += delta)
        for(scalar y = lower_corner[1]; y <= upper_corner[1]; y += delta)
            for(scalar x = lower_corner[0]; x <= upper_corner[0]; x += delta)
            {
                vec3 pt(x, y, z);
                vec3 field = (type == E) ? calc_Efield(pt) : calc_Bfield(pt);

                field = field.normalize() / 10;
                out << pt << " " << field << endl;
            }
}

/* trace a field line */
void dump_fieldline(ostream &out, vec3 x, scalar len)
{
    point = x;
    scalar delta = .1;
    while(len > 0)
    {
        out << point << endl;

        vec3 B = calc_Bfield(point);

        point += delta * B;
        len -= delta;
    }
}

/* dump field magnitudes along a line */
void dump_values(vec3 start, vec3 del, int times)
{
    point = start;
    while(times--)
    {
        point += del;
    }
}

void all_lower(string &str)
{
    for(int i = 0; i < str.length(); i++)
        str[i] = tolower(str[i]);
}

string itoa(int n)
{
    stringstream ss;
    ss << n;
    return ss.str();
}

Manifold *parse_curve(stringstream &ss)
{
    string type;
    ss >> type;
    if(type == "line" || type == "linesegment")
    {
        vec3 a, b;
        ss >> a >> b;
        return (Curve*)new LineSegment(a, b);
    }
    else if(type == "arc")
    {
        vec3 center, radius, normal;
        scalar angle;
        ss >> center >> radius >> normal;
        ss >> angle;
        return (Curve*)new Arc(center, radius, normal, angle);
    }
    else if(type == "spiral" || type == "solenoid")
    {
        vec3 origin, radius, normal;
        scalar angle, pitch;
        ss >> origin >> radius >> normal >> angle >> pitch;
        return (Curve*)new Spiral(origin, radius, normal, angle, pitch);
    }
    else if(type == "toroid")
    {
        vec3 origin, maj_radius, maj_normal;
        scalar min_radius, maj_angle, pitch;
        ss >> origin >> maj_radius >> maj_normal;
        ss >> min_radius >> maj_angle >> pitch;

        return (Curve*)new Toroid(origin, maj_radius, maj_normal, maj_angle, min_radius, pitch);
    }
    else if(type == "plane")
    {
        vec3 origin, v1, v2;
        ss >> origin >> v1 >> v2;
        return (Surface*)new Plane(origin, v1, v2);
    }
    else if(type == "disk")
    {
        vec3 center, radius, normal;
        scalar angle;
        ss >> center >> radius >> normal >> angle;
        return (Surface*)new Disk(center, radius, normal, angle);
    }
    else if(type == "sphere")
    {
        vec3 center;
        scalar radius;
        ss >> center >> radius;

        return (Surface*)new Sphere(center, radius);
    }
    else if(type == "opencylinder")
    {
        vec3 origin, axis;
        scalar rad;
        ss >> origin >> axis >> rad;
        return (Surface*)new OpenCylinder(origin, axis, rad);
    }
    else if(type == "closedcylinder")
    {
        vec3 origin, axis;
        scalar rad;
        ss >> origin >> axis >> rad;
        return (Surface*)new ClosedCylinder(origin, axis, rad);
    }
    else throw "unknown curve type (must be line, arc, spiral, or toroid)";
}

void print_help()
{
    cout << endl;
    cout << "fieldviz 0.1" << endl;
    cout << "Copyright (C) 2019 Franklin Wei" << endl << endl;

    cout << "Commands:" << endl;
    cout << "  add {I CURRENT|Q DENSITY} MANIFOLD" << endl;
    cout << "    Add an entity of the specified type and the shape MANIFOLD, which can be:" << endl;
    cout << "    of (<X> is a 3-tuple specifying a vector):" << endl;
    cout << "     1-manifolds:" << endl;
    cout << "      line <a> <b>" << endl;
    cout << "      arc <center> <radius> <normal> angle" << endl;
    cout << "      solenoid <center> <radius> <normal> angle pitch" << endl;
    cout << "      toroid <center> <radius> <maj_normal> min_radius maj_angle pitch" << endl;
    cout << "     2-manifolds:" << endl;
    cout << "      plane <origin> <vec1> <vec2>" << endl;
    cout << "      disk <center> <radius> <normal> angle" << endl;
    cout << "      sphere <center> radius" << endl;
    cout << endl;
    cout << "  delete [ID..]" << endl;
    cout << "    Delete an entity by its previously returned identifier." << endl;
    cout << endl;
    cout << "  draw [I|Q] ..." << endl;
    cout << "    Draw the specified current/charge distributions" << endl;
    cout << endl;
    cout << "  field [E|B] <lower_corner> <upper_corner> DELTA" << endl;
    cout << "    Plot the E or B field in the rectangular prism bounded by lower and upper." << endl;
    cout << "    DELTA specifies density." << endl;
    cout << endl;
    cout << "  newwindow" << endl;
    cout << "    Make future plots go into a new window" << endl;
    cout << endl;
    cout << "  delta D" << endl;
    cout << "    Set integration fineness to D (smaller is better but slower)" << endl;
}

vec3 dA(vec3 s, vec3 dA)
{
    /* will cast to vec3 */
    return dA.magnitude();
}

string hist_path;

void exit_handler()
{
    write_history(hist_path.c_str());
}

void int_handler(int a)
{
    (void) a;
    exit(0);
}

int main(int argc, char *argv[])
{
    Surface *surf = new Sphere(vec3(0, 0, 1), 1);
    cout << "Area of 10x10 square = " << surf->integrate(dA, D) << endl;

    hist_path = getenv("HOME");
    hist_path += "/";
    hist_path += HISTORY_FILE;

    using_history();
    read_history(hist_path.c_str());
    atexit(exit_handler);
    signal(SIGINT, int_handler);

    Gnuplot *gp = NULL;

    try {
        Gnuplot::set_terminal_std("qt");
        gp = new Gnuplot();
    }
    catch(GnuplotException e) {
        Gnuplot::set_terminal_std("dumb");
        gp = new Gnuplot();
    }

    *gp << "set view equal xyz";

    cout << "Welcome to fieldviz!" << endl << endl;
    cout << "Type `help' for a command listing." << endl;

    /* will change to replot on subsequent commands */
    string plot_cmd = "splot";

    while(1)
    {
        char *cs = readline("fieldviz> ");
        if(!cs)
            return 0;
        add_history(cs);

        string line(cs);

        free(cs);

        all_lower(line);

        /* parse */
        stringstream ss(line);

        string cmd;
        ss >> cmd;

        try {
            if(cmd == "add")
            {
                /* add a current or charge distribution */
                Entity e;

                string type;
                ss >> type;

                /* union */
                double val;
                ss >> val;

                Manifold *path = parse_curve(ss);

                cout << "Manifold type: " << path->name() << endl;

                int idx;
                if(type == "i")
                    idx = add_current(val, path);
                else if(type == "q")
                    idx = add_charge(val, path);
                else throw "unknown distribution type (must be I or Q)";

                cout << "Index: " << idx << endl;
            }
            else if(cmd == "delete")
            {
                int id;
                while(ss >> id)
                {
                    if(entities.erase(id))
                        cout << "Deleted " << id << "." << endl;
                    else
                        cerr << "No entity " << id << "!" << endl;
                }
            }
            else if(cmd == "field")
            {
                string type;

                vec3 lower, upper;
                scalar delta;

                if(!(ss >> type >> lower >> upper >> delta))
                    throw "plot requires <E/B> <lower> <upper> delta";

                FieldType t = (type == "e") ? FieldType::E : FieldType::B;

                ofstream out;
                string fname = gp->create_tmpfile(out);

                dump_field(out,
                           t,
                           lower, upper, delta);

                out.close();

                string cmd = plot_cmd + " '" + fname + "' w vectors";
                *gp << cmd;

                plot_cmd = "replot";
            }
            else if(cmd == "draw")
            {
                int e_types = 0;

                while(ss)
                {
                    string type_str;
                    if(ss >> type_str)
                    {
                        if(type_str == "i")
                            e_types |= Entity::CURRENT;
                        else if(type_str == "q")
                            e_types |= Entity::CHARGE;
                        else
                            throw "unknown entity type (must be I or Q)";
                    }
                }

                if(!e_types)
                    e_types |= Entity::CHARGE | Entity::CURRENT;

                ofstream out;
                string fname = gp->create_tmpfile(out);
                int n = dump_entities(out, e_types,
                                      entities);
                out.close();

                string cmd = plot_cmd + " for[i = 0:" + itoa(n - 1) + "] '" + fname + "' i i w vectors";
                *gp << cmd;

                plot_cmd = "replot";
            }
            else if(cmd == "delta")
            {
                ss >> D;
                if(D <= 0)
                {
                    cerr << "D must be positive and non-zero!" << endl;
                    D = DEFAULT_D;
                }
            }
            else if(cmd == "newwindow")
            {
                plot_cmd = "splot";
            }
            else if(cmd == "help")
                print_help();
            else
                cerr << "invalid" << endl;
        } catch(const char *err) {
            cerr << "parse error: " << err << endl;
        }
    }

    //LineSegment wire(vec3(0, -100, 0), vec3(0, 100, 0));

    //std::cout << "length = " << loop.integrate(integrand, 1e-2) << endl;

    //vec3 dx = .01;

    //point = 0;

    //scalar I = 1;

    //for(int i = 0; i < 1000; i++, point += dx)
    //std::cout << point[0] << " " << U0 / ( 4 * M_PI ) * loop.integrate(dB, 1e-2)[0] << endl;

#if 0
    mkdir("field", 0755);

    for(scalar y = -1.5; y <= 1.5; y += .1)
    {
        stringstream ss;
        ss << "field/" << y << ".fld";
        ofstream ofs(ss.str());

        dump_fieldline(ofs, vec3(0, y, 0), 10);

        ofs.close();
    }
#endif
}