Project

General

Profile

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

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

1
///////////////////////////////////////////////////////////////////////////////////////////////////
2
// Copyright 2021 Leszek Koltunski                                                               //
3
//                                                                                               //
4
// This file is part of Distorted.                                                               //
5
//                                                                                               //
6
// Magic Cube is proprietary software licensed under an EULA which you should have received      //
7
// along with the code. If not, check https://distorted.org/magic/License-Magic-Cube.html        //
8
///////////////////////////////////////////////////////////////////////////////////////////////////
9

    
10
package org.distorted.objectlib.json;
11

    
12
import java.io.BufferedWriter;
13
import java.io.FileOutputStream;
14
import java.io.IOException;
15
import java.io.OutputStreamWriter;
16
import java.nio.charset.StandardCharsets;
17

    
18
import org.distorted.objectlib.helpers.ObjectFaceShape;
19
import org.distorted.objectlib.helpers.ObjectStickerOverride;
20
import org.json.JSONArray;
21
import org.json.JSONException;
22
import org.json.JSONObject;
23

    
24
import org.distorted.library.type.Static3D;
25
import org.distorted.library.type.Static4D;
26

    
27
import org.distorted.objectlib.helpers.ObjectShape;
28
import org.distorted.objectlib.helpers.ObjectSticker;
29
import org.distorted.objectlib.scrambling.ScrambleState;
30
import org.distorted.objectlib.main.TwistyObject;
31

    
32
///////////////////////////////////////////////////////////////////////////////////////////////////
33

    
34
public class JsonWriter
35
{
36
  public static final int VERSION_OBJECT_MAJOR = 5;
37
  public static final int VERSION_OBJECT_MINOR = 0;
38
  public static final int VERSION_EXTRAS_MAJOR = 1;
39
  public static final int VERSION_EXTRAS_MINOR = 0;
40

    
41
  private static JsonWriter mThis;
42
  private static int mNumCubitFaces;
43

    
44
///////////////////////////////////////////////////////////////////////////////////////////////////
45

    
46
  private JsonWriter()
47
    {
48

    
49
    }
50

    
51
///////////////////////////////////////////////////////////////////////////////////////////////////
52

    
53
  private JSONArray generateCubits(TwistyObject object) throws JSONException
54
    {
55
    JSONArray array = new JSONArray();
56

    
57
    int[] numLayers     = object.getNumLayers();
58
    float[][] positions = object.getCubitPositions(numLayers);
59
    int numCubits       = positions.length;
60

    
61
    for(int c=0; c<numCubits; c++)
62
      {
63
      JSONObject cubit = new JSONObject();
64
      Static4D rotQuat = object.getCubitQuats(c,numLayers);
65
      int variant      = object.getCubitVariant(c,numLayers);
66
      int type         = object.getCubitType(c);
67
      float[] offset   = object.getCubitOffset(c);
68

    
69
      JSONArray pos = new JSONArray();
70
      int numPos = positions[c].length;
71
      for(int j=0; j<numPos; j++) pos.put(positions[c][j]);
72
      cubit.put("centers", pos);
73
      cubit.put("qx", rotQuat.get0() );
74
      cubit.put("qy", rotQuat.get1() );
75
      cubit.put("qz", rotQuat.get2() );
76
      cubit.put("qw", rotQuat.get3() );
77
      cubit.put("variant", variant );
78
      cubit.put("type", type);
79

    
80
      if( offset!=null )
81
        {
82
        cubit.put("offsetX", offset[0]);
83
        cubit.put("offsetY", offset[1]);
84
        cubit.put("offsetZ", offset[2]);
85
        }
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[] faceOuter, 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
      face.put("isOuter", faceOuter[i]);
175

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

    
181
      array.put(face);
182
      }
183

    
184
    return array;
185
    }
186

    
187
///////////////////////////////////////////////////////////////////////////////////////////////////
188

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

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

    
205
    return array;
206
    }
207

    
208
///////////////////////////////////////////////////////////////////////////////////////////////////
209

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

    
219
///////////////////////////////////////////////////////////////////////////////////////////////////
220

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

    
228
    return -1;
229
    }
230

    
231
///////////////////////////////////////////////////////////////////////////////////////////////////
232

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

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

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

    
248
      ObjectShape shape = object.getObjectShape(i);
249
      ObjectFaceShape face = object.getObjectFaceShape(i);
250

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

    
261
      int num = vertIndices.length;
262
      if( num>mNumCubitFaces ) mNumCubitFaces=num;
263

    
264
      int cubit = findCubitWithVariant(object,i,numCubits,numLayers);
265

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

    
272
      JSONArray verticesArr = generateVertices(vertices,cornerIndices,centerIndices);
273
      shapeObj.put("vertices", verticesArr);
274
      JSONArray facesArr = generateFaces(object,vertIndices,bandIndices,faceOuter[i],cubit,numLayers);
275
      shapeObj.put("faces", facesArr);
276
      JSONArray bandsArr = generateBands(bands);
277
      shapeObj.put("bands", bandsArr);
278

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

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

    
291
      shapes.put(shapeObj);
292
      }
293

    
294
    return shapes;
295
    }
296

    
297
///////////////////////////////////////////////////////////////////////////////////////////////////
298

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

    
303
    int numStickers = object.getNumStickerTypes();
304

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

    
310
      ObjectSticker sticker = object.retSticker(i);
311

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

    
317
      stickerObj.put("stroke", stroke);
318
      int numVertices = radii.length;
319

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

    
333
    return stickers;
334
    }
335

    
336
///////////////////////////////////////////////////////////////////////////////////////////////////
337

    
338
  private JSONArray generateOverrides(TwistyObject object) throws JSONException
339
    {
340
    ObjectStickerOverride[] overrides = object.getStickerOverrides();
341

    
342
    if( overrides!=null )
343
      {
344
      JSONArray overrideArray = new JSONArray();
345

    
346
      for (ObjectStickerOverride objectStickerOverride : overrides)
347
        {
348
        JSONObject override = new JSONObject();
349
        int[] cubfac = objectStickerOverride.getCubitFaces();
350
        int color    = objectStickerOverride.getColor();
351
        JSONArray cubfacArray = new JSONArray();
352
        for (int cf : cubfac) cubfacArray.put(cf);
353

    
354
        override.put("cubitfaces", cubfacArray);
355
        override.put("color", color);
356

    
357
        overrideArray.put(override);
358
        }
359

    
360
      return overrideArray;
361
      }
362

    
363
    return null;
364
    }
365

    
366
///////////////////////////////////////////////////////////////////////////////////////////////////
367

    
368
  private JSONObject generateMesh(TwistyObject object) throws JSONException
369
    {
370
    JSONObject mesh = new JSONObject();
371

    
372
    JSONArray shapes   = generateShapes(object);  // do this before cubits so we calculate numCubitFaces
373
    JSONArray cubits   = generateCubits(object);
374
    JSONArray stickers = generateStickers(object);
375

    
376
    mesh.put("shapes"  , shapes);
377
    mesh.put("cubits"  , cubits);
378
    mesh.put("stickers", stickers);
379

    
380
    JSONArray overrides = generateOverrides(object);
381
    if( overrides!=null ) mesh.put("overrides", overrides);
382

    
383
    return mesh;
384
    }
385

    
386
///////////////////////////////////////////////////////////////////////////////////////////////////
387

    
388
  private JSONObject generateMetadata(TwistyObject object, int numScramble) throws JSONException
389
    {
390
    JSONObject metadata = new JSONObject();
391

    
392
    metadata.put("longname"   , object.getObjectName() );
393
    metadata.put("inventor"   , object.getInventor());
394
    metadata.put("year"       , object.getYearOfInvention());
395
    metadata.put("complexity" , object.getComplexity());
396
    metadata.put("size"       , object.getSize() );
397
    metadata.put("scrambles"  , numScramble );
398
    metadata.put("shortname"  , object.getShortName() );
399
    metadata.put("resetmaps"  , object.shouldResetTextureMaps() );
400
    metadata.put("num_faces"  , object.getNumFaces() );
401

    
402
    JSONArray sigArray = new JSONArray();
403
    long[] sig = object.getSignature().getArray();
404
    for (long l : sig) sigArray.put(l);
405
    metadata.put("signature" , sigArray );
406

    
407
    return metadata;
408
    }
409

    
410
///////////////////////////////////////////////////////////////////////////////////////////////////
411

    
412
  private JSONArray generateQuats(TwistyObject object) throws JSONException
413
    {
414
    JSONArray quatsArray = new JSONArray();
415
    Static4D[] quats = object.getQuats();
416

    
417
    for(Static4D quat : quats)
418
      {
419
      JSONObject q = new JSONObject();
420
      q.put("x",quat.get0());
421
      q.put("y",quat.get1());
422
      q.put("z",quat.get2());
423
      q.put("w",quat.get3());
424
      quatsArray.put(q);
425
      }
426

    
427
    return quatsArray;
428
    }
429

    
430
///////////////////////////////////////////////////////////////////////////////////////////////////
431

    
432
  private JSONArray generateAxis(TwistyObject object) throws JSONException
433
    {
434
    JSONArray axis = new JSONArray();
435

    
436
    Static3D[] rotAxis = object.getRotationAxis();
437
    int numAxis = rotAxis.length;
438
    int[][] basicAngle = object.getBasicAngles();
439
    int[] numLayers = object.getNumLayers();
440
    float[][] cuts = object.getCuts(numLayers);
441
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
442

    
443
    for( int i=0; i<numAxis; i++ )
444
      {
445
      JSONObject axObject = new JSONObject();
446
      Static3D ax = rotAxis[i];
447

    
448
      axObject.put("x", ax.get0() );
449
      axObject.put("y", ax.get1() );
450
      axObject.put("z", ax.get2() );
451

    
452
      JSONArray angleArray = new JSONArray();
453
      for(float angle : basicAngle[i]) angleArray.put(angle);
454
      axObject.put("basicAngles", angleArray);
455
      JSONArray cutsArray = new JSONArray();
456
      if( cuts[i]!=null ) for(float cut : cuts[i]) cutsArray.put(cut);
457
      axObject.put("cuts", cutsArray);
458
      JSONArray rotaArray = new JSONArray();
459
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
460
      axObject.put("rotatable", rotaArray );
461

    
462
      axis.put(axObject);
463
      }
464

    
465
    return axis;
466
    }
467

    
468
///////////////////////////////////////////////////////////////////////////////////////////////////
469

    
470
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
471
    {
472
    JSONObject scrambling = new JSONObject();
473

    
474
    ScrambleState[] states = object.getScrambleStates();
475
    int scrambleType = object.getScrambleType();
476
    scrambling.put("scrambleType",scrambleType );
477

    
478
    if( states!=null )
479
      {
480
      JSONArray scrambleStates = new JSONArray();
481

    
482
      for(ScrambleState state : states)
483
        {
484
        JSONArray axisArray = new JSONArray();
485
        int numAxis = state.getNumAxis();
486

    
487
        for(int ax=0; ax<numAxis; ax++)
488
          {
489
          JSONArray axArray = new JSONArray();
490
          int[] axData = state.getAx(ax);
491

    
492
          if( axData!=null )
493
            for(int data : axData) axArray.put(data);
494

    
495
          axisArray.put(axArray);
496
          }
497

    
498
        scrambleStates.put(axisArray);
499
        }
500

    
501
      scrambling.put("scrambleStates", scrambleStates);
502
      }
503

    
504
    return scrambling;
505
    }
506

    
507
///////////////////////////////////////////////////////////////////////////////////////////////////
508

    
509
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
510
    {
511
    JSONObject touchControl = new JSONObject();
512

    
513
    touchControl.put("movementType" , object.getTouchControlType() );
514
    touchControl.put("movementSplit", object.getTouchControlSplit() );
515

    
516
    int[][][] enabled = object.getEnabled();
517

    
518
    if( enabled!=null )
519
      {
520
      JSONArray enabledArray = new JSONArray();
521

    
522
      for(int[][] faceEnabled : enabled)
523
        {
524
        JSONArray faceArray = new JSONArray();
525

    
526
        for(int[] sectionEnabled : faceEnabled)
527
          {
528
          JSONArray sectionArray = new JSONArray();
529
          for(int ax : sectionEnabled) sectionArray.put(ax);
530
          faceArray.put(sectionArray);
531
          }
532
        enabledArray.put(faceArray);
533
        }
534

    
535
      touchControl.put("enabledAxis", enabledArray);
536
      }
537

    
538
    int[] numLayers = object.getNumLayers();
539
    float[] dist3D = object.getDist3D(numLayers);
540

    
541
    if( dist3D!=null )
542
      {
543
      JSONArray distArray = new JSONArray();
544
      for( float dist: dist3D ) distArray.put(dist);
545
      touchControl.put("dist3D", distArray);
546
      }
547

    
548
    return touchControl;
549
    }
550

    
551
///////////////////////////////////////////////////////////////////////////////////////////////////
552

    
553
  private JSONArray generateColors(TwistyObject object)
554
    {
555
    JSONArray jsonColors = new JSONArray();
556
    int numFaceColors = object.getNumFaceColors();
557
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
558

    
559
    jsonColors.put(object.getInternalColor());
560

    
561
    return jsonColors;
562
    }
563

    
564
///////////////////////////////////////////////////////////////////////////////////////////////////
565

    
566
  private JSONObject generateSolved(TwistyObject object) throws JSONException
567
    {
568
    JSONObject solved = new JSONObject();
569
    int[][] solvedGroups = object.getSolvedQuats();
570

    
571
    solved.put("functionIndex", object.getSolvedFunctionIndex() );
572

    
573
    if( solvedGroups!=null )
574
      {
575
      JSONArray groupArray = new JSONArray();
576

    
577
      for( int[] group : solvedGroups )
578
        {
579
        JSONArray groupElements = new JSONArray();
580
        for( int element : group ) groupElements.put(element);
581
        groupArray.put(groupElements);
582
        }
583

    
584
      solved.put("groups", groupArray );
585
      }
586

    
587
    return solved;
588
    }
589

    
590
///////////////////////////////////////////////////////////////////////////////////////////////////
591

    
592
  public String createObjectString(TwistyObject object,int numScramble) throws JSONException
593
    {
594
    JSONObject json = new JSONObject();
595

    
596
    JSONObject metadata    = generateMetadata(object,numScramble);
597
    JSONObject mesh        = generateMesh(object);
598
    JSONArray  axis        = generateAxis(object);
599
    JSONArray  quats       = generateQuats(object);
600
    JSONObject scrambling  = generateScrambling(object);
601
    JSONObject touchControl= generateTouchControl(object);
602
    JSONArray  colors      = generateColors(object);
603
    JSONObject solved      = generateSolved(object);
604

    
605
    json.put("major"       , VERSION_OBJECT_MAJOR);
606
    json.put("minor"       , VERSION_OBJECT_MINOR);
607
    json.put("metadata"    , metadata);
608
    json.put("mesh"        , mesh);
609
    json.put("axis"        , axis);
610
    json.put("quats"       , quats);
611
    json.put("scrambling"  , scrambling);
612
    json.put("touchcontrol", touchControl);
613
    json.put("colors"      , colors);
614
    json.put("solved"      , solved);
615

    
616
    return json.toString();
617
    }
618

    
619
///////////////////////////////////////////////////////////////////////////////////////////////////
620

    
621
  public String createExtrasString(TwistyObject object) throws JSONException
622
    {
623
    String[][] tuts = object.getTutorials();
624

    
625
    if( tuts!=null )
626
      {
627
      JSONObject json = new JSONObject();
628
      JSONArray  tutorials = new JSONArray();
629

    
630
      for(String[] tut : tuts)
631
        {
632
        String language = tut[0];
633
        String link     = tut[1];
634
        String title    = tut[2];
635
        String author   = tut[3];
636

    
637
        JSONObject oneTut = new JSONObject();
638

    
639
        oneTut.put("language", language);
640
        oneTut.put("link"    , link    );
641
        oneTut.put("title"   , title   );
642
        oneTut.put("author"  , author  );
643

    
644
        tutorials.put(oneTut);
645
        }
646

    
647
      json.put("major"     , VERSION_EXTRAS_MAJOR);
648
      json.put("minor"     , VERSION_EXTRAS_MINOR);
649
      json.put("object"    , object.getShortName() );
650
      json.put("tutorials" , tutorials);
651

    
652
      return json.toString();
653
      }
654

    
655
    return null;
656
    }
657

    
658
///////////////////////////////////////////////////////////////////////////////////////////////////
659

    
660
  public void write(String filename, String contents) throws IOException
661
    {
662
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
663
    BufferedWriter bw = new BufferedWriter(osw);
664
    bw.write(contents);
665
    bw.flush();
666
    }
667

    
668
///////////////////////////////////////////////////////////////////////////////////////////////////
669

    
670
  public static JsonWriter getInstance()
671
    {
672
    if( mThis==null ) mThis = new JsonWriter();
673
    return mThis;
674
    }
675
}
(2-2/2)