Project

General

Profile

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

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

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.distorted.objectlib.helpers.ObjectStickerOverride;
31
import org.json.JSONArray;
32
import org.json.JSONException;
33
import org.json.JSONObject;
34

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

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

    
43
///////////////////////////////////////////////////////////////////////////////////////////////////
44

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

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

    
55
///////////////////////////////////////////////////////////////////////////////////////////////////
56

    
57
  private JsonWriter()
58
    {
59

    
60
    }
61

    
62
///////////////////////////////////////////////////////////////////////////////////////////////////
63

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

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

    
72
    for(int c=0; c<numCubits; c++)
73
      {
74
      JSONObject cubit = new JSONObject();
75
      Static4D rotQuat = object.getCubitQuats(c,numLayers);
76
      int variant      = object.getCubitVariant(c,numLayers);
77
      int type         = object.getCubitType(c);
78
      float[] offset   = object.getCubitOffset(c);
79

    
80
      JSONArray pos = new JSONArray();
81
      int numPos = positions[c].length;
82
      for(int j=0; j<numPos; j++) pos.put(positions[c][j]);
83
      cubit.put("centers", pos);
84
      cubit.put("qx", rotQuat.get0() );
85
      cubit.put("qy", rotQuat.get1() );
86
      cubit.put("qz", rotQuat.get2() );
87
      cubit.put("qw", rotQuat.get3() );
88
      cubit.put("variant", variant );
89
      cubit.put("type", type);
90
      cubit.put("offsetX", offset[0]);
91
      cubit.put("offsetY", offset[1]);
92
      cubit.put("offsetZ", offset[2]);
93

    
94
      JSONArray colors = new JSONArray();
95

    
96
      for(int f=0; f<mNumCubitFaces; f++)
97
        {
98
        int cubColor = object.getCubitFaceMap(c,f);
99
        colors.put(cubColor);
100
        }
101
      cubit.put("colors",colors);
102

    
103
      array.put(cubit);
104
      }
105

    
106
    return array;
107
    }
108

    
109
///////////////////////////////////////////////////////////////////////////////////////////////////
110

    
111
  private JSONArray generateCorners(float[][] corners) throws JSONException
112
    {
113
    JSONArray array = new JSONArray();
114

    
115
    for(float[] c : corners)
116
      {
117
      JSONObject corner = new JSONObject();
118
      corner.put("strength", c[0]);
119
      corner.put("radius"  , c[1]);
120
      array.put(corner);
121
      }
122

    
123
    return array;
124
    }
125

    
126
///////////////////////////////////////////////////////////////////////////////////////////////////
127

    
128
  private JSONArray generateCenters(float[][] centers) throws JSONException
129
    {
130
    JSONArray array = new JSONArray();
131

    
132
    for(float[] c : centers)
133
      {
134
      JSONObject center = new JSONObject();
135
      center.put("x", c[0]);
136
      center.put("y", c[1]);
137
      center.put("z", c[2]);
138
      array.put(center);
139
      }
140

    
141
    return array;
142
    }
143

    
144
///////////////////////////////////////////////////////////////////////////////////////////////////
145

    
146
  private JSONArray generateBands(float[][] bands) throws JSONException
147
    {
148
    JSONArray array = new JSONArray();
149

    
150
    for (float[] b : bands)
151
      {
152
      JSONObject band = new JSONObject();
153
      band.put("height"          , b[0]);
154
      band.put("angle"           , b[1]);
155
      band.put("distanceToCenter", b[2]);
156
      band.put("distanceToFlat"  , b[3]);
157
      band.put("numOfBands"      , b[4]);
158
      band.put("extraI"          , b[5]);
159
      band.put("extraJ"          , b[6]);
160
      array.put(band);
161
      }
162

    
163
    return array;
164
    }
165

    
166
///////////////////////////////////////////////////////////////////////////////////////////////////
167

    
168
  private JSONArray generateFaces(TwistyObject object, int[][] vertIndices, int[] bandIndices, int[] faceOuter, int cubit, int[] numLayers) throws JSONException
169
    {
170
    JSONArray array = new JSONArray();
171
    int numFaces = vertIndices.length;
172
    int variant = object.getCubitVariant(cubit,numLayers);
173

    
174
    for(int i=0; i<numFaces; i++)
175
      {
176
      JSONObject face = new JSONObject();
177
      face.put("bandIndex", bandIndices[i]);
178

    
179
      int sticker = object.getVariantFaceColor(variant,i);
180
      face.put("sticker", sticker);
181
      face.put("isOuter", faceOuter[i]);
182

    
183
      JSONArray vertArr = new JSONArray();
184
      int numV = vertIndices[i].length;
185
      for(int j=0; j<numV; j++) vertArr.put(vertIndices[i][j]);
186
      face.put("vertexIndices",vertArr);
187

    
188
      array.put(face);
189
      }
190

    
191
    return array;
192
    }
193

    
194
///////////////////////////////////////////////////////////////////////////////////////////////////
195

    
196
  private JSONArray generateVertices(float[][] vertices, int[] cornerIndices, int[] centerIndices) throws JSONException
197
    {
198
    JSONArray array = new JSONArray();
199
    int numVertices = vertices.length;
200

    
201
    for(int j=0; j<numVertices; j++)
202
      {
203
      JSONObject vert = new JSONObject();
204
      vert.put("x", vertices[j][0]);
205
      vert.put("y", vertices[j][1]);
206
      vert.put("z", vertices[j][2]);
207
      vert.put("cornerIndex", cornerIndices[j]);
208
      vert.put("centerIndex", centerIndices[j]);
209
      array.put(vert);
210
      }
211

    
212
    return array;
213
    }
214

    
215
///////////////////////////////////////////////////////////////////////////////////////////////////
216

    
217
  private JSONObject generateConvexity(float[] convexity) throws JSONException
218
    {
219
    JSONObject object = new JSONObject();
220
    object.put("x", convexity[0]);
221
    object.put("y", convexity[1]);
222
    object.put("z", convexity[2]);
223
    return object;
224
    }
225

    
226
///////////////////////////////////////////////////////////////////////////////////////////////////
227

    
228
  private int findCubitWithVariant(TwistyObject object, int variant, int numCubits, int[] numLayers)
229
    {
230
    for(int i=0; i<numCubits; i++)
231
      {
232
      if( object.getCubitVariant(i,numLayers)==variant ) return i;
233
      }
234

    
235
    return -1;
236
    }
237

    
238
///////////////////////////////////////////////////////////////////////////////////////////////////
239

    
240
  private JSONArray generateShapes(TwistyObject object) throws JSONException
241
    {
242
    JSONArray shapes = new JSONArray();
243

    
244
    int[] numLayers = object.getNumLayers();
245
    int numVariants = object.getNumCubitVariants(numLayers);
246
    float[][] positions = object.getCubitPositions(numLayers);
247
    int[][] faceOuter   = object.getVariantFaceIsOuter();
248
    int numCubits = positions.length;
249
    mNumCubitFaces = 0;
250

    
251
    for(int i=0; i<numVariants; i++)
252
      {
253
      JSONObject shapeObj = new JSONObject();
254

    
255
      ObjectShape shape = object.getObjectShape(i);
256
      ObjectFaceShape face = object.getObjectFaceShape(i);
257

    
258
      float[] convexity  = face.getConvexityCenter();
259
      float[][] vertices = shape.getVertices();
260
      int[][] vertIndices= shape.getVertIndices();
261
      float[][] bands    = face.getBands();
262
      int[] bandIndices  = face.getBandIndices();
263
      float[][] corners  = face.getCorners();
264
      int[] cornerIndices= face.getCornerIndices();
265
      float[][] centers  = face.getCenters();
266
      int[] centerIndices= face.getCenterIndices();
267

    
268
      int num = vertIndices.length;
269
      if( num>mNumCubitFaces ) mNumCubitFaces=num;
270

    
271
      int cubit = findCubitWithVariant(object,i,numCubits,numLayers);
272

    
273
      if( convexity!=null )
274
        {
275
        JSONObject convObj = generateConvexity(convexity);
276
        shapeObj.put("convexity", convObj);
277
        }
278

    
279
      JSONArray verticesArr = generateVertices(vertices,cornerIndices,centerIndices);
280
      shapeObj.put("vertices", verticesArr);
281
      JSONArray facesArr = generateFaces(object,vertIndices,bandIndices,faceOuter[i],cubit,numLayers);
282
      shapeObj.put("faces", facesArr);
283
      JSONArray bandsArr = generateBands(bands);
284
      shapeObj.put("bands", bandsArr);
285

    
286
      if( corners!=null )
287
        {
288
        JSONArray cornerArr = generateCorners(corners);
289
        shapeObj.put("cornerPush", cornerArr);
290
        }
291

    
292
      if( centers!=null )
293
        {
294
        JSONArray centerArr = generateCenters(centers);
295
        shapeObj.put("centerPush", centerArr);
296
        }
297

    
298
      shapes.put(shapeObj);
299
      }
300

    
301
    return shapes;
302
    }
303

    
304
///////////////////////////////////////////////////////////////////////////////////////////////////
305

    
306
  private JSONArray generateStickers(TwistyObject object) throws JSONException
307
    {
308
    JSONArray stickers = new JSONArray();
309

    
310
    int numStickers = object.getNumStickerTypes();
311

    
312
    for(int i=0; i<numStickers; i++)
313
      {
314
      JSONObject stickerObj = new JSONObject();
315
      JSONArray  vertexArray= new JSONArray();
316

    
317
      ObjectSticker sticker = object.retSticker(i);
318

    
319
      float[] coords     = sticker.getCoords();
320
      float[] curvatures = sticker.getCurvature();
321
      float[] radii      = sticker.getRadii();
322
      float   stroke     = sticker.getStroke();
323

    
324
      stickerObj.put("stroke", stroke);
325
      int numVertices = radii.length;
326

    
327
      for(int j=0; j<numVertices; j++)
328
        {
329
        JSONObject vertex = new JSONObject();
330
        vertex.put("x", coords[2*j  ]);
331
        vertex.put("y", coords[2*j+1]);
332
        vertex.put("angle", curvatures==null ? 0 : curvatures[j]);
333
        vertex.put("radius",radii[j]);
334
        vertexArray.put(vertex);
335
        }
336
      stickerObj.put("vertices", vertexArray);
337
      stickers.put(stickerObj);
338
      }
339

    
340
    return stickers;
341
    }
342

    
343
///////////////////////////////////////////////////////////////////////////////////////////////////
344

    
345
  private JSONArray generateOverrides(TwistyObject object) throws JSONException
346
    {
347
    ObjectStickerOverride[] overrides = object.getStickerOverrides();
348

    
349
    if( overrides!=null )
350
      {
351
      JSONArray overrideArray = new JSONArray();
352

    
353
      for (ObjectStickerOverride objectStickerOverride : overrides)
354
        {
355
        JSONObject override = new JSONObject();
356
        int cubit = objectStickerOverride.getCubit();
357
        int face  = objectStickerOverride.getFace();
358
        int color = objectStickerOverride.getColor();
359

    
360
        override.put("cubit", cubit);
361
        override.put("face" , face );
362
        override.put("color", color);
363

    
364
        overrideArray.put(override);
365
        }
366

    
367
      return overrideArray;
368
      }
369

    
370
    return null;
371
    }
372

    
373
///////////////////////////////////////////////////////////////////////////////////////////////////
374

    
375
  private JSONObject generateMesh(TwistyObject object) throws JSONException
376
    {
377
    JSONObject mesh = new JSONObject();
378

    
379
    JSONArray shapes   = generateShapes(object);  // do this before cubits so we calculate numCubitFaces
380
    JSONArray cubits   = generateCubits(object);
381
    JSONArray stickers = generateStickers(object);
382

    
383
    mesh.put("shapes"  , shapes);
384
    mesh.put("cubits"  , cubits);
385
    mesh.put("stickers", stickers);
386

    
387
    JSONArray overrides = generateOverrides(object);
388
    if( overrides!=null ) mesh.put("overrides", overrides);
389

    
390
    return mesh;
391
    }
392

    
393
///////////////////////////////////////////////////////////////////////////////////////////////////
394

    
395
  private JSONObject generateMetadata(TwistyObject object, int numScramble) throws JSONException
396
    {
397
    JSONObject metadata = new JSONObject();
398

    
399
    metadata.put("longname"   , object.getObjectName() );
400
    metadata.put("inventor"   , object.getInventor());
401
    metadata.put("year"       , object.getYearOfInvention());
402
    metadata.put("complexity" , object.getComplexity());
403
    metadata.put("size"       , object.getSize() );
404
    metadata.put("scrambles"  , numScramble );
405
    metadata.put("shortname"  , object.getShortName() );
406
    metadata.put("resetmaps"  , object.shouldResetTextureMaps() );
407
    metadata.put("num_faces"  , object.getNumFaces() );
408

    
409
    ObjectSignature signature = object.getSignature();
410

    
411
    metadata.put("signature1" , signature.getLong1() );
412
    metadata.put("signature2" , signature.getLong2() );
413
    metadata.put("signature3" , signature.getLong3() );
414

    
415
    return metadata;
416
    }
417

    
418
///////////////////////////////////////////////////////////////////////////////////////////////////
419

    
420
  private JSONArray generateQuats(TwistyObject object) throws JSONException
421
    {
422
    JSONArray quatsArray = new JSONArray();
423
    Static4D[] quats = object.getQuats();
424

    
425
    for(Static4D quat : quats)
426
      {
427
      JSONObject q = new JSONObject();
428
      q.put("x",quat.get0());
429
      q.put("y",quat.get1());
430
      q.put("z",quat.get2());
431
      q.put("w",quat.get3());
432
      quatsArray.put(q);
433
      }
434

    
435
    return quatsArray;
436
    }
437

    
438
///////////////////////////////////////////////////////////////////////////////////////////////////
439

    
440
  private JSONArray generateAxis(TwistyObject object) throws JSONException
441
    {
442
    JSONArray axis = new JSONArray();
443

    
444
    Static3D[] rotAxis = object.getRotationAxis();
445
    int numAxis = rotAxis.length;
446
    int[][] basicAngle = object.getBasicAngles();
447
    int[] numLayers = object.getNumLayers();
448
    float[][] cuts = object.getCuts(numLayers);
449
    boolean[][] rotatable = object.getLayerRotatable(numLayers);
450

    
451
    for( int i=0; i<numAxis; i++ )
452
      {
453
      JSONObject axObject = new JSONObject();
454
      Static3D ax = rotAxis[i];
455

    
456
      axObject.put("x", ax.get0() );
457
      axObject.put("y", ax.get1() );
458
      axObject.put("z", ax.get2() );
459

    
460
      JSONArray angleArray = new JSONArray();
461
      for(float angle : basicAngle[i]) angleArray.put(angle);
462
      axObject.put("basicAngles", angleArray);
463
      JSONArray cutsArray = new JSONArray();
464
      if( cuts[i]!=null ) for(float cut : cuts[i]) cutsArray.put(cut);
465
      axObject.put("cuts", cutsArray);
466
      JSONArray rotaArray = new JSONArray();
467
      for(boolean rot : rotatable[i]) rotaArray.put(rot);
468
      axObject.put("rotatable", rotaArray );
469

    
470
      axis.put(axObject);
471
      }
472

    
473
    return axis;
474
    }
475

    
476
///////////////////////////////////////////////////////////////////////////////////////////////////
477

    
478
  private JSONObject generateScrambling(TwistyObject object) throws JSONException
479
    {
480
    JSONObject scrambling = new JSONObject();
481

    
482
    ScrambleState[] states = object.getScrambleStates();
483
    int scrambleType = object.getScrambleType();
484
    scrambling.put("scrambleType",scrambleType );
485

    
486
    if( states!=null )
487
      {
488
      JSONArray scrambleStates = new JSONArray();
489

    
490
      for(ScrambleState state : states)
491
        {
492
        JSONArray axisArray = new JSONArray();
493
        int numAxis = state.getNumAxis();
494

    
495
        for(int ax=0; ax<numAxis; ax++)
496
          {
497
          JSONArray axArray = new JSONArray();
498
          int[] axData = state.getAx(ax);
499

    
500
          if( axData!=null )
501
            for(int data : axData) axArray.put(data);
502

    
503
          axisArray.put(axArray);
504
          }
505

    
506
        scrambleStates.put(axisArray);
507
        }
508

    
509
      scrambling.put("scrambleStates", scrambleStates);
510
      }
511

    
512
    return scrambling;
513
    }
514

    
515
///////////////////////////////////////////////////////////////////////////////////////////////////
516

    
517
  private JSONObject generateTouchControl(TwistyObject object) throws JSONException
518
    {
519
    JSONObject touchControl = new JSONObject();
520

    
521
    touchControl.put("movementType" , object.getTouchControlType() );
522
    touchControl.put("movementSplit", object.getTouchControlSplit() );
523

    
524
    int[][][] enabled = object.getEnabled();
525

    
526
    if( enabled!=null )
527
      {
528
      JSONArray enabledArray = new JSONArray();
529

    
530
      for(int[][] faceEnabled : enabled)
531
        {
532
        JSONArray faceArray = new JSONArray();
533

    
534
        for(int[] sectionEnabled : faceEnabled)
535
          {
536
          JSONArray sectionArray = new JSONArray();
537
          for(int ax : sectionEnabled) sectionArray.put(ax);
538
          faceArray.put(sectionArray);
539
          }
540
        enabledArray.put(faceArray);
541
        }
542

    
543
      touchControl.put("enabledAxis", enabledArray);
544
      }
545

    
546
    int[] numLayers = object.getNumLayers();
547
    float[] dist3D = object.getDist3D(numLayers);
548

    
549
    if( dist3D!=null )
550
      {
551
      JSONArray distArray = new JSONArray();
552
      for( float dist: dist3D ) distArray.put(dist);
553
      touchControl.put("dist3D", distArray);
554
      }
555

    
556
    return touchControl;
557
    }
558

    
559
///////////////////////////////////////////////////////////////////////////////////////////////////
560

    
561
  private JSONArray generateColors(TwistyObject object)
562
    {
563
    JSONArray jsonColors = new JSONArray();
564
    int numFaceColors = object.getNumFaceColors();
565
    for(int i=0; i<numFaceColors; i++) jsonColors.put(object.getColor(i));
566

    
567
    jsonColors.put(object.getInternalColor());
568

    
569
    return jsonColors;
570
    }
571

    
572
///////////////////////////////////////////////////////////////////////////////////////////////////
573

    
574
  private JSONObject generateSolved(TwistyObject object) throws JSONException
575
    {
576
    JSONObject solved = new JSONObject();
577
    int[][] solvedGroups = object.getSolvedQuats();
578

    
579
    solved.put("functionIndex", object.getSolvedFunctionIndex() );
580

    
581
    if( solvedGroups!=null )
582
      {
583
      JSONArray groupArray = new JSONArray();
584

    
585
      for( int[] group : solvedGroups )
586
        {
587
        JSONArray groupElements = new JSONArray();
588
        for( int element : group ) groupElements.put(element);
589
        groupArray.put(groupElements);
590
        }
591

    
592
      solved.put("groups", groupArray );
593
      }
594

    
595
    return solved;
596
    }
597

    
598
///////////////////////////////////////////////////////////////////////////////////////////////////
599

    
600
  public String createObjectString(TwistyObject object,int numScramble) throws JSONException
601
    {
602
    JSONObject json = new JSONObject();
603

    
604
    JSONObject metadata    = generateMetadata(object,numScramble);
605
    JSONObject mesh        = generateMesh(object);
606
    JSONArray  axis        = generateAxis(object);
607
    JSONArray  quats       = generateQuats(object);
608
    JSONObject scrambling  = generateScrambling(object);
609
    JSONObject touchControl= generateTouchControl(object);
610
    JSONArray  colors      = generateColors(object);
611
    JSONObject solved      = generateSolved(object);
612

    
613
    json.put("major"       , VERSION_OBJECT_MAJOR);
614
    json.put("minor"       , VERSION_OBJECT_MINOR);
615
    json.put("metadata"    , metadata);
616
    json.put("mesh"        , mesh);
617
    json.put("axis"        , axis);
618
    json.put("quats"       , quats);
619
    json.put("scrambling"  , scrambling);
620
    json.put("touchcontrol", touchControl);
621
    json.put("colors"      , colors);
622
    json.put("solved"      , solved);
623

    
624
    return json.toString();
625
    }
626

    
627
///////////////////////////////////////////////////////////////////////////////////////////////////
628

    
629
  public String createExtrasString(TwistyObject object) throws JSONException
630
    {
631
    String[][] tuts = object.getTutorials();
632

    
633
    if( tuts!=null )
634
      {
635
      JSONObject json = new JSONObject();
636
      JSONArray  tutorials = new JSONArray();
637

    
638
      for(String[] tut : tuts)
639
        {
640
        String language = tut[0];
641
        String link     = tut[1];
642
        String title    = tut[2];
643
        String author   = tut[3];
644

    
645
        JSONObject oneTut = new JSONObject();
646

    
647
        oneTut.put("language", language);
648
        oneTut.put("link"    , link    );
649
        oneTut.put("title"   , title   );
650
        oneTut.put("author"  , author  );
651

    
652
        tutorials.put(oneTut);
653
        }
654

    
655
      json.put("major"     , VERSION_EXTRAS_MAJOR);
656
      json.put("minor"     , VERSION_EXTRAS_MINOR);
657
      json.put("object"    , object.getShortName() );
658
      json.put("tutorials" , tutorials);
659

    
660
      return json.toString();
661
      }
662

    
663
    return null;
664
    }
665

    
666
///////////////////////////////////////////////////////////////////////////////////////////////////
667

    
668
  public void write(String filename, String contents) throws IOException
669
    {
670
    OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
671
    BufferedWriter bw = new BufferedWriter(osw);
672
    bw.write(contents);
673
    bw.flush();
674
    }
675

    
676
///////////////////////////////////////////////////////////////////////////////////////////////////
677

    
678
  public static JsonWriter getInstance()
679
    {
680
    if( mThis==null ) mThis = new JsonWriter();
681
    return mThis;
682
    }
683
}
(2-2/2)