Project

General

Profile

Download (20.5 KB) Statistics
| Branch: | Revision:

distorted-objectlib / src / main / java / org / distorted / objectlib / json / JsonWriter.java @ 8c8c6fcf

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2021 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Distorted is free software: you can redistribute it and/or modify                             //
7
// it under the terms of the GNU General Public License as published by                          //
8
// the Free Software Foundation, either version 2 of the License, or                             //
9
// (at your option) any later version.                                                           //
10
//                                                                                               //
11
// Distorted is distributed in the hope that it will be useful,                                  //
12
// but WITHOUT ANY WARRANTY; without even the implied warranty of                                //
13
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                                 //
14
// GNU General Public License for more details.                                                  //
15
//                                                                                               //
16
// You should have received a copy of the GNU General Public License                             //
17
// along with Distorted.  If not, see <http://www.gnu.org/licenses/>.                            //
18
///////////////////////////////////////////////////////////////////////////////////////////////////
19

    
20
package org.distorted.objectlib.json;
21

    
22
import java.io.BufferedWriter;
23
import java.io.FileOutputStream;
24
import java.io.IOException;
25
import java.io.OutputStreamWriter;
26
import java.nio.charset.StandardCharsets;
27

    
28
import org.distorted.objectlib.helpers.ObjectFaceShape;
29
import org.distorted.objectlib.helpers.ObjectSignature;
30
import org.json.JSONArray;
31
import org.json.JSONException;
32
import org.json.JSONObject;
33

    
34
import org.distorted.library.type.Static3D;
35
import org.distorted.library.type.Static4D;
36

    
37
import org.distorted.objectlib.helpers.ObjectShape;
38
import org.distorted.objectlib.helpers.ObjectSticker;
39
import org.distorted.objectlib.scrambling.ScrambleState;
40
import org.distorted.objectlib.main.TwistyObject;
41

    
42
///////////////////////////////////////////////////////////////////////////////////////////////////
43

    
44
public class JsonWriter
45
{
46
  public static final int VERSION_OBJECT_MAJOR = 3;
47
  public static final int VERSION_OBJECT_MINOR = 0;
48
  public static final int VERSION_EXTRAS_MAJOR = 1;
49
  public static final int VERSION_EXTRAS_MINOR = 0;
50

    
51
  private static JsonWriter mThis;
52
  private static int mNumCubitFaces;
53

    
54
///////////////////////////////////////////////////////////////////////////////////////////////////
55

    
56
  private JsonWriter()
57
    {
58

    
59
    }
60

    
61
///////////////////////////////////////////////////////////////////////////////////////////////////
62

    
63
  private JSONArray generateCubits(TwistyObject object) throws JSONException
64
    {
65
    JSONArray array = new JSONArray();
66

    
67
    int[] numLayers     = object.getNumLayers();
68
    float[][] positions = object.getCubitPositions(numLayers);
69
    int numCubits       = positions.length;
70

    
71
    for(int c=0; c<numCubits; c++)
72
      {
73
      JSONObject cubit = new JSONObject();
74
      Static4D rotQuat  = object.getCubitQuats(c,numLayers);
75
      int variant       = object.getCubitVariant(c,numLayers);
76

    
77
      JSONArray pos = new JSONArray();
78
      int numPos = positions[c].length;
79
      for(int j=0; j<numPos; j++) pos.put(positions[c][j]);
80
      cubit.put("centers", pos);
81
      cubit.put("qx", rotQuat.get0() );
82
      cubit.put("qy", rotQuat.get1() );
83
      cubit.put("qz", rotQuat.get2() );
84
      cubit.put("qw", rotQuat.get3() );
85
      cubit.put("variant", variant );
86

    
87
      JSONArray colors = new JSONArray();
88

    
89
      for(int f=0; f<mNumCubitFaces; f++)
90
        {
91
        int cubColor = object.getCubitFaceMap(c,f);
92
        colors.put(cubColor);
93
        }
94
      cubit.put("colors",colors);
95

    
96
      array.put(cubit);
97
      }
98

    
99
    return array;
100
    }
101

    
102
///////////////////////////////////////////////////////////////////////////////////////////////////
103

    
104
  private JSONArray generateCorners(float[][] corners) throws JSONException
105
    {
106
    JSONArray array = new JSONArray();
107

    
108
    for(float[] c : corners)
109
      {
110
      JSONObject corner = new JSONObject();
111
      corner.put("strength", c[0]);
112
      corner.put("radius"  , c[1]);
113
      array.put(corner);
114
      }
115

    
116
    return array;
117
    }
118

    
119
///////////////////////////////////////////////////////////////////////////////////////////////////
120

    
121
  private JSONArray generateCenters(float[][] centers) throws JSONException
122
    {
123
    JSONArray array = new JSONArray();
124

    
125
    for(float[] c : centers)
126
      {
127
      JSONObject center = new JSONObject();
128
      center.put("x", c[0]);
129
      center.put("y", c[1]);
130
      center.put("z", c[2]);
131
      array.put(center);
132
      }
133

    
134
    return array;
135
    }
136

    
137
///////////////////////////////////////////////////////////////////////////////////////////////////
138

    
139
  private JSONArray generateBands(float[][] bands) throws JSONException
140
    {
141
    JSONArray array = new JSONArray();
142

    
143
    for (float[] b : bands)
144
      {
145
      JSONObject band = new JSONObject();
146
      band.put("height"          , b[0]);
147
      band.put("angle"           , b[1]);
148
      band.put("distanceToCenter", b[2]);
149
      band.put("distanceToFlat"  , b[3]);
150
      band.put("numOfBands"      , b[4]);
151
      band.put("extraI"          , b[5]);
152
      band.put("extraJ"          , b[6]);
153
      array.put(band);
154
      }
155

    
156
    return array;
157
    }
158

    
159
///////////////////////////////////////////////////////////////////////////////////////////////////
160

    
161
  private JSONArray generateFaces(TwistyObject object, int[][] vertIndices, int[] bandIndices, int cubit, int[] numLayers) throws JSONException
162
    {
163
    JSONArray array = new JSONArray();
164
    int numFaces = vertIndices.length;
165
    int variant = object.getCubitVariant(cubit,numLayers);
166

    
167
    for(int i=0; i<numFaces; i++)
168
      {
169
      JSONObject face = new JSONObject();
170
      face.put("bandIndex", bandIndices[i]);
171

    
172
      int sticker = object.getVariantFaceColor(variant,i);
173
      face.put("sticker",sticker);
174

    
175
      JSONArray vertArr = new JSONArray();
176
      int numV = vertIndices[i].length;
177
      for(int j=0; j<numV; j++) vertArr.put(vertIndices[i][j]);
178
      face.put("vertexIndices",vertArr);
179

    
180
      array.put(face);
181
      }
182

    
183
    return array;
184
    }
185

    
186
///////////////////////////////////////////////////////////////////////////////////////////////////
187

    
188
  private JSONArray generateVertices(float[][] vertices, int[] cornerIndices, int[] centerIndices) throws JSONException
189
    {
190
    JSONArray array = new JSONArray();
191
    int numVertices = vertices.length;
192

    
193
    for(int j=0; j<numVertices; j++)
194
      {
195
      JSONObject vert = new JSONObject();
196
      vert.put("x", vertices[j][0]);
197
      vert.put("y", vertices[j][1]);
198
      vert.put("z", vertices[j][2]);
199
      vert.put("cornerIndex", cornerIndices[j]);
200
      vert.put("centerIndex", centerIndices[j]);
201
      array.put(vert);
202
      }
203

    
204
    return array;
205
    }
206

    
207
///////////////////////////////////////////////////////////////////////////////////////////////////
208

    
209
  private JSONObject generateConvexity(float[] convexity) throws JSONException
210
    {
211
    JSONObject object = new JSONObject();
212
    object.put("x", convexity[0]);
213
    object.put("y", convexity[1]);
214
    object.put("z", convexity[2]);
215
    return object;
216
    }
217

    
218
///////////////////////////////////////////////////////////////////////////////////////////////////
219

    
220
  private int findCubitWithVariant(TwistyObject object, int variant, int numCubits, int[] numLayers)
221
    {
222
    for(int i=0; i<numCubits; i++)
223
      {
224
      if( object.getCubitVariant(i,numLayers)==variant ) return i;
225
      }
226

    
227
    return -1;
228
    }
229

    
230
///////////////////////////////////////////////////////////////////////////////////////////////////
231

    
232
  private JSONArray generateShapes(TwistyObject object) throws JSONException
233
    {
234
    JSONArray shapes = new JSONArray();
235

    
236
    int[] numLayers = object.getNumLayers();
237
    int numVariants = object.getNumCubitVariants(numLayers);
238
    float[][] positions = object.getCubitPositions(numLayers);
239
    int numCubits = positions.length;
240
    mNumCubitFaces = 0;
241

    
242
    for(int i=0; i<numVariants; i++)
243
      {
244
      JSONObject shapeObj = new JSONObject();
245

    
246
      ObjectShape shape = object.getObjectShape(i);
247
      ObjectFaceShape face = object.getObjectFaceShape(i);
248

    
249
      float[] convexity  = face.getConvexityCenter();
250
      float[][] vertices = shape.getVertices();
251
      int[][] vertIndices= shape.getVertIndices();
252
      float[][] bands    = face.getBands();
253
      int[] bandIndices  = face.getBandIndices();
254
      float[][] corners  = face.getCorners();
255
      int[] cornerIndices= face.getCornerIndices();
256
      float[][] centers  = face.getCenters();
257
      int[] centerIndices= face.getCenterIndices();
258

    
259
      int num = vertIndices.length;
260
      if( num>mNumCubitFaces ) mNumCubitFaces=num;
261

    
262
      int cubit = findCubitWithVariant(object,i,numCubits,numLayers);
263

    
264
      if( convexity!=null )
265
        {
266
        JSONObject convObj = generateConvexity(convexity);
267
        shapeObj.put("convexity", convObj);
268
        }
269

    
270
      JSONArray verticesArr = generateVertices(vertices,cornerIndices,centerIndices);
271
      shapeObj.put("vertices", verticesArr);
272
      JSONArray facesArr = generateFaces(object,vertIndices,bandIndices,cubit,numLayers);
273
      shapeObj.put("faces", facesArr);
274
      JSONArray bandsArr = generateBands(bands);
275
      shapeObj.put("bands", bandsArr);
276

    
277
      if( corners!=null )
278
        {
279
        JSONArray cornerArr = generateCorners(corners);
280
        shapeObj.put("cornerPush", cornerArr);
281
        }
282

    
283
      if( centers!=null )
284
        {
285
        JSONArray centerArr = generateCenters(centers);
286
        shapeObj.put("centerPush", centerArr);
287
        }
288

    
289
      shapes.put(shapeObj);
290
      }
291

    
292
    return shapes;
293
    }
294

    
295
///////////////////////////////////////////////////////////////////////////////////////////////////
296

    
297
  private JSONArray generateStickers(TwistyObject object) throws JSONException
298
    {
299
    JSONArray stickers = new JSONArray();
300

    
301
    int numStickers = object.getNumStickerTypes();
302

    
303
    for(int i=0; i<numStickers; i++)
304
      {
305
      JSONObject stickerObj = new JSONObject();
306
      JSONArray  vertexArray= new JSONArray();
307

    
308
      ObjectSticker sticker = object.retSticker(i);
309

    
310
      float[] coords     = sticker.getCoords();
311
      float[] curvatures = sticker.getCurvature();
312
      float[] radii      = sticker.getRadii();
313
      float   stroke     = sticker.getStroke();
314

    
315
      stickerObj.put("stroke", stroke);
316
      int numVertices = radii.length;
317

    
318
      for(int j=0; j<numVertices; j++)
319
        {
320
        JSONObject vertex = new JSONObject();
321
        vertex.put("x", coords[2*j  ]);
322
        vertex.put("y", coords[2*j+1]);
323
        vertex.put("angle", curvatures==null ? 0 : curvatures[j]);
324
        vertex.put("radius",radii[j]);
325
        vertexArray.put(vertex);
326
        }
327
      stickerObj.put("vertices", vertexArray);
328
      stickers.put(stickerObj);
329
      }
330

    
331
    return stickers;
332
    }
333

    
334
///////////////////////////////////////////////////////////////////////////////////////////////////
335

    
336
  private JSONObject generateMesh(TwistyObject object) throws JSONException
337
    {
338
    JSONObject mesh = new JSONObject();
339

    
340
    JSONArray shapes   = generateShapes(object);  // do this before cubits so we calculate numCubitFaces
341
    JSONArray cubits   = generateCubits(object);
342
    JSONArray stickers = generateStickers(object);
343

    
344
    mesh.put("shapes"  , shapes);
345
    mesh.put("cubits"  , cubits);
346
    mesh.put("stickers", stickers);
347

    
348
    return mesh;
349
    }
350

    
351
///////////////////////////////////////////////////////////////////////////////////////////////////
352

    
353
  private JSONObject generateMetadata(TwistyObject object, int numScramble) throws JSONException
354
    {
355
    JSONObject metadata = new JSONObject();
356

    
357
    metadata.put("longname"   , object.getObjectName() );
358
    metadata.put("inventor"   , object.getInventor());
359
    metadata.put("year"       , object.getYearOfInvention());
360
    metadata.put("complexity" , object.getComplexity());
361
    metadata.put("size"       , object.getSize() );
362
    metadata.put("scrambles"  , numScramble );
363
    metadata.put("shortname"  , object.getShortName() );
364
    metadata.put("resetmaps"  , object.shouldResetTextureMaps() );
365
    metadata.put("num_faces"  , object.getNumFaces() );
366

    
367
    ObjectSignature signature = object.getSignature();
368

    
369
    metadata.put("signature1" , signature.getLong1() );
370
    metadata.put("signature2" , signature.getLong2() );
371
    metadata.put("signature3" , signature.getLong3() );
372

    
373
    return metadata;
374
    }
375

    
376
///////////////////////////////////////////////////////////////////////////////////////////////////
377

    
378
  private JSONArray generateQuats(TwistyObject object) throws JSONException
379
    {
380
    JSONArray quatsArray = new JSONArray();
381
    Static4D[] quats = object.getQuats();
382

    
383
    for(Static4D quat : quats)
384
      {
385
      JSONObject q = new JSONObject();
386
      q.put("x",quat.get0());
387
      q.put("y",quat.get1());
388
      q.put("z",quat.get2());
389
      q.put("w",quat.get3());
390
      quatsArray.put(q);
391
      }
392

    
393
    return quatsArray;
394
    }
395

    
396
///////////////////////////////////////////////////////////////////////////////////////////////////
397

    
398
  private JSONArray generateAxis(TwistyObject object) throws JSONException
399
    {
400
    JSONArray axis = new JSONArray();
401

    
402
    Static3D[] rotAxis = object.getRotationAxis();
403
    int numAxis = rotAxis.length;
404
    int[][] basicAngle = object.getBasicAngles();
405
    int[] numLayers = object.getNumLayers();
406
    float[][] cuts = object.getCuts(numLayers);
407
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
408

    
409
    for( int i=0; i<numAxis; i++ )
410
      {
411
      JSONObject axObject = new JSONObject();
412
      Static3D ax = rotAxis[i];
413

    
414
      axObject.put("x", ax.get0() );
415
      axObject.put("y", ax.get1() );
416
      axObject.put("z", ax.get2() );
417

    
418
      JSONArray angleArray = new JSONArray();
419
      for(float angle : basicAngle[i]) angleArray.put(angle);
420
      axObject.put("basicAngles", angleArray);
421
      JSONArray cutsArray = new JSONArray();
422
      if( cuts[i]!=null ) for(float cut : cuts[i]) cutsArray.put(cut);
423
      axObject.put("cuts", cutsArray);
424
      JSONArray rotaArray = new JSONArray();
425
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
426
      axObject.put("rotatable", rotaArray );
427

    
428
      axis.put(axObject);
429
      }
430

    
431
    return axis;
432
    }
433

    
434
///////////////////////////////////////////////////////////////////////////////////////////////////
435

    
436
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
437
    {
438
    JSONObject scrambling = new JSONObject();
439

    
440
    ScrambleState[] states = object.getScrambleStates();
441
    int scrambleType = object.getScrambleType();
442
    scrambling.put("scrambleType",scrambleType );
443

    
444
    if( states!=null )
445
      {
446
      JSONArray scrambleStates = new JSONArray();
447

    
448
      for(ScrambleState state : states)
449
        {
450
        JSONArray axisArray = new JSONArray();
451
        int numAxis = state.getNumAxis();
452

    
453
        for(int ax=0; ax<numAxis; ax++)
454
          {
455
          JSONArray axArray = new JSONArray();
456
          int[] axData = state.getAx(ax);
457

    
458
          if( axData!=null )
459
            for(int data : axData) axArray.put(data);
460

    
461
          axisArray.put(axArray);
462
          }
463

    
464
        scrambleStates.put(axisArray);
465
        }
466

    
467
      scrambling.put("scrambleStates", scrambleStates);
468
      }
469

    
470
    return scrambling;
471
    }
472

    
473
///////////////////////////////////////////////////////////////////////////////////////////////////
474

    
475
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
476
    {
477
    JSONObject touchControl = new JSONObject();
478

    
479
    touchControl.put("movementType" , object.getTouchControlType() );
480
    touchControl.put("movementSplit", object.getTouchControlSplit() );
481

    
482
    int[][][] enabled = object.getEnabled();
483

    
484
    if( enabled!=null )
485
      {
486
      JSONArray enabledArray = new JSONArray();
487

    
488
      for(int[][] faceEnabled : enabled)
489
        {
490
        JSONArray faceArray = new JSONArray();
491

    
492
        for(int[] sectionEnabled : faceEnabled)
493
          {
494
          JSONArray sectionArray = new JSONArray();
495
          for(int ax : sectionEnabled) sectionArray.put(ax);
496
          faceArray.put(sectionArray);
497
          }
498
        enabledArray.put(faceArray);
499
        }
500

    
501
      touchControl.put("enabledAxis", enabledArray);
502
      }
503

    
504
    int[] numLayers = object.getNumLayers();
505
    float[] dist3D = object.getDist3D(numLayers);
506

    
507
    if( dist3D!=null )
508
      {
509
      JSONArray distArray = new JSONArray();
510
      for( float dist: dist3D ) distArray.put(dist);
511
      touchControl.put("dist3D", distArray);
512
      }
513

    
514
    return touchControl;
515
    }
516

    
517
///////////////////////////////////////////////////////////////////////////////////////////////////
518

    
519
  private JSONArray generateColors(TwistyObject object)
520
    {
521
    JSONArray jsonColors = new JSONArray();
522
    int numFaceColors = object.getNumFaceColors();
523
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
524

    
525
    jsonColors.put(object.getInternalColor());
526

    
527
    return jsonColors;
528
    }
529

    
530
///////////////////////////////////////////////////////////////////////////////////////////////////
531

    
532
  private JSONObject generateSolved(TwistyObject object) throws JSONException
533
    {
534
    JSONObject solved = new JSONObject();
535
    int[][] solvedGroups = object.getSolvedQuats();
536

    
537
    solved.put("functionIndex", object.getSolvedFunctionIndex() );
538

    
539
    if( solvedGroups!=null )
540
      {
541
      JSONArray groupArray = new JSONArray();
542

    
543
      for( int[] group : solvedGroups )
544
        {
545
        JSONArray groupElements = new JSONArray();
546
        for( int element : group ) groupElements.put(element);
547
        groupArray.put(groupElements);
548
        }
549

    
550
      solved.put("groups", groupArray );
551
      }
552

    
553
    return solved;
554
    }
555

    
556
///////////////////////////////////////////////////////////////////////////////////////////////////
557

    
558
  public String createObjectString(TwistyObject object,int numScramble) throws JSONException
559
    {
560
    JSONObject json = new JSONObject();
561

    
562
    JSONObject metadata    = generateMetadata(object,numScramble);
563
    JSONObject mesh        = generateMesh(object);
564
    JSONArray  axis        = generateAxis(object);
565
    JSONArray  quats       = generateQuats(object);
566
    JSONObject scrambling  = generateScrambling(object);
567
    JSONObject touchControl= generateTouchControl(object);
568
    JSONArray  colors      = generateColors(object);
569
    JSONObject solved      = generateSolved(object);
570

    
571
    json.put("major"       , VERSION_OBJECT_MAJOR);
572
    json.put("minor"       , VERSION_OBJECT_MINOR);
573
    json.put("metadata"    , metadata);
574
    json.put("mesh"        , mesh);
575
    json.put("axis"        , axis);
576
    json.put("quats"       , quats);
577
    json.put("scrambling"  , scrambling);
578
    json.put("touchcontrol", touchControl);
579
    json.put("colors"      , colors);
580
    json.put("solved"      , solved);
581

    
582
    return json.toString();
583
    }
584

    
585
///////////////////////////////////////////////////////////////////////////////////////////////////
586

    
587
  public String createExtrasString(TwistyObject object) throws JSONException
588
    {
589
    String[][] tuts = object.getTutorials();
590

    
591
    if( tuts!=null )
592
      {
593
      JSONObject json = new JSONObject();
594
      JSONArray  tutorials = new JSONArray();
595

    
596
      for(String[] tut : tuts)
597
        {
598
        String language = tut[0];
599
        String link     = tut[1];
600
        String title    = tut[2];
601
        String author   = tut[3];
602

    
603
        JSONObject oneTut = new JSONObject();
604

    
605
        oneTut.put("language", language);
606
        oneTut.put("link"    , link    );
607
        oneTut.put("title"   , title   );
608
        oneTut.put("author"  , author  );
609

    
610
        tutorials.put(oneTut);
611
        }
612

    
613
      json.put("major"     , VERSION_EXTRAS_MAJOR);
614
      json.put("minor"     , VERSION_EXTRAS_MINOR);
615
      json.put("object"    , object.getShortName() );
616
      json.put("tutorials" , tutorials);
617

    
618
      return json.toString();
619
      }
620

    
621
    return null;
622
    }
623

    
624
///////////////////////////////////////////////////////////////////////////////////////////////////
625

    
626
  public void write(String filename, String contents) throws IOException
627
    {
628
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
629
    BufferedWriter bw = new BufferedWriter(osw);
630
    bw.write(contents);
631
    bw.flush();
632
    }
633

    
634
///////////////////////////////////////////////////////////////////////////////////////////////////
635

    
636
  public static JsonWriter getInstance()
637
    {
638
    if( mThis==null ) mThis = new JsonWriter();
639
    return mThis;
640
    }
641
}
(2-2/2)